JavaScriptA Primer In Far Too Many Parts
History
Mocha                     April 1995    LiveScript                                  JavaScriptBrendan EichCTO, Mozilla Corp.
JScriptJavaScript         ECMAScript                       ActionScript
Basics
Data Types• number• string• boolean• object• null• NaN• undefined
Strings• Are Objects, have methods
Strings"Foo" + "Bar";        //"FooBar"var str = "Lorem Ipsum Dolor Sit Amet";str.toLowerCase();    //"lorem ipsum dolor s...
String to NumberparseInt("56");        //56parseInt("42.567");    //42parseInt("asdf");      //NaNparseInt("5a6");       /...
Objects• “Dictionary” / “Associative Array”• Key: Value or Key: Value  • Without : A-Z0-9 only• Does not keep intrinsic or...
Objectsvar object = {    foo: value,    complex key: 0,    bar: {        nested: true    }};object.foo;                //v...
in or hasOwnProperty()• Tough call:  • .hasOwnProperty() more consistent  • in checks inherited properties     • Used in f...
invar test   = {    foo:   value,    bar:   value,    baz:   value}for (var key in test) {    console.log(key + ": " + tes...
Arrays• Special object• Numerical keys only• Keeps intrinsic ordering• Short ([]) and Long (new Array()) syntax
Arraysvar arrayShort = [    one,    two];arrayShort[2] = three;var arrayLong = new Array();arrayLong[0] = one;arrayLong[1]...
Arraysvar arr = [1,2,3,4,6];arr.indexOf(2);     //1arr.join(:);      //"1:2:3:4:6"arr.pop();          //6//[1,2,3,4]arr.pu...
Arraysvar arr1 = [1,2,3];var arr2 = [3,4,5];arr1.concat(arr2);    //[1,2,3,3,4,5]
Functions• Are Objects as well• “Elevated”  • You can use a named function before it is    defined in code  • Function defin...
Functionsfunction Foo() {    //...}Foo(); //validBar(); //validfunction Bar() {    //...}
Functionsfunction Foo() {}Foo.bar = "value";bar in Foo;       //trueFoo.bar == "value"; //true
Function Arguments• No way to assign default arguments• But arguments are not required  • If an argument is not specified, ...
arguments• A special variable found inside a function• A not-quite array object containing all the function arguments
argumentsfunction sum() {    var x = 0;    for (var i = 0; i < arguments.length; ++i) {        x += arguments[i];    }    ...
typeof• Determines a variables type• Returns a string
typeoftypeof   true;        //"boolean"typeof   12;          //"number"typeof   "string";    //"string"typeof   [];       ...
Comparison• a == b / a != b  • A and B compared by value alone  • 1 == “1” evaluates to true• a === b / a !== b  • A and B...
window, document• Built in, global, Objects• window  • Provides access to the browser window  • The “global” object: foo =...
Scoping
Global & Local• Functions are the only way to create new scopes• Variables defined with var are local• Variables defined wit...
Global & Localvar outerScope = 10;var outerScope2 = 10;function Foo() {    var outerScope   =   20;    var innerScope   = ...
Lexical Scopingfunction Foo() {              function Foo() {    var baz = 1;                  var baz = 1;    return Bar(...
Closures
Closures• First-Class  • Can assign functions to variables, pass as     arguments and return as values• Anonymous  • Not r...
Closuresfunction Foo() {    var count = 0;    return function() {        count = count + 1;        return count;    };}var...
Closuresfunction createAdder(amount) {    return function(input) {        return input + amount;    };}var add2 = createAd...
Module Pattern   (function(exports, undefined){       //ALL your code here       var localVar = "bar"       globalVar    =...
this
this• Trips everyone up• Special variable used within a function• Refers to the “contextual object”• Changes based on wher...
thisvar Foo = {    bar: "bar",    baz: function() {        return this.bar;    }};Foo.baz(); //"bar"Foo.bar = "bat";Foo.ba...
thisvar Foo = {    bar: "bar",    baz: function() {        return this.bar;    }};Foo.bat = function() {    return this.ba...
call & apply• Methods in the function prototype• Change the context in which a function executes!
call & applyvar Foo = {    bar: "bar",    baz = function(param1, param2) {        return this.bar + param1 + param2;    }}...
Exceptions
Exceptions• All errors are thrown• Classic try...catch...finally blocks
Exceptionstry {    funcDoesNotExist();} catch (e) {    alert(e); //ReferenceError: funcDoesNotExist is not defined} finall...
Exceptionsfunction Foo() {    throw new Error("Message");}function Bar() {    throw "Message";}try {    Foo();} catch (e) ...
Prototype
OOP... Kinda...• Almost no real difference between a dictionary and an object• Named Functions double as object constructor...
OOP... Kinda...                                   Foofunction Foo() {    //The "Constructor"}                             ...
new                                 instancevar instance = new Foo();instance.baz();      //worksinstance.bar();      //er...
new                                 instanceinstance.bat = function() {    /* ... */}                                 ‣ ba...
Overriding Prototypefunction Foo(baz) {    this.baz = baz;}Foo.prototype.bar = function() {    return this.baz;};var foo1 ...
Asynchronous
Asynchronous• setTimeout, setInterval allow you to have code executing asynchronously while other code executes
setIntervalvar id = setInterval(function() {    //Code to execute every 1000 milliseconds}, 1000);//clearInterval(id); to ...
setTimeoutvar id = setTimeout(function() {    //Code to execute after 1000 milliseconds have passed}, 1000);//clearTimeout...
Nifty TricksetTimeout(function() {    //Code to run in parallel    //while the code after is    //executed.}, 1);//Code he...
DOM
DOM• Document Object Model• API to interact with the HTML/XHTML document
DOMvar paragraph = document.createElement(p);var content = document.createTextNode("Lorem Ipsum");paragraph.appendChild(co...
JSON
2001   JSONDouglas Crockford     Awesome
JSON• JavaScript Object Notation• Serialization format that is basically JavaScript code minus comments• Can be eval()’ed•...
JSON{"menu": {                                <menu id="file" value="File">   "id": "file",                            <po...
jQuery
January 2006   jQueryJohn ResigAuthor, jQuery
jQuery• Cross-browser JavaScript library• Simplifies and normalizes DOM, AJAX, etc.• Centers around using extended CSS sele...
jQuery$("div").addClass("special");                                Find all div tags                                Add cl...
jQuery$("#foo")                              <div id="foo"></div>  .html("<strong>bar</strong> baz");                     ...
jQuery$(img.preview).hide();$(.button).click(function(){   •Hide all images with});    $(img.preview).show();     the clas...
Animation$(.button).click(function(){    $(img.preview)                                     When .button is clicked,      ...
Events• jQuery wraps an event handling system• Handles browser events, AJAX events, and custom events
Events$(document).ready(function() {    //Only execute when the document fires    //its onready event (page is done loadin...
Events$(img).hover(function(){    //Do something when user hovers over    //any img tag});
AJAX• Asynchronous JavaScript And XML  • Though never use XML, use JSON• jQuery has an AJAX library• Wraps all the differen...
AJAX$.ajax({  url: "test.php",  success: function(data){      $(div.status).addClass("done")                     .html(dat...
Resourceshttp://api.jquery.com/
Tools
Chrome/Safari Devel. Tools
Firefox FireBug
JavaScript Primer
JavaScript Primer
Upcoming SlideShare
Loading in...5
×

JavaScript Primer

1,704

Published on

A primer for JavaScript that covers from basic variable definition to scoping, "this", and a brief foray into the DOM and jQuery.

Published in: Technology, Design
1 Comment
1 Like
Statistics
Notes
No Downloads
Views
Total Views
1,704
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
29
Comments
1
Likes
1
Embeds 0
No embeds

No notes for slide

JavaScript Primer

  1. 1. JavaScriptA Primer In Far Too Many Parts
  2. 2. History
  3. 3. Mocha April 1995 LiveScript JavaScriptBrendan EichCTO, Mozilla Corp.
  4. 4. JScriptJavaScript ECMAScript ActionScript
  5. 5. Basics
  6. 6. Data Types• number• string• boolean• object• null• NaN• undefined
  7. 7. Strings• Are Objects, have methods
  8. 8. Strings"Foo" + "Bar"; //"FooBar"var str = "Lorem Ipsum Dolor Sit Amet";str.toLowerCase(); //"lorem ipsum dolor sit amet"str.toUpperCase(); //"LOREM IPSUM DOLOR SIT AMET"str.split(" "); //["Lorem", "Ispum", "Dolor", "Sit", "Amet"]str.substring(6,9); //"Ips"new String("Lorem Ipsum Dolor Sit Amet") == str; //true
  9. 9. String to NumberparseInt("56"); //56parseInt("42.567"); //42parseInt("asdf"); //NaNparseInt("5a6"); //5parseFloat("24.68"); //24.68parseFloat("asdf"); //NaNparseFloat("24a"); //24
  10. 10. Objects• “Dictionary” / “Associative Array”• Key: Value or Key: Value • Without : A-Z0-9 only• Does not keep intrinsic ordering• Accessed keys using . (dot) or [] notation
  11. 11. Objectsvar object = { foo: value, complex key: 0, bar: { nested: true }};object.foo; //valueobject.[complex key]; //0object.bar.nested; //trueobject.bar[nested]; //trueobject[bar].nested; //trueobject[bar][nested]; //true
  12. 12. in or hasOwnProperty()• Tough call: • .hasOwnProperty() more consistent • in checks inherited properties • Used in for loop
  13. 13. invar test = { foo: value, bar: value, baz: value}for (var key in test) { console.log(key + ": " + test[key]);}//PRINTS://foo: value//bar: value//baz: value
  14. 14. Arrays• Special object• Numerical keys only• Keeps intrinsic ordering• Short ([]) and Long (new Array()) syntax
  15. 15. Arraysvar arrayShort = [ one, two];arrayShort[2] = three;var arrayLong = new Array();arrayLong[0] = one;arrayLong[1] = two;arrayLong[2] = three;//arrayShort: ["one", "two", "three"]//arrayLong: ["one", "two", "three"]
  16. 16. Arraysvar arr = [1,2,3,4,6];arr.indexOf(2); //1arr.join(:); //"1:2:3:4:6"arr.pop(); //6//[1,2,3,4]arr.push(7); //5//[1,2,3,4,7]arr.reverse(); //[7,4,3,2,1]arr.shift(); //1//[2,3,4,7]arr.unshift(8); //5//[8,2,3,4,7]arr.slice(1); //[2,3,4,7]arr.slice(1,3); //[2,3]arr.slice(-3); //[3,4,7]arr.slice(-3,-1); //[3,4]
  17. 17. Arraysvar arr1 = [1,2,3];var arr2 = [3,4,5];arr1.concat(arr2); //[1,2,3,3,4,5]
  18. 18. Functions• Are Objects as well• “Elevated” • You can use a named function before it is defined in code • Function definitions are elevated to the top
  19. 19. Functionsfunction Foo() { //...}Foo(); //validBar(); //validfunction Bar() { //...}
  20. 20. Functionsfunction Foo() {}Foo.bar = "value";bar in Foo; //trueFoo.bar == "value"; //true
  21. 21. Function Arguments• No way to assign default arguments• But arguments are not required • If an argument is not specified, it is set to undefined
  22. 22. arguments• A special variable found inside a function• A not-quite array object containing all the function arguments
  23. 23. argumentsfunction sum() { var x = 0; for (var i = 0; i < arguments.length; ++i) { x += arguments[i]; } return x;}sum(1, 2, 3); //6
  24. 24. typeof• Determines a variables type• Returns a string
  25. 25. typeoftypeof true; //"boolean"typeof 12; //"number"typeof "string"; //"string"typeof []; //"object"typeof {}; //"object"typeof NaN; //"number"typeof null; //"object"typeof undefined; //"undefined"function Foo() {}typeof Foo; //"function"
  26. 26. Comparison• a == b / a != b • A and B compared by value alone • 1 == “1” evaluates to true• a === b / a !== b • A and B compared by value and by type • 1 === “1” evaluates to false
  27. 27. window, document• Built in, global, Objects• window • Provides access to the browser window • The “global” object: foo === window.foo • Things like window.location.href, etc• document • Provides access to the current DOM
  28. 28. Scoping
  29. 29. Global & Local• Functions are the only way to create new scopes• Variables defined with var are local• Variables defined without var are global• Global variables are members of window
  30. 30. Global & Localvar outerScope = 10;var outerScope2 = 10;function Foo() { var outerScope = 20; var innerScope = 20; globalVariable = 30; outerScope2 = 40;}Foo();alert(outerScope); //10alert(outerScope2); //40alert(innerScope); //erroralert(globalVariable); //30
  31. 31. Lexical Scopingfunction Foo() { function Foo() { var baz = 1; var baz = 1; return Bar();} function Bar() { return baz;function Bar() { } return baz;} return Bar(); }Foo(); //baz is not defined Foo(); //1
  32. 32. Closures
  33. 33. Closures• First-Class • Can assign functions to variables, pass as arguments and return as values• Anonymous • Not required to have a name• A function that “closes over” variables defined outside itself
  34. 34. Closuresfunction Foo() { var count = 0; return function() { count = count + 1; return count; };}var bar = Foo();bar(); //1bar(); //2bar(); //3
  35. 35. Closuresfunction createAdder(amount) { return function(input) { return input + amount; };}var add2 = createAdder(2);add2(2); //4add2(8); //10var add3 = createAdder(3);add3(3); //6add3(7); //10
  36. 36. Module Pattern (function(exports, undefined){ //ALL your code here var localVar = "bar" globalVar = "baz"; exports.foo = "bat"; })(window); alert(localVar); //error alert(globalVar); //"baz" alert(window.globalVar); //"baz" alert(foo); //"bat" alert(window.foo); //"bat"BEWARE: export (singular) is a reserved word in Safari
  37. 37. this
  38. 38. this• Trips everyone up• Special variable used within a function• Refers to the “contextual object”• Changes based on where a function executes
  39. 39. thisvar Foo = { bar: "bar", baz: function() { return this.bar; }};Foo.baz(); //"bar"Foo.bar = "bat";Foo.baz(); //"bat"var baz = Foo.baz;baz(); //undefined
  40. 40. thisvar Foo = { bar: "bar", baz: function() { return this.bar; }};Foo.bat = function() { return this.bar + "bat";};Foo.bat(); //"barbat"
  41. 41. call & apply• Methods in the function prototype• Change the context in which a function executes!
  42. 42. call & applyvar Foo = { bar: "bar", baz = function(param1, param2) { return this.bar + param1 + param2; }};var Foo2 = { bar: "123"};Foo.baz("baz", "bat"); //"barbazbat"Foo.baz.apply(Foo2, "baz", "bat"); //"123bazbat"Foo.baz.call(Foo2, ["baz", "bat"]); //"123bazbat"
  43. 43. Exceptions
  44. 44. Exceptions• All errors are thrown• Classic try...catch...finally blocks
  45. 45. Exceptionstry { funcDoesNotExist();} catch (e) { alert(e); //ReferenceError: funcDoesNotExist is not defined} finally { //Always Executes}
  46. 46. Exceptionsfunction Foo() { throw new Error("Message");}function Bar() { throw "Message";}try { Foo();} catch (e) { e.message == "Message"; //true}try { Bar();} catch (e) { e == "Message"; //true}
  47. 47. Prototype
  48. 48. OOP... Kinda...• Almost no real difference between a dictionary and an object• Named Functions double as object constructors• Function objects contain a prototype dictionary that is copied to instance when using new
  49. 49. OOP... Kinda... Foofunction Foo() { //The "Constructor"} ‣ barFoo.bar = function() { //A "Static" Function ‣ prototype} ‣ bazFoo.prototype.baz = function() { ‣ constructor //A "Method"}; ‣ __proto__
  50. 50. new instancevar instance = new Foo();instance.baz(); //worksinstance.bar(); //error ‣ __proto__Foo.bar(); //works ‣ bazFoo.baz(); //error ‣ constructorFoo.prototype.baz(); //works ‣ __proto__ ‣ ...
  51. 51. new instanceinstance.bat = function() { /* ... */} ‣ batinstance.bat(); //works ‣ __proto__Foo.bat(); //error ‣ bazFoo.prototype.bat(); //error ‣ constructor ‣ __proto__ ‣ ...
  52. 52. Overriding Prototypefunction Foo(baz) { this.baz = baz;}Foo.prototype.bar = function() { return this.baz;};var foo1 = new Foo(1);var foo2 = new Foo(2);foo1.bar(); //1foo2.bar(); //2Foo.prototype.bar = function() { return this.baz * 2;};foo1.bar(); //2foo2.bar(); //4
  53. 53. Asynchronous
  54. 54. Asynchronous• setTimeout, setInterval allow you to have code executing asynchronously while other code executes
  55. 55. setIntervalvar id = setInterval(function() { //Code to execute every 1000 milliseconds}, 1000);//clearInterval(id); to stop
  56. 56. setTimeoutvar id = setTimeout(function() { //Code to execute after 1000 milliseconds have passed}, 1000);//clearTimeout(id); to cancel
  57. 57. Nifty TricksetTimeout(function() { //Code to run in parallel //while the code after is //executed.}, 1);//Code here will execute immediately//without waiting on the above
  58. 58. DOM
  59. 59. DOM• Document Object Model• API to interact with the HTML/XHTML document
  60. 60. DOMvar paragraph = document.createElement(p);var content = document.createTextNode("Lorem Ipsum");paragraph.appendChild(content);paragraph.classList.add(my-class);document.getElementsByTagName(body)[0].appendChild(paragraph);
  61. 61. JSON
  62. 62. 2001 JSONDouglas Crockford Awesome
  63. 63. JSON• JavaScript Object Notation• Serialization format that is basically JavaScript code minus comments• Can be eval()’ed• Minimal overhead compared to XML • No advanced parsers needed
  64. 64. JSON{"menu": { <menu id="file" value="File"> "id": "file", <popup> "value": "File", <menuitem value="New" "popup": { onclick="CreateNewDoc()" /> "menuitem": [ <menuitem value="Open" {"value": "New", onclick="OpenDoc()" /> "onclick": "CreateNewDoc()"}, <menuitem value="Close" {"value": "Open", onclick="CloseDoc()" /> "onclick": "OpenDoc()"}, </popup> {"value": "Close", </menu> "onclick": "CloseDoc()"} ] }}}
  65. 65. jQuery
  66. 66. January 2006 jQueryJohn ResigAuthor, jQuery
  67. 67. jQuery• Cross-browser JavaScript library• Simplifies and normalizes DOM, AJAX, etc.• Centers around using extended CSS selectors to grab an element(s)
  68. 68. jQuery$("div").addClass("special"); Find all div tags Add class special
  69. 69. jQuery$("#foo") <div id="foo"></div> .html("<strong>bar</strong> baz"); <div id="foo"> <strong>bar</strong> baz </div>
  70. 70. jQuery$(img.preview).hide();$(.button).click(function(){ •Hide all images with}); $(img.preview).show(); the class preview •When element with the class button is clicked, show all images with the class preview
  71. 71. Animation$(.button).click(function(){ $(img.preview) When .button is clicked, .fadeOut(600, function() { fade out img.preview $(this).remove(); }); over 600 milliseconds}); and then remove it from the DOM
  72. 72. Events• jQuery wraps an event handling system• Handles browser events, AJAX events, and custom events
  73. 73. Events$(document).ready(function() { //Only execute when the document fires //its onready event (page is done loading)});$(document).bind(ready, function() { //Equivalent to the above});
  74. 74. Events$(img).hover(function(){ //Do something when user hovers over //any img tag});
  75. 75. AJAX• Asynchronous JavaScript And XML • Though never use XML, use JSON• jQuery has an AJAX library• Wraps all the different browser quirks • IE is weird
  76. 76. AJAX$.ajax({ url: "test.php", success: function(data){ $(div.status).addClass("done") .html(data); }});
  77. 77. Resourceshttp://api.jquery.com/
  78. 78. Tools
  79. 79. Chrome/Safari Devel. Tools
  80. 80. Firefox FireBug
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×