JavaScript       Programming the WWWSaturday, December 15, 12
Agenda                  Key Concepts                  Core Types                  Syntax                  The Global Objec...
History             1995 Brendan Eich started             developing a new language             for Netscape Navigator 2.0...
JavaScript Key Ideas                  Interpreter based (no compilation)                  Loosely typed language          ...
JavaScript Key Ideas                  Interpreter based (no compilation)                  Loosely typed language          ...
JavaScript Key Ideas                  Interpreter based (no compilation)                  Loosely typed language          ...
Hello JavaScript                             Define and initialize a variable called ‘text’ with                           ...
Hello JavaScript                  var text = “Hello World”;                  console.log(text);     Call the log function ...
Hello JavaScript                              Define and initialize a variable called ‘text’ with                          ...
Running JavaScript                  Easy way: jsbin                  Completely offline using node.js                  Using...
Demo             JavaScript Basic SyntaxSaturday, December 15, 12
JavaScript Core Types                  Numbers                  Strings                  Booleans                  null   ...
Numbers                  JavaScript has only one number type called                  number                  number is a 6...
Numeric Functions                  Number(string)                            converts string to number                    ...
Numeric Functions                      x = 3;                      y = Number(7);                      z = Number(‘9’);   ...
Q&A                  Numbers                  Strings                  Booleans                  null                  und...
Strings                  Strings are unicode 16-bit chars (like in Java).                  No char class. Characters are s...
String Examples                   hello.length          === 5                   String(10).length       === 2             ...
Lab                  http://ynonperek.com/javascript-exer.html                  Exercises 1-5Saturday, December 15, 12
Q&A                  Numbers                  Strings                  Booleans                  null                  und...
Boolean Type                  JavaScript supports ‘true’ and ‘false’ as boolean                  values                  B...
null                  represents the "nothing" of JavaScript                  usually used to mark errors                 ...
undefined                  Not even the nothing                  JavaScript puts undefined in anything that hasnt           ...
JavaScript False/True                  These are all falsy:                        false, null, undefined                  ...
Objects                  Everything else is an object                  An object is a collection of key/value pairs.      ...
Objects     name            Ynon Perek                                            var me = {                              ...
Q&A                  Numbers                  Strings                  Booleans                  null                  und...
Exercise                  Write a JS program that randomizes 3 numbers                  from 1 to 100, and prints their su...
JavaScript Syntax                  Identifiers                  Reserved Words                  Comments                  L...
JavaScript Identifiers                  Starts with a letter, an _, or a $                  Followed by letters, digits, _ ...
Naming Conventions                  variable names are lowercased                  multiple words are separated by _ in va...
Identifier Examples                  counter                  file_name                  function getName()                 ...
JavaScript Reserved                  Words                  abstract             boolean break byte             case catch...
JavaScript Comments                   // this is a valid line comment in Javascript                   /**                 ...
Syntax Q & A                  Identifiers                  Reserved Words                  Comments                  Loops ...
Loop Controls                  JavaScript has:                        while and do-while loops                        for ...
While Loop                  Syntax:                    while (expression) {                            statement;         ...
Do-while Loop                  Syntax:                   do {                     statement;                   } while (ex...
For Loop                     Syntax:                     for ( initialize; test; increment) {                       statem...
For Example                   var sum = 0;                   for ( var i=0; i < 10; ++i ) {                            sum...
For-in loop                  allows iterating through all the properties of an                  object                  Be...
Branches                  Syntax:                   if ( expression ) {                   }                   else if     ...
Exercise                  Write a JS that randomizes 3 number and prints                  the largest one                 ...
Syntax Q & A                  Identifiers                  Reserved Words                  Comments                  Loops ...
Functions & Scope                                             var text = Hello Scope;                  Outside all functio...
Functions & Scope                  A function is an object that is callable (meaning we                  can apply it to a...
Creating A Function                   function foo(x, y) {                     return x + y;                   }          ...
Functions & Scope                  Inside a function, a variable can be scoped with                  the keyword var      ...
Functions & Scope                  Best Practices:                        Write all code inside a function block          ...
Functions & Scope                  A function definition can appear “inside” another                  function             ...
Functions & Scope                  What is printed ? Why ?                   function Counter(max) {                     v...
Functions Q & ASaturday, December 15, 12
Objects                  An object is a collection of key/value pairs                  Objects are instantiated using the ...
Objects                   var pos = { x : 50; y : 10 };                   pos.move = function(dx, dy) {                   ...
Objects Exercise                  Create a person object with three fields:                        name: your name         ...
The this Keyword                  Inside a function, a special keyword named ‘this’                  is used to determine ...
Arrays                  Arrays represent ordered data in JavaScript                  Arrays are normal objects, so they ca...
Arrays                   var arr = [];                   arr.push(1, 2, 3); // add data                   arr.pop();      ...
Syntax Q & A                  Identifiers                  Reserved Words                  Comments                  Loops ...
DOM             Scripting             Using JS To Manipulate the             web page                                     ...
The DOM                  Stands for Document                                             div         HTML                 ...
The DOM                                     <p id="text"></p>                  Can use                  getElementById    ...
DOM Agenda                  jQuery Introduction                  Handling Events                  Writing a simple web    ...
The Facts                  Every browser is different. Really.                  W3 Standard                  Webkit        ...
Ajax Libraries                  Developer tools that wrap common functionality                  and create a standard     ...
jQuery Basics                                         Wrap a normal DOM          $(p).html(hello jQUery);   element inside...
jQuery Basics: Selectors                                          <p id="text"></p>                  Powerful element     ...
jQuery Actions                                  $(div#foo).addClass(wide);                  Each jQuery     $(div#foo).rem...
jQuery Actions Example                  Zebra stripe a table                  using jQuery                                ...
jQuery Events                  Define what to do when something happens                  in jQuery, “bind” a function to an...
jQuery Events                  document.ready   scroll                  click            select                  hover    ...
jQuery Demo                  Build a red spotter game                  Game should present the user with 4 colored        ...
jQuery API                  Other useful methods:                  attr - change an attribute value                  css -...
jQuery Lab                  Write a web application that splits the screen into                  four sections. Each click...
Q&ASaturday, December 15, 12
Thank You                  Ynon Perek                  ynonperek@yahoo.com                  ynonperek.comSaturday, Decembe...
Upcoming SlideShare
Loading in …5
×

02 JavaScript Syntax

3,460
-1

Published on

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
3,460
On Slideshare
0
From Embeds
0
Number of Embeds
5
Actions
Shares
0
Downloads
583
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

02 JavaScript Syntax

  1. 1. JavaScript Programming the WWWSaturday, December 15, 12
  2. 2. Agenda Key Concepts Core Types Syntax The Global Object & Scope Chain Function ObjectsSaturday, December 15, 12
  3. 3. History 1995 Brendan Eich started developing a new language for Netscape Navigator 2.0 Original name was LiveScript Announced on Dec 1995 as JavaScript 1996 Microsoft responded with JScriptSaturday, December 15, 12
  4. 4. JavaScript Key Ideas Interpreter based (no compilation) Loosely typed language Objects are just hash tablesSaturday, December 15, 12
  5. 5. JavaScript Key Ideas Interpreter based (no compilation) Loosely typed language Objects are just hash tablesSaturday, December 15, 12
  6. 6. JavaScript Key Ideas Interpreter based (no compilation) Loosely typed language Objects are just hash tablesSaturday, December 15, 12
  7. 7. Hello JavaScript Define and initialize a variable called ‘text’ with the string “Hello World” var text = “Hello World”; console.log(text);Saturday, December 15, 12
  8. 8. Hello JavaScript var text = “Hello World”; console.log(text); Call the log function from the console object on the variable ‘text’Saturday, December 15, 12
  9. 9. Hello JavaScript Define and initialize a variable called ‘text’ with the string “Hello World” var text = “Hello World”; console.log(text); Call the log function from the console object on the variable ‘text’Saturday, December 15, 12
  10. 10. Running JavaScript Easy way: jsbin Completely offline using node.js Using a simple HTML fileSaturday, December 15, 12
  11. 11. Demo JavaScript Basic SyntaxSaturday, December 15, 12
  12. 12. JavaScript Core Types Numbers Strings Booleans null undefined ObjectsSaturday, December 15, 12
  13. 13. Numbers JavaScript has only one number type called number number is a 64-bit floating point (double) Same arithmetical problems double have (0.1+0.2 ! =0.3) A special value NaN represents errorsSaturday, December 15, 12
  14. 14. Numeric Functions Number(string) converts string to number returns NaN on error parseInt(string, radix) converts string to number tries its best (so 7hello is OK) Math.random() returns a random between 0 and 1Saturday, December 15, 12
  15. 15. Numeric Functions x = 3; y = Number(7); z = Number(‘9’); console.log(x + y + z);Saturday, December 15, 12
  16. 16. Q&A Numbers Strings Booleans null undefined ObjectsSaturday, December 15, 12
  17. 17. Strings Strings are unicode 16-bit chars (like in Java). No char class. Characters are strings of length 1 Strings are immutable (like in Java) Both Single and Double quotes make a stringSaturday, December 15, 12
  18. 18. String Examples hello.length === 5 String(10).length === 2 hello.indexOf(l) === 2 hello.lastIndexOf(l)=== 3 hello.toUpperCase() === HELLOSaturday, December 15, 12
  19. 19. Lab http://ynonperek.com/javascript-exer.html Exercises 1-5Saturday, December 15, 12
  20. 20. Q&A Numbers Strings Booleans null undefined ObjectsSaturday, December 15, 12
  21. 21. Boolean Type JavaScript supports ‘true’ and ‘false’ as boolean values Boolean(value) is a function returning the truthness of a value returns false if value is falsy, and true if value is truthy !!value has the same meaningSaturday, December 15, 12
  22. 22. null represents the "nothing" of JavaScript usually used to mark errors JavaScript will not give null to a variable. Its always the result of an assignment performed on purposeSaturday, December 15, 12
  23. 23. undefined Not even the nothing JavaScript puts undefined in anything that hasnt yet been assigned a valueSaturday, December 15, 12
  24. 24. JavaScript False/True These are all falsy: false, null, undefined “” (the empty string) 0, NaN Everything else is truthySaturday, December 15, 12
  25. 25. Objects Everything else is an object An object is a collection of key/value pairs. Objects are fully dynamic, so new methods and fields can be added at runtime Objects have no classes Each object has a prototype. Well talk about that later.Saturday, December 15, 12
  26. 26. Objects name Ynon Perek var me = {    name  : Ynon Perek,    email : ynonperek@yahoo.com, email ynonperek@yahoo.com    web   : http://ynonperek.com };  web http://ynonperek.comSaturday, December 15, 12
  27. 27. Q&A Numbers Strings Booleans null undefined ObjectsSaturday, December 15, 12
  28. 28. Exercise Write a JS program that randomizes 3 numbers from 1 to 100, and prints their sum total Write a JS function that takes two values and returns their sum. If it got only one, it should return that numberSaturday, December 15, 12
  29. 29. JavaScript Syntax Identifiers Reserved Words Comments Loops and Branches Functions Objects & ArraysSaturday, December 15, 12
  30. 30. JavaScript Identifiers Starts with a letter, an _, or a $ Followed by letters, digits, _ or $Saturday, December 15, 12
  31. 31. Naming Conventions variable names are lowercased multiple words are separated by _ in variable names multiple words are camel cased in function names A constructor function starts with a captialSaturday, December 15, 12
  32. 32. Identifier Examples counter file_name function getName() function Person()Saturday, December 15, 12
  33. 33. JavaScript Reserved Words abstract boolean break byte case catch char class const continue debugger default delete do double else enum export extends false final finally float for function goto if implements import in instanceof int interface long native new null package private protected public return short static super switch synchronized this throw throws transient true try typeof var volatile void while withSaturday, December 15, 12
  34. 34. JavaScript Comments // this is a valid line comment in Javascript /** * Java style multi line comments work well also * they are recommended for commenting on functions */Saturday, December 15, 12
  35. 35. Syntax Q & A Identifiers Reserved Words Comments Loops and Branches Functions Objects & ArraysSaturday, December 15, 12
  36. 36. Loop Controls JavaScript has: while and do-while loops for loops for-in loopsSaturday, December 15, 12
  37. 37. While Loop Syntax: while (expression) { statement; }Saturday, December 15, 12
  38. 38. Do-while Loop Syntax: do { statement; } while (expression); Note the ending semicolonSaturday, December 15, 12
  39. 39. For Loop Syntax: for ( initialize; test; increment) { statement; }Saturday, December 15, 12
  40. 40. For Example var sum = 0; for ( var i=0; i < 10; ++i ) { sum += i; } console.log(sum);Saturday, December 15, 12
  41. 41. For-in loop allows iterating through all the properties of an object Be careful with this one - it yields wrong results when combined with inheritanceSaturday, December 15, 12
  42. 42. Branches Syntax: if ( expression ) { } else if ( something_else ) { } else { }Saturday, December 15, 12
  43. 43. Exercise Write a JS that randomizes 3 number and prints the largest one Write a JS that prints the square-sum of all the numbers divisible by 7 in range 1..100 (1^2 + 7^2 + 14^2 + ...)Saturday, December 15, 12
  44. 44. Syntax Q & A Identifiers Reserved Words Comments Loops and Branches Functions Objects & ArraysSaturday, December 15, 12
  45. 45. Functions & Scope var text = Hello Scope; Outside all functions,   var sum = 0; variables have the   “global” scope. for ( var i=0; i < 10; i++ ) {   sum += i;   } Count how many   globals are on the right console.log( sum );Saturday, December 15, 12
  46. 46. Functions & Scope A function is an object that is callable (meaning we can apply it to arguments) In JavaScript, we have two ways to declare a function. Either as a named function or an anonymous function A function can return a value by using the return keywordSaturday, December 15, 12
  47. 47. Creating A Function function foo(x, y) {   return x + y; } var bar = function(x, y) {   return x + y; };Saturday, December 15, 12
  48. 48. Functions & Scope Inside a function, a variable can be scoped with the keyword var Using strict mode, all variables must be defined var This helps prevent bugs because we are less likely to mess with outside codeSaturday, December 15, 12
  49. 49. Functions & Scope Best Practices: Write all code inside a function block Use only one var statement at the beginning of that functionSaturday, December 15, 12
  50. 50. Functions & Scope A function definition can appear “inside” another function This is called a “closure”, and then the inner function has access to all variables defined by the outer “closing” function It also keeps all variables aliveSaturday, December 15, 12
  51. 51. Functions & Scope What is printed ? Why ? function Counter(max) {   var val = 0;   return function() { return (val < max) ? val++ : false; }; } var c = Counter(10); while (c()) {   console.log(c()); }Saturday, December 15, 12
  52. 52. Functions Q & ASaturday, December 15, 12
  53. 53. Objects An object is a collection of key/value pairs Objects are instantiated using the object literal Properties stored in objects are fetched using the square bracket notation or the dot notationSaturday, December 15, 12
  54. 54. Objects var pos = { x : 50; y : 10 }; pos.move = function(dx, dy) { this.x += dx; this.y += dy; };Saturday, December 15, 12
  55. 55. Objects Exercise Create a person object with three fields: name: your name favorite_color: your favorite color hello: a function that prints out your name and favorite colorSaturday, December 15, 12
  56. 56. The this Keyword Inside a function, a special keyword named ‘this’ is used to determine the function calling context When a function was called as a method, this refers to the calling object Otherwise, this refers to the global objectSaturday, December 15, 12
  57. 57. Arrays Arrays represent ordered data in JavaScript Arrays are normal objects, so they can have attributes other than their indexes Arrays have some array related functions we can useSaturday, December 15, 12
  58. 58. Arrays var arr = []; arr.push(1, 2, 3); // add data arr.pop(); // returns 3 arr[0] = 5; // changes array console.log(arr[2]); // value atSaturday, December 15, 12
  59. 59. Syntax Q & A Identifiers Reserved Words Comments Loops and Branches Functions Objects & ArraysSaturday, December 15, 12
  60. 60. DOM Scripting Using JS To Manipulate the web page http://www.flickr.com/photos/jram23/3088840966/Saturday, December 15, 12
  61. 61. The DOM Stands for Document div HTML Object Model Every HTML element has a JS object “bound” to it in a special bond HTMLDivElement JSSaturday, December 15, 12
  62. 62. The DOM <p id="text"></p> Can use getElementById to find a specific var t = document.getElementById(text); element t.innerHTML = "Hello World"; Can use getElementsByTagNam e to get all elements with a specified nameSaturday, December 15, 12
  63. 63. DOM Agenda jQuery Introduction Handling Events Writing a simple web appSaturday, December 15, 12
  64. 64. The Facts Every browser is different. Really. W3 Standard Webkit Mozilla MicrosoftSaturday, December 15, 12
  65. 65. Ajax Libraries Developer tools that wrap common functionality and create a standard Many options to choose from. We’ll use jQuerySaturday, December 15, 12
  66. 66. jQuery Basics Wrap a normal DOM $(p).html(hello jQUery); element inside a jQuery object <p></p> All operations on the element are performed by jQuery Unified and cross browser APISaturday, December 15, 12
  67. 67. jQuery Basics: Selectors <p id="text"></p> Powerful element selection and manipulations $(p#text).html("Hello World"); Works “the same” for all mobile & desktop browsers Selector returning a jQuery Object An action to perform on the objectSaturday, December 15, 12
  68. 68. jQuery Actions $(div#foo).addClass(wide); Each jQuery $(div#foo).removeClass(wide); object $(div#foo).css(background, red); supports a wide range of $(div#foo).hide(); functions to $(div#foo).show();     alter the elementsSaturday, December 15, 12
  69. 69. jQuery Actions Example Zebra stripe a table using jQuery $(table tr:nth-child(2n)).css(background, #ccc);Saturday, December 15, 12
  70. 70. jQuery Events Define what to do when something happens in jQuery, “bind” a function to an event After the bind, every time the the event happens your callback is called, with the object as the “this” argumentSaturday, December 15, 12
  71. 71. jQuery Events document.ready scroll click select hover submit keypress Full list: http:// mousemove api.jquery.com/ category/events/ resizeSaturday, December 15, 12
  72. 72. jQuery Demo Build a red spotter game Game should present the user with 4 colored squares, only one is red User should click on the red squareSaturday, December 15, 12
  73. 73. jQuery API Other useful methods: attr - change an attribute value css - change a style attribute html - change innerHTML content data - store arbitrary data inside an elementSaturday, December 15, 12
  74. 74. jQuery Lab Write a web application that splits the screen into four sections. Each click on a section should display a sentence inside the clicked section Write a web app to convert time units. User should enter time in seconds, minutes or hours, and convert to all the others Use HTML5 Boilerplate and jQuerySaturday, December 15, 12
  75. 75. Q&ASaturday, December 15, 12
  76. 76. Thank You Ynon Perek ynonperek@yahoo.com ynonperek.comSaturday, December 15, 12

×