JavaScript – For Beginners and Noobs – JAVA   Script



JavaScript – For Beginners and Noobs – JAVA   Script

0 0


presentation-js-for-beginners

JS Presentation

On Github rcorral / presentation-js-for-beginners

JavaScript

For Beginners and Noobs

Created by Rafael Corral May 2013

Everyone was a noob once, it's ok. We all sucked at one point in time. Teaching programming is difficult, everyone learns differently. If I talk too much and you want to see an example just stop me, because you won't be the only one. Or if I'm giving out too many examples and you need more explanation then let me know too.

WHOIS

About Rafael Corral

me@rafaelcorral.com@rcorrallinkedin.com/in/rafacorral Software Engineer at Barracuda Networks

Agenda

  • Ramble
  • Data Types
  • Objects
  • Functions
  • Inheritance
  • Arrays
  • Tools
  • Tips

JAVA   Script

About JavaScript

History

  • 1995; 18 years ago
  • Developed by Netscape
  • Shipped in beta of Netscape Navigator 2.0
  • IE adopts JS in IE 3.0, 1996
  • Nov. 1996 submitted to ECMA International
  • June 1997 first edition of ECMA-262
  • Latest 5.1 edition, June 2011
  • ECMAScript edition 6 is around the corner

Warning

  • Countless BAD parts
  • Imperfections
  • Confusing
  • Ugly
  • Globals
The amazing thing about JS is that it's possible to get a lot done without knowing much about the language.

Data Types

Null

    null

    // Not
    NULL
    // or
    Null
                    

undefined

    undefined

    // Variable declared but not set
    // Not the same as
    null
                    

Booleans

    true
    // and
    false
                    

Numbers

    var months = 12; // int
    var height = 6.5; // float
    var year = months / 'x'; // NaN
                    
Integers and floats

Strings

    var first_name = "Rafael";
                    
Numbers, strings, and booleans are object-like in that they have methods, but they are immutable. Objects in JavaScript are mutable keyed collections. In JavaScript, arrays are objects, functions are objects, regular expressions are objects, and, of course, objects are objects.

Objects

Containers of properties

Properties can be a name and a value. Objects in JS are class-free. JavaScript a prototype linkage feature that allows one object to inherit the properties of another object
Objects can contain other objects so that they can represent tree or graph structures.

Object Literal

    var empty_object = {};
    var user = {
        name: 'Rafael',
        age: 25
    }
                    
Objects can appear anywhere where an expression can appear.

Access Properties

    user['name']; // Rafael
    user.age; // 25
    user.email; // undefined
    user.gender || 'none'; // none
                    

Passed by reference

    var another_user = user;
    another_user.name = 'Travis';
    user.name; // Travis
                    

Prototype

    user.get_age = function() { return this.age; }

    var user_proto = function(){};
    user_proto.prototype = user;

    var user2 = new user_proto;
    user2.age = 40;
    user2.get_age(); // 40
    user.get_age(); // 25

    user.get_name = function(){ return this.name; }
    user2.name = 'Rafael';
    user.get_name(); // Travis
                    

.hasOwnProperty

    user.height = 72;
    user.hasOwnProperty('height'); // true

    user2.height; // 72
    user2.hasOwnProperty('height'); // false
                    
This method is available in objects

Enumeration

    for ( var i in user ) {
        if ( typeof user[i] !== 'function' ) {
            alert( i + ': ' + user[i] );
        }
    }
                    

Functions

Functions in JavaScript are Objects

  • Functions are objects.
  • Function objects have a hidden link to: Function.prototype.
  • Function.prototype is itself linked to: Object.prototype.
  • Every function also has two other hidden properties:
    • The functions context.
    • The code that is included inside the function.

To complicate things

  • Every function object has a prototype property.
  • It's value is a constructor property whose value is the function.

The thing that's special about functions is that they can be invoked.

Function Literal

    // Create a function that gets the remainder
    var remainder = function(a, b) {
        return a % b;
    }
                    
Functions are created with function literals. A function has 4 parts:
  • The reserved word function
  • The functions name (optional).
  • The parameters for the function. Zero or more.
  • The statements wrapped in curly braces.
A function literal can appear anywhere that an expression can appear.

Closure

    var person = function(fname, lname, age){
        var get_name = function(){
                return fname + ' ' + lname;
            },
            get_age = function(){
                return age;
            };

        return {
            name: get_name(),
            age: get_age()
        }
    }

    var user_object = person('Rafael', 'Corral', 25);
                    
  • Functions can be created inside of other functions.
  • An inner function has access to parameters and variables of the functions it's nested within.
  • Te function object created by a function literal contains a hidden link to that context.
  • This is called closure.

Function Invocation Pattern

When a function is invoked it get's the declared parameters. It receives two additional parameters: this and arguments. The value of this is determined by the invocation pattern.

Method Invocation

    var my_person = {
        age: 0,
        increment_age: function(inc){
            this.age += typeof inc === 'number' ? inc : 1;
            return this;
        },
        get_age: function(){
            return this.age;
        }
    }

    my_person.increment_age().get_age(); // 1
    my_person.increment_age(2).get_age(); // 3
                    

Function Invocation Pattern

    var color = 'red';
    var favorite_color = {
        get_color: function(){
            this.color = 'blue';
            function inner_function(){
                return this.color;
            }
            return inner_function();
        }
    }

    favorite_color.get_color(); // 'red'
                    

Function Invocation Pattern

    var color = 'red';
    var favorite_color = {
        get_color: function(){
            this.color = 'blue';
            var that = this; // Workaround
            function inner_function(){
                return that.color;
            }
            return inner_function();
        }
    }

    favorite_color.get_color(); // 'blue'
                    

Constructor Invocation Pattern

    var Mammal = function( type ) {
        this.type = type;
    }

    // Create a public method
    Mammal.prototype.get_type = function(){
        return this.type;
    }

    // Create a cat
    var cat = new Mammal('cat');

    cat.get_type(); // 'cat'
                    
Functions that are intended to be used with the new prefix are called constructors. By convention, they are kept capitalized. If called without the new prefix, bad things can happen.this will get bound to the global object rather than the newely created one. It is not recommended to use this style of contructor functions.

Apply Invocation Pattern

    // The first parameter is the value of this

    var array = [9, 6];
    remainder.apply(null, array); // 3

    cat.get_type.apply({type: 'dog'}); // 'dog'
                    

Function Scope

    var foo = function(){
        var a = 3, b = 5;

        var bar = function(){
            var b = 7, c = 11;
            // a is 3, b is 7, c is 11

            a += b;
            // a is 10, b is 7, c is 11
        }
        // a is 3, b is 5
        bar();
        // a is 10, b is 5
    }
    foo();
                    

Closure

    var game = (function(){
        // This value can't be modified
        var type = 'chess';

        return {
            get_game: function(){
                return type;
            }
        }
    }());
                    

Closure Example

    var mammal = function( type ) {
        return {
            get_type: function(){
                return type;
            }
        }
    }

    // Create a cat
    var cat = mammal('cat');

    cat.get_type(); // 'cat'
                    
type is private and will always be available to the inner method of the returned object.

Inheritance

In classical languages, objects inherit from classes and a class can inherit from another class. JS is a prototypal language, which means objects inherit from other objects.

Prototypal Inheritance

    var electronics = {
        type: '',
        get_type: function(){
            return this.type;
        }
    };

    var tv = function(inches){
        var F = function(){};
        F.prototype = electronics;
        _f = new F;
        _f.type = 'tv';
        _f.inches = inches;
        _f.get_inches = function(){
            return this.inches;
        }
        return _f;
    };

    var samsung = tv(55);
    samsung.get_inches(); // 55
    samsung.inches = 42;
    samsung.get_inches(); // 42
                    

Functional Pattern

    var electronics = function(type){
        var that = {};
        that.get_type = function(){
            return type;
        }

        return that;
    };

    var tv = function(inches){
        var that = electronics('tv');
        that.get_inches = function(){
            return inches;
        }

        return that;
    };

    var samsung = tv(55);
    samsung.get_inches(); // 55
    samsung.inches = 42;
    samsung.get_inches(); // 55
                    
This pattern provides us with privacy. Once the inches and type are set they cannot be changed.

Arrays

JavaScript provides an object that has some array-like characteristics.

Array Literals

    var empty = [];

    var numbers = [
        'zero', 'one', 'two',
        'three', 'four', 'five'
    ];

    empty[1]; // undefined
    numbers[1]; // 'one'
    numbers.legth; // 6

    // object literal
    var numbers_object = {
        0: 'zero', 1: 'one', 2: 'two',
        3: 'three', 4: 'four', 5: 'five'
    }
                    
  • Elements are accessed by integers, that are used to compute offsets.
  • An array is a pair of square brackets with zero or more values separated by commas.
  • The first value will get the property name '0', the second will get a '1' and so on.
  • numbers inherits from Array.prototype
  • numbers_object inherits from Object.prototype
  • numbers inherits useful methods for manipulating arrays
  • numbers also gets a mysterious length property

Length

    var some_array = [];
    some_array.length; // 0

    some_array[100] = 'some value';
    some_array.length; // 101

    some_array.length = 0;
    some_array.length; // 0
                    

Array Object Methods

    .concat()
    .join()
    .pop()
    .push()
    .reverse()
    .shift()
    .unshift()
                    

Delete

    delete numbers[4]; // Leaves a hole in the array
    // Numbers is ['zero', 'one', 'two', 'three', undefined, 'five']

    numbers.splice(4, 1);
    // numbers is ['zero', 'one', 'two', 'three', 'five']
                    

Tools

  • Browser inspector
  • Node.js
  • Phantom.js
  • JSLint
  • Firebug

Tips

Create a single global object for your application

    var myapp = {
        options: {
            length: 1,
            width: 2,
            color: red
        },
        function1: function(){

        }
    };
                    

Be cautious of the scope

    var name = 'Rafael';
    function dogs_name(){
        name = 'Sunny';
    }
    var my_dog = dogs_name();
    name; // 'Sunny'
                    

==

    '' == '0' // false
    0 == '' // true
    0 == '0' // true

    false == 'false' // false
    false == '0' // true

    false == undefined // false
    false == null // false
    null == undefined // true

    ' \t\ r\ n ' == 0 // true

    // Using === would solve all this confusion
                    

eval is evil

    // Just don't do this
    eval('somecode');
                    

THE END

me@rafaelcorral.com@rcorrallinkedin.com/in/rafacorral