Fundamental JavaScript [UTC, March 2014]

5,929 views

Published on

A bit of an introduction to JavaScript for University of Tennessee at Chattanooga’s Web 2 students.

Published in: Technology
3 Comments
22 Likes
Statistics
Notes
No Downloads
Views
Total views
5,929
On SlideShare
0
From Embeds
0
Number of Embeds
1,350
Actions
Shares
0
Downloads
727
Comments
3
Likes
22
Embeds 0
No embeds

No notes for slide

Fundamental JavaScript [UTC, March 2014]

  1. 1. FUNDAMENTAL JAVASCRIPT Aaron Gustafson @AaronGustafson slideshare.net/AaronGustafson
  2. 2. Variables (i.e. buckets)
  3. 3. FUNDAMENTAL JAVASCRIPT Variables var my_var; var another_var, yet_another_var;
  4. 4. FUNDAMENTAL JAVASCRIPT Variables var MYVAR, myvar, myVar, MyVar, MyVaR;
  5. 5. FUNDAMENTAL JAVASCRIPT Variables: Scope function myFunc() { var my_var = false; } my_var; // undefined
  6. 6. Data Types (i.e. stuff that goes in buckets)
  7. 7. FUNDAMENTAL JAVASCRIPT Data type: Strings var single_quoted = 'my text', double_quoted = "more text"; var no_escape_necessary = 'some "text"', escaped = 'some 'text''; var numeric_string = '06517';
  8. 8. FUNDAMENTAL JAVASCRIPT Data type: Numbers var positive = 34, negative = -1, decimal = 3.14;
  9. 9. FUNDAMENTAL JAVASCRIPT Data type: Booleans var yes = true, no = false, also_yes = 1, // truthy also_no = 0; // falsey
  10. 10. FUNDAMENTAL JAVASCRIPT Data type: Arrays var my_cats = []; my_cats[0] = 'Sabine'; my_cats[1] = 'Dakota'; my_cats; // ['Sabine','Dakota']
  11. 11. FUNDAMENTAL JAVASCRIPT Data type: Arrays var sabine = [ 'Sabine', // 0 = name 'cat', // 1 = type 'female', // 2 = gender 17, // 3 = age true // 4 = spayed/neutered ]; sabine[2]; // 'female'
  12. 12. FUNDAMENTAL JAVASCRIPT Data type: Arrays var sabine = ['Sabine', 'cat', 'female', 14, true], dakota = ['Dakota', 'cat', 'male', 13, true]; pets = [ sabine, dakota ]; pets[1][0]; // 'Dakota'
  13. 13. FUNDAMENTAL JAVASCRIPT Data type: Hashes var sabine = []; sabine['name'] = 'Sabine'; sabine['type'] = 'cat'; sabine['gender'] = 'female'; sabine['age'] = 14; sabine['fixed'] = true; sabine; // [] sabine['name']; // 'Sabine' sabine.name; // 'Sabine'
  14. 14. FUNDAMENTAL JAVASCRIPT Data type: Objects var sabine = {}; sabine.name = 'Sabine'; sabine.type = 'cat'; sabine.gender = 'female'; sabine.age = 14; sabine.fixed = true; sabine; // Object sabine['name']; // 'Sabine' sabine.name; // 'Sabine'
  15. 15. Operators (i.e. telling JS what to do)
  16. 16. FUNDAMENTAL JAVASCRIPT Operators: Arithmetic var one = 2 - 1, two = 1 + 1, three = 9 / 3, four = 2 * 2, five = three + two;
  17. 17. FUNDAMENTAL JAVASCRIPT Operators: Concatenation 'This is a ' + 'string'; // 'This is a string'
  18. 18. FUNDAMENTAL JAVASCRIPT Operators: Shorthand var my_var = 1; my_var my_var my_var my_var += 2; // 3 -= 2; // 1 *= 2; // 2 /= 2; // 1 my_var++; my_var--; ++my_var; --my_var; // // // // 2 1 2 1 (after eval.) (after eval.) (before eval.) (before eval.)
  19. 19. FUNDAMENTAL JAVASCRIPT Operators: Comparison var my_var = 1; my_var my_var my_var my_var my_var my_var my_var my_var > 2; < 2; == 2; >= 2; <= 2; != 2; === 2; !== 2; // false // true // false // false // true // true // false // true
  20. 20. FUNDAMENTAL JAVASCRIPT Operators: Identity function isTrue( value ) { return value === true; } isTrue( isTrue( isTrue( isTrue( true ); // true false ); // false 1 ); // false 0 ); // false
  21. 21. FUNDAMENTAL JAVASCRIPT Operators: Logical if ( ! my_var ) { // my_var is false, null or undefined (not) } if ( my_var > 2 && my_var < 10 ) { // my_var is between 2 and 10 (exclusive) } if ( my_var > 2 || my_var < 2 ) { // my_var is greater or less than 2 // (i.e. my_var != 2) }
  22. 22. FUNDAMENTAL JAVASCRIPT Operators: Logical if ( ! ( my_var < 2 ) ) { // my_var is not less than 2 // (or my_var >= 2) } if ( ( my_var > 2 && my_var < 10 ) || my_var == 15 ) { // my_var is between 2 and 10 (exclusive) // or my_var is 15 }
  23. 23. FUNDAMENTAL JAVASCRIPT Data type: Dynamic typing var my_var = false; // boolean my_var = 14; // number my_var = "test"; // string my_var = []; // array my_var = {}; // object my_var = function(){}; // function
  24. 24. FUNDAMENTAL JAVASCRIPT Data type: Dynamic typing 'This is a ' + 'string'; // 'This is a string' 10 + '20'; // '1020'
  25. 25. Control Structures (i.e. conducting the symphony)
  26. 26. FUNDAMENTAL JAVASCRIPT Conditional Action if ( condition ) { statement ; }
  27. 27. FUNDAMENTAL JAVASCRIPT Semicolons: Use them first statement second statement
  28. 28. FUNDAMENTAL JAVASCRIPT Semicolons: Use them first statement second statement compression first statement second statement
  29. 29. FUNDAMENTAL JAVASCRIPT Semicolons: Use them first statement ; second statement ; compression first statement ; second statement ;
  30. 30. FUNDAMENTAL JAVASCRIPT Conditional Action if ( 1 > 2 ) { console.log( 'something is terribly wrong' ); }
  31. 31. FUNDAMENTAL JAVASCRIPT Conditional Action if ( 1 > 2 ) { console.log( 'something is terribly wrong' ); } else { console.log( 'everything is okay' ); }
  32. 32. FUNDAMENTAL JAVASCRIPT Conditional Action console.log( 1 > 2 ? 'something is terribly wrong' : 'everything is okay' );
  33. 33. FUNDAMENTAL JAVASCRIPT Conditional Action if ( height > 6 ) { console.log( 'you are tall' ); } else if ( height > 5.5 ) { console.log( 'you are of average height' ); } else { console.log( 'you are shorter than average' ); }
  34. 34. FUNDAMENTAL JAVASCRIPT Conditional Action var msg = 'You are '; switch ( true ) { case height > 6: msg += 'tall'; break; case height > 5.5: msg += 'of average height'; break; default: msg += 'shorter than average'; break; } console.log( msg );
  35. 35. FUNDAMENTAL JAVASCRIPT For Loops for ( initialization ; test condition ; alteration ) { statement ; }
  36. 36. FUNDAMENTAL JAVASCRIPT For Loops for ( var i=1; i<=10; i++ ) { console.log( i ); } // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
  37. 37. FUNDAMENTAL JAVASCRIPT For Loops for ( var i=1; i<=10; i++ ) { console.log( i ); } // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 var i = 1; for ( ; i<=10; ) { console.log( i++ ); } // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
  38. 38. FUNDAMENTAL JAVASCRIPT While Loops initialization ; while ( test condition ) { statement ; alteration ; }
  39. 39. FUNDAMENTAL JAVASCRIPT While Loops var i = 1; while ( i < 10 ) { console.log( i ); i += 2; } // 1, 3, 5, 7, 9 i; // 11
  40. 40. FUNDAMENTAL JAVASCRIPT While Loops var i = 11; while ( i > 10 ) { console.log( i++ ); } // infinite loop (condition is always met)
  41. 41. FUNDAMENTAL JAVASCRIPT While Loops var i = 10; while ( i ) { console.log( i-- ); } // 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
  42. 42. Functions (i.e. reusable bundles of logic)
  43. 43. FUNDAMENTAL JAVASCRIPT Functions function name( arguments ) { statements ; }
  44. 44. FUNDAMENTAL JAVASCRIPT Functions function isTrue( value ) { return value === true; } isTrue( isTrue( isTrue( isTrue( true ); // true false ); // false 1 ); // false 0 ); // false
  45. 45. FUNDAMENTAL JAVASCRIPT Functions function add( a, b ) { return a + b; } add( 1, 2 ); // 3 add( 4, 5 ); // 9 add( 1, 2, 3 ); // 3
  46. 46. FUNDAMENTAL JAVASCRIPT Functions function add( a, b, c ) { return a + b + c; } add( 1, 2 ); // Not a number (NaN) add( 4, 5 ); // NaN add( 1, 2, 3 ); // 6
  47. 47. FUNDAMENTAL JAVASCRIPT Functions function add( a, b, c ) { c = c || 0; return a + b + c; } add( 1, 2 ); // 3 add( 4, 5 ); // 9 add( 1, 2, 3 ); // 6
  48. 48. FUNDAMENTAL JAVASCRIPT Functions function add() { var total = 0, i = 0; while ( arguments[i] ) { total += arguments[i++]; } return total; } add( 1, 2 ); add( 1, 2, 3 ); add( 1, 2, 3, 8 ); // 3 // 6 // 14
  49. 49. FUNDAMENTAL JAVASCRIPT Functions function add() { var total = 0, i = 0; while ( arguments[i] ) { total += arguments[i++]; } return total; } add( add( add( add( 1, 1, 1, 1, 2 ); 2, 3 ); 2, 3, 8 ); 2, ‘foo’, 8 ); // 3 // 6 // 14 // 3foo8
  50. 50. FUNDAMENTAL JAVASCRIPT Functions function add() { var total = 0, i = 0; while ( arguments[i] ) { if ( typeof arguments[i] == 'number' ) { total += arguments[i]; } i++; } return total; } add( add( add( add( 1, 1, 1, 1, 2 ); 2, 3 ); 2, 3, 8 ); 2, ‘foo’, 8 ); // 3 // 6 // 14 // 11
  51. 51. FUNDAMENTAL JAVASCRIPT Variables: Scope function myFunc() { my_first_var = true; var my_second_var = false; } window.my_first_var; // undefined myFunc(); window.my_first_var; // true window.my_second_var; // undefined
  52. 52. FUNDAMENTAL JAVASCRIPT Variables: Scope function myFunc() { my_first_var = true; var my_second_var = false; } window.my_first_var; // undefined myFunc(); window.my_first_var; // true window.my_second_var; // undefined window.myFunc; // function
  53. 53. FUNDAMENTAL JAVASCRIPT Variables: Scope function Silly() { a = 10; return a *= 2; } var a = 10; a; Silly(); Silly(); a; // 10 // 20 // 20 // 20
  54. 54. FUNDAMENTAL JAVASCRIPT Variables: Scope function Silly() { var a = 10; return a *= 2; } var a = 10; a; Silly(); Silly(); a; // 10 // 20 // 20 // 10
  55. 55. FUNDAMENTAL JAVASCRIPT Variables: Scope function Silly() { return a *= 2; } var a = Silly(); Silly(); a; 10; // 20 // 40 // 40
  56. 56. FUNDAMENTAL JAVASCRIPT “Anonymous” Functions window.onload = function(){ // do something };
  57. 57. FUNDAMENTAL JAVASCRIPT “Anonymous” Functions (function(){ // do something }());
  58. 58. FUNDAMENTAL JAVASCRIPT “Anonymous” Functions ( // encapsulates some code );
  59. 59. FUNDAMENTAL JAVASCRIPT “Anonymous” Functions ( function(){ // defines an anonymous function } );
  60. 60. FUNDAMENTAL JAVASCRIPT “Anonymous” Functions ( function(){ }() // executes it immediately );
  61. 61. FUNDAMENTAL JAVASCRIPT “Anonymous” Functions (function(){ // do something }());
  62. 62. Objects (i.e. organizers)
  63. 63. FUNDAMENTAL JAVASCRIPT Objects var Foo = {};
  64. 64. FUNDAMENTAL JAVASCRIPT Objects var Foo = {}; Foo.value = ‘bar’; Foo.value; // ‘bar’
  65. 65. FUNDAMENTAL JAVASCRIPT Objects var Foo = {}; Foo.value = ‘bar’; Foo.doSomething = function(){ console.log( this.value ); }; Foo.doSomething(); // ‘bar’
  66. 66. FUNDAMENTAL JAVASCRIPT Almost everything’s an object var str_a = '1 2 3 4 5', str_b = '6 7 8 9'; str_a.length; str_a.concat( ' ', str_b ); str_a.indexOf( '1' ); str_a.lastIndexOf( ' ' ); // 9 // '1 2 3 4 5 6 7 8 9' // 0 // 7
  67. 67. FUNDAMENTAL JAVASCRIPT Almost everything’s an object var arr = [ 1, 2, 3, 4, 5 ]; arr.length; arr.join( ' ' ); // 5 // '1 2 3 4 5' arr.pop(); arr; // 5 // [ 1, 2, 3, 4 ] arr.push( 6 ); arr; // 5 (the new length) // [ 1, 2, 3, 4, 6 ] arr.reverse(); arr; // [ 6, 4, 3, 2, 1 ] arr.shift(); arr.unshift( 5 ); arr; // 6 // 5 (the new length) // [ 5, 4, 3, 2, 1 ]
  68. 68. The DOM (i.e. your HTML)
  69. 69. FUNDAMENTAL JAVASCRIPT HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset=”utf-8"> <title>Page Title</title> </head> <body> <h1>This is a heading</h1> <p>This is a paragraph with a <a href="http://blog.easy-designs.net">link</a>.</p> <ul> <li>a list item</li> <li>another list item</li> <li>a third list item</li> </ul> </body> </html>
  70. 70. FUNDAMENTAL JAVASCRIPT HTML html
  71. 71. FUNDAMENTAL JAVASCRIPT HTML html head meta title body h1 p ul a li li li
  72. 72. FUNDAMENTAL JAVASCRIPT HTML p this is a paragraph of text with a a href="http://blog.easy-designs.net" . link
  73. 73. Step 1: Find Stuff
  74. 74. FUNDAMENTAL JAVASCRIPT Find Stuff (in CSS) p { color: red; } #footer { border: 1px solid; } #footer p { color: black; }
  75. 75. FUNDAMENTAL JAVASCRIPT Find Stuff (in JS) document.getElementsByTagName( 'p' ); document.getElementById( 'footer' ); document.getElementById( 'footer' ) .getElementsByTagName( 'p' );
  76. 76. FUNDAMENTAL JAVASCRIPT Find Stuff (in jQuery) $( 'p' ); $( '#footer' ); $( '#footer p' );
  77. 77. FUNDAMENTAL JAVASCRIPT Find Stuff (in modern JS) document.querySelector( 'p' ); document.querySelector( '#footer' ); document.querySelector( '#footer p' );
  78. 78. FUNDAMENTAL JAVASCRIPT Libraries vs. Vanilla JS Write less code Write more code Don’t worry about browser differences Deal with browser issues More abstraction More explicit Extra Downloads Built-in Slower Faster 81
  79. 79. FUNDAMENTAL JAVASCRIPT Comparison Syntax document.getElementsByTagName( ‘p’ ) $( ‘p’ ) document.getElementById( ‘foo’ ) Operations/second 8,280,893 19,449 12,137,211 $( ‘#foo’ ) 350,557 document.querySelector( ‘ul.first’ ) 350,102 $( ‘ul.first’ ) 18,450
  80. 80. FUNDAMENTAL JAVASCRIPT Comparison Syntax Operations/second document.getElementsByTagName( ‘p’ ) 8,280,893 99.7% slower 19,449 $( ‘p’ ) document.getElementById( ‘foo’ ) $( ‘#foo’ ) 97.1% slower 12,137,211 350,557 document.querySelector( ‘ul.first’ ) 350,102 95% slower 18,450 $( ‘ul.first’ )
  81. 81. FUNDAMENTAL JAVASCRIPT Traversing a document var a = document.getElementsByTagName( 'a' ), a_len = a.length, i, title; for ( i=0; i < a_len; i++ ) { title = a[i].getAttribute( 'title' ); if ( title ) { console.log( title ); } }
  82. 82. FUNDAMENTAL JAVASCRIPT Traversing a document node node node node node node node .previousSibling; // node .nextSibling; // node .parentNode; // node .childNodes; // node list .children; // element collection .firstChild; // node .lastChild; // node
  83. 83. FUNDAMENTAL JAVASCRIPT Digging in node .nodeName; // e.g. “em” or “#text” node .nodeType; // 1 = element // 2 = attribute // 3 = text node .nodeValue; // only attribute nodes // and text nodes
  84. 84. Step 2: Manipulate Stuff
  85. 85. FUNDAMENTAL JAVASCRIPT Manipulate Stuff (in CSS) p { color: red; } #footer { border: 1px solid; } #footer > p { color: black; }
  86. 86. FUNDAMENTAL JAVASCRIPT Manipulate Stuff (in JS) var abbr = document.createElement( 'abbr' ); var text = document.createTextNode( 'TN' ); abbr.setAttribute( 'title', 'Tennessee' ); abbr.appendChild( text );
  87. 87. FUNDAMENTAL JAVASCRIPT Manipulating the DOM element .appendChild( new_node ); element .insertBefore( new_node, target ); element .replaceChild( new_node, target );
  88. 88. FUNDAMENTAL JAVASCRIPT Manipulating elements var p = document.getElementsByTagName( 'p' )[0], // collect abbr = document.createElement( 'abbr' ), text = document.createTextNode( 'TN' ); // generate abbr.setAttribute( 'title', 'Tennessee' ); abbr.appendChild( text ); p.appendChild( abbr ); // combine
  89. 89. FUNDAMENTAL JAVASCRIPT Cheap creation // find #foo var p = document.getElementById( '#foo' ); // create the model var abbr = document.createElement( 'abbr' ); for ( i=0; i<100; i++ ) { // append cheap copies to #foo p.appendChild( abbr.cloneNode() ); }
  90. 90. FUNDAMENTAL JAVASCRIPT Cheap creation // create the model var abbr = document.createElement( 'abbr' ), a, b; // add a child abbr.appendChild( document.createTextNode('hi') ); // make cheap copies a = abbr.cloneNode( false ); b = abbr.cloneNode( true ); // <abbr></abbr> // <abbr>hi</abbr>
  91. 91. FUNDAMENTAL JAVASCRIPT Bulk manipulation // good for read/write of large chunks element .innerHTML = new_content; // avoid in general document.write( new_content );
  92. 92. Exercise 1
  93. 93. FUNDAMENTAL JAVASCRIPT HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset=”utf-8"> <title>Example 1</title> </head> <body> <blockquote cite="http://bit.ly/1n9zDlG"> <p>Progressive Enhancement, as a label for a strategy for Web design, was coined by Steven Champeon in a series of articles and presentations for Webmonkey and the SxSW Interactive conference.</p> </blockquote> </body> </html>
  94. 94. FUNDAMENTAL JAVASCRIPT The plan 1.Find all the blockquotes in a document 2. Get the value of the cite attribute 3. Create a new anchor element node 4. Set the href attribute of the anchor to the value of the cite 5. Create a new text node with the word “source” 6. Insert the text into the anchor 7. Insert the anchor into the blockquote. 97
  95. 95. FUNDAMENTAL JAVASCRIPT HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset=”utf-8"> <title>Example 1</title> </head> <body> <blockquote cite="http://bit.ly/1n9zDlG"> <p>Progressive Enhancement, as a label for a strategy for Web design, was coined by Steven Champeon in a series of articles and presentations for Webmonkey and the SxSW Interactive conference.</p> </blockquote> <script> ... </script> </body> </html>
  96. 96. FUNDAMENTAL JAVASCRIPT My take var quotes = document.getElementsByTagName( 'blockquote' ); for ( var i=0; i < quotes.length; i++ ) { var source = quotes[i].getAttribute( 'cite' ); if ( source ) { var link = document.createElement( 'a' ); link.setAttribute( 'href', source ); var text = document.createTextNode( 'source' ); link.appendChild( text ); quotes[i].appendChild( link ); } }
  97. 97. Exercise 2
  98. 98. FUNDAMENTAL JAVASCRIPT HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset=”utf-8"> <title>Example 2</title> </head> <body> <p>This is a <em>test</em> of a simple email obfuscation technique. It relies on an obfuscated email address placed in an emphasis element (<code>em</code>) and replaces it with a <code>mailto:</code> link for the valid email address.</p> <p>For example, this email address—<em>aaron [at] easy [dash] designs [dot] net</em>— should be converted.</p> </body> </html>
  99. 99. FUNDAMENTAL JAVASCRIPT The plan 1. Find all the em elements in a document 2. Make sure the content passes our obfuscation test (e.g. contains “[at]”) 3. Grab the content and convert bracketed terms to their equivalents to reveal the email address (e.g. “[at]” to “@”) 4. Create a new anchor 5. Set the content to be the email address 6. Set the mailto: href 7. Replace the em with the anchor 102
  100. 100. FUNDAMENTAL JAVASCRIPT HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset=”utf-8"> <title>Example 2</title> </head> <body> <p>This is a <em>test</em> of a simple email obfuscation technique. It relies on an obfuscated email address placed in an emphasis element (<code>em</code>) and replaces it with a <code>mailto:</code> link for the valid email address.</p> <p>For example, this email address—<em>aaron [at] easy [dash] designs [dot] net</em>— should be converted.</p> </body> </html>
  101. 101. FUNDAMENTAL JAVASCRIPT My take var ems = document.getElementsByTagName('em'), i = ems.length, str, a; while ( i-- ) { if ( ems[i].firstChild && ems[i].firstChild.nodeValue.match( /s*[at]s*/g ) ) { str = ems[i].firstChild.nodeValue .replace( /s*[dot]s*/g, '.' ) .replace( /s*[at]s*/g, '@' ) .replace( /s*[dash]s*/g, '-' ); a = document.createElement( 'a' ); a.setAttribute( 'href', 'mailto:' + str ); a.appendChild( document.createTextNode( str ) ); ems[i].parentNode.replaceChild( a, ems[i] ); } }

×