JavaScript Primer – 11.19.2015 – Java is to JavaScript as Car is to Carpet



JavaScript Primer – 11.19.2015 – Java is to JavaScript as Car is to Carpet

0 0


slides-javascript

JavaScript visual presentation for Seminars

On Github devcsrj / slides-javascript

JavaScript Primer

11.19.2015

By @devcsrj

Contents

  • About JS
  • Core JavaScript
  • Fundamentals
  • Client-Side JavaScript

Java is to JavaScript as Car is to Carpet

  • JS started as Mocha, then became LiveScript
  • Was named JavaScript after Netscape-Sun agreement
  • Created by Brendan Eich (co-founded the Mozilla project)
  • Interpreted, dynamically-typed

Getting Started

What you need: A browser

On Firefox

  • Open Web Console
    • Ctrl + Shift + K
    • Tools > Web Developer > Web Console
  • Type and Enter
    • console.log( "Oh yeah" )
    • alert( "Awesome" )

On Chrome

  • Open Web Console
    • Ctrl + Shift + J
    • (or) Menu > More Tools > Developer Tools > Console Tab
  • Type and Enter
    • console.log( "Oh yeah" )
    • alert( "Awesome" )

Fundamentals: Lexical Structure

  • Case Sensitive - while, not While, or WHILE
  • Comments
    // This is a one-liner comment
    /* This is another comment */ // this one too
    /*
     * Multiple-lined comment.
     * Yep.
     */
  • Identifiers - must begin with a letter, _ or $
    // Legal identifiers
    var i, my_variable_name, v13, _dummy, $str;

Fundamentals: Lexical Structure II

  • Semicolons - Optional, but take note:
var a
a
=
3
console.log(a)
// Interpreted as: var a; a = 3; console.log(a);

var y = x + f
(a+b).toString()
// Interpreted as: var y = x + f(a+b).toString();

Fundamentals: Types, Values and Variables

var x           // Declare a variable named x
    
x = 0;          // Now variable x has the value of 0
x               // => 0: A variable evaluates to its value

// JS supports several types of values
x = 1;                  // Numbers
x = 0.01;               // One number type for integer and reals
x = "hello world";      // Strings
x = 'JavaScript';       // Single quote marks also delimit Strings
x = true;               // Boolean values
x = false;

x = null;               // A special value denoting "no value"
x = undefined;          // Undefined is like null

Fundamentals: Comparison Operators

7 == 7              // true
7 === "7"           // false 
7 === 7             // true

"auf" != "hau"      // true
"auf" !== "hau"     // true

7 > 7               // false
7 >= 7              // true
7 < 1               // false
7 <= 1              // false

Fundamentals: Arithmetic Operators

Standard: addition(+), subtraction(-), multiplication(*),division(/) Operator Example Remainder (%) 12 % 5 returns 2 Increment (++) if x is 3, then x++ is 4 Decrement (--) if x is 3, then x-- is 2 Unary negation (-) if x is 3, then -x is -3 Unary plus (-) +"3" returns 3 +true returns 1 Exponentiation 2 ** 3 returns 8

Fundamentals: Control Structures

if( condition ) {
    // Executes if condition is true
} else {
    // Else what
}

switch( expression ) {
    case 'value1':
        // Execute code if expression is 'value1'
        break;
    case 'value2':
        // Execute code if expression is 'value2'
        break;
    case default:
        // Execute code if expression does not match any
        // `default` is a reserved keyword
        // `break` optional, since it is the end of switch
}

Fundamentals: Control Structures II

while( condition ) {
    // Execute this every time condition is true
}

for( init ; condition ; iterator ){
    // Execute until condition is met
}

Fundamentals: More Types - Array

var universities = [ "auf", "hau", "spcf", "ama" ]    
var bankAccounts = [ 10001, 10002, 10003, 10004 ]
// You can mix datatypes
var stuff = [ 5, 'random', [], "I wonder who does this", true, 50.0 ]

// Methods - @see Array.prototype
                        

Fundamentals: Functions

function average ( arr ) {
    var mean = 0;
    for( var i = 0; i < arr.length; i ++ )
        mean += arr[ i ];
    return mean / arr.length
}

average ( [ 85, 88, 75, 83 ] ); // 82.75

var madEcho = function ( what ) {
    return what.toUpperCase() + "!!!!"
}
madEcho // prints function declaration
madEcho ( "hi" ); // "HI!!!!"

Fundamentals: Functions II

var greet = function ( greeting, name ){
    alert( greeting + name );
}
greet // prints function declration
greet( 'Hello Master ', 'RJ' );

// IIFE (iffy) - Immediately Invoked Function Expression
(function( greeting, name ){
    alert( greeting + name );
})( 'Hello Master ', 'RJ' );

Fundamentals: More Types - Object

var person = {
    firstName : "Reijhanniel Jearl",
    lastName : "Campos",
    age : 20,
    likes : [ "pizza", "all-meat pizza", "more pizza" ],
    introduce : function (){
        return "Hi, I am " + this.firstName + " " + this.lastName 
            + ", " + this.age + ". I like " + this.likes
    }
}

person.introduce()
                        

Client-Side JavaScript

The Window object

is the main entry point to all client-side JavaScript features and APIs.

window.location = "http://github.com"
// The alert() method is a method of the `window` object
// Same as:
setTimeout( function() { alert( "Sup" )  }, 2000 );
location

document // we focus on this!
                        

Document Object Model (DOM)

.. a platform- and language-neutral interface that will allow programs and scripts to dynamically access and update the content, structure and style of documents - w3.org

Try the following:

document // to see the document object model

// Adds a `style` attribute to <body> tag
document.body.style.backgroundColor = 'yellow' 

// Sets a new value for <title> tag
document.title = "Look at the tab name!"

// Returns an array of <section> tags
document.getElementsByTagName( "section" );

// Sets HTML content of element with id of `caption-id`,
document.getElementById( "caption-id" ).innerHTML = "Yo"

Events Do something!

// try `Inspect Element`!
var btn = document.getElementById( "btn-for-event" );
var poke = function( event ){ // expect an `event` variable
    event.target.innerHTML = "You poked me!"
}

// attach `poke` function `onclick`
btn.addEventListener( "click", poke );
// or: btn.onclick = poke;

// attach an anonymous function `onclick`
btn.addEventListener( "click", function( event ) {
    alert( "Poked you back!" );
});

// remove `poke` function `onclick`
btn.removeEventListener( "click", poke );

// More Events @see MDN Event ref

Scripting

<!DOCTYPE html>
<html>
    <head>...</head>
    <body>
        ...

        <script>
            // Do magic
        </script>
    </body>
</html>

Scripting II

<div id="div1">The text above has been created dynamically.</div>

<script>
  document.body.onload = addElement;

  function addElement () { 
    // create a new div element and give it some content 
    var newDiv = document.createElement( "div" ); 
    var newContent = document.createTextNode("Hi there and greetings!"); 
    //add the text node to the newly created div. 
    newDiv.appendChild(newContent);

    // add the newly created element and its content into the DOM 
    var currentDiv = document.getElementById( "div1" ); 
    document.body.insertBefore( newDiv, currentDiv ); 
  }    
</script>
JavaScript Primer 11.19.2015 By @devcsrj