Are u sure!

You know JavaScript?


goo.gl/dV2puW




MD Khan / @mdkhan005

www.thatJSdude.com

(youtube.com/user/khanLearning)

todo

  • hoisting wasnt that clear: feedback by audiance
  • How do we develop a app?

    You don't get what you deserve

    You only get what you negotiate

    Function

    function in JS

    1. function like an object
    2. could have property

    3. have a length property
    4. length is number of parameters

    function call

    
    function foo(a, b){
        return a * b;
    }
    
    foo(2,3);
    							

    Two stages

    • Creation stage
    • Execution stage

    Creation Stage

    
    ExecutionContext: {}
    							
  • Each function call creates own ExectuionContext
  • roughly an 'environment' where function executes
  • 
    ExecutionContext: {
        scopeChain: { ... }
    }
    							
    
    ExecutionContext: {
        scopeChain : { ... },
        variableObject: { ... }
    }
    							

    creation stage

    1. Execution Context > Scope chain > variable object
    
    ExecutionContext: {
        scopeChain : { ... },
        variableObject: {
            arguments:{ ... }
        }
    }
    							
    
    ExecutionContext: {
        scopeChain : { ... },
        variableObject: {
            arguments:{
        	    0 : 2,
                1 : 3,
        	    length : 2
            }
        }
    }
    							
    
    foo(2,3);
    							
    JavaScript execution

    variable instantiation

    
    ExecutionContext: {
        scopeChain : { ... },
        variableObject: {
            arguments:{
        	    0 : 2,
                1 : 3,
        	    length : 2
            },
            a : 2,
            b : 3
        }
    }
    							
    
    function foo(a, b){
        return a * b;
    }
    
    foo(2,3);
    							

    inner variable, function

    
    function foo(a, b){
        function ttt(){console.log(a);}
        var c = a + b;
        return a * b;
    }
    							
    
    ExecutionContext: {
        scopeChain : { ... },
        variableObject: {
            arguments:{
        	    0 : 2,
                1 : 3,
        	    length : 2
            },
            a : 2,
            b : 3,
            ttt : pointer to function ttt(),
            c : undefined
        }
    }
    							

    this

    object, “owner” of the function being executed

    
    ExecutionContext: {
        scopeChain : { ... },
        variableObject: { ... },
        this:{ ... }
    }
    							
    
    ExecutionContext: {
        scopeChain : { ... },
        variableObject: {
            arguments:{
        	    0 : 2,
                1 : 3,
        	    length : 2
            },
            a : 2,
            b : 3,
            ttt : pointer to function ttt(),
            c : undefined,
        },
        this: { ... }
    }
    							

    Execution stage

    1. start reading the code from first line
    2. assign values
    3. if need to access variable, it read from ExecutionContext
    4. until hits first return or body ends

    Summary

    1. two stages of function: creation, execution
    2. creates execution context (before running any code)

    3. First thing created is the scope chain
    4. then it creates variableObject

    5. create arguments, variable, determine this

    6. execute function

    Scope

    JavaScript Scope



    • Global scope

    • local scope

    global scope

    var a = 2;
    function b(){
       console.log(a);
    }							

    Local Scope

    local/function scope

    function b(){
       var d = 21;
       console.log(d);
    }
    b();
    
    console.log(d); //ReferenceError: d is not defined
    								
    1. function call creates execution context (before running any code)
    2. First thing created is the scope chain
    3. create arguments, variable, determine this
    4. execute function

    JS scope chain

    multi execution context

    var a = 2;
    function b(){ console.log(a); }
    function c(){ console.log(a); }
    b();
    c();

    local events

    nested function (closure)

  • Scope is static.
  • set in the creation stage and never changes



  • scope chain



    is a collection of

  • current execution context
  • all parent execution context



  • what you need to know about block scope- let

    closure

    function in a function

    
    function counter(){
        var i = 0;
    
        return function(){
           return i++;
        }
    }
    							
    
    var a = counter();
    
    a;
    //function (){
    //       return i++;
    //    }
    							
    
    a();
    							

    function inside function

    multiple closure

    
    function counter(){
        var i = 0;
    
        return function(){
           return i++;
        }
    }
    
    var a = counter();
    a(); //0
    a(); //1
    a(); //2
    a(); //3
    a(); //4
    a(); //5

    multiple closure

    
    var b = counter();
    b(); //0
    b(); //1
    b(); //2
    b(); //3

    each closure have separate private variable

    Who care?

    1. garbage collector can not claim the variable you are holding
    2. How many closure you are creating

    3. variable reference: Dont use excessively large private variable
    4. Unnecessary closure affect processing speed and memory consumption



    Addy Osmani: memory efficient JS

    Summary

    • function inside another function
    • doesn't have to return function
    • Refer to variables, parameters outside of current scope
    • read and write outer scope variable
    • each closure has separate private variable
    Closure for dummies

    arguments

    Local variable, available to all functions

    
    function foo(a, b){
      return arguments;
    }
    
    foo(); //[]
    
    foo('js', 'is', 'fun'); //['js', 'is', 'fun']
    							
    1. can't explicity created
    2. available only when function begin execution
    3. arguments & named parameters references same value
    4. updateing arguments[i] changes named parameters

    Like an Array

    
    arguments.length; //3
    arguments[2]; //fun
    							

    Not an Array

    
    arguments.indexOf('is');
    //TypeError: Object has no method 'indexOf'
    							

    Convert to Array

    
    var args = Array.prototype.slice.call(arguments);
    args.map();
    							

    Don't mess up with names

    
    function foo(a, arguments) {
        return arguments;
    };
     
    foo(1); //undefined
    							
    
    function foo(a, b) {
        var arguments = 43;
        return arguments
    };
     
    foo(1, 2); //43
    							
    Angus Croll: aguments

    wake him up

    summary

    1. function could have properties
    2. two stages of function call: Creation, Execution

    3. ExecutionContext: Scope chain, variableObj, this
    4. Jackie Chan, Kim Kardashian, super bowl

    5. Scope chain: collection of current + all parent Execution context
    6. Closure: save states and create encapsulation

    7. arguments: is an array like object
    8. Don't create a variable or parameter named arguments

    morning of a developer

    hoisting

    hoist variable

    
    function foo(){
      console.log(a);
      //do something
      var a = 42;
    }
    							
    
    foo();
    //undefined
    							
    
    function foo(){
      var a;
      console.log(a);
      //do something
      a = 42;
    }
    							
    
    function justLooping() {
    
        for (var i = 0; i < 5; i++) {
            //do something
        }
        console.log(i);
    }
    							
    
    function justLooping() {
        var i;
        for (i = 0; i < 5; i++) {
            //do something
        }
        console.log(i);
    }
    							

    let's look into inner function

    
    function outer(){
      inner();
    
      //do something else 	
      
      function inner(){
        console.log('inside inner function');
      }  
    }
    
    outer(); // inside inner function
    							
    
    function outer(){
      function inner(){
        console.log('inside inner');
      }
    
      //do something
      
      inner();
    }
    							
    JS hoisting explained

    function expression

    
    function outer(){
      inner();
      //do something else 	
      var inner = function(){
        console.log('inside inner');
      }  
    }
    							
    
    outer();//TypeError: undefined is not a function
    							
    
    function outer(){
      var inner;
      inner();
      //do something else 	
      inner = function(){
        console.log('inside inner');
      }  
    }

    this

    What the heck is "this"?

    What is this?

    
    this;//window								
    							
    
    function whatIsThis() {
       return this;
    }
    whatIsThis(); //window
    
    (function(){
       return this;
    })();
    //window
    
    (function(){
       'use strict';
       return this;
    })(); //undefined
    Smashing: JS Scope

    understand the context of execution

    
    var a = {
        b: function() {
            return this;
        }
    };
    a.b();//Object {b: function}
    
    var foo = a.b;
    
    
    var foo = function(){
      return this;
    };
    foo(); //window
    window.foo(); //window
    
    var d = {};
    d.c = a.b;
    d.c();//Object {c: function}
    							
    Angus Croll: this

    constructor

    this = {}

    newly constructed object

    
    function Friend(name) {
      this.name = name;
      this.context = this;
    }
    
    var frnd1 = new Friend('js dude');
    var frnd2 = new Friend('common guy');
    							
    
    frnd1.name; //js dude
    frnd1.context;//Friend {name: "js dude", context: Friend}
    							
    
    frnd2.name; //common guy
    frnd2.context;//Friend {name: "common guy", context: Friend}
                                

    prototype chain

    access property, methods in the prototype chain

    
    var dad = {
      fathersName:'big Dad'
    }
    
    var child = Object.create(dad);
    							
    
    child.whoIsYourFather = function(){
        return this.fathersName;
     }
    							
    
    child.whoIsYourFather(); //big Dad
    							
    
    child.hasOwnProperty('fathersName'); //false
    Object.getPrototypeOf(child); //{fathersName: "big Dad"}
    							
    sitePoint: this

    setTimeout inside constructor

    
    function Menu(item){
      this.item = item;
      this.context = this;
    
      setTimeout(function(){
        console.log('setTimeout context:', this);
      }, 10);
    
    }
    							
    
    var lunch = new Menu('pizza');
    
    //setTimeout context: window
    
    lunch.context//Menu {item: "pizza", context: Menu}
    							

    Same issues with setInterval

    "this" in arguments

    8 ES5 function allows thisArg

    
    Function.prototype.bind( thisArg [ , arg1 [ , arg2, ... ] ] )
    Function.prototype.call( thisArg [ , arg1 [ , arg2, ... ] ] )
    Function.prototype.apply( thisArg, argArray )
    							

    DOM event handler

    this = element the event fired from

    
    function bluify(e){
      console.log(this === e.currentTarget); // Always true
      console.log(this === e.target);// true when currentTarget and target are the same object
      this.style.backgroundColor = '#A5D9F3';
    }
    							
    
    //execute it in console
    document.getElementById('myButton').addEventListener('click', function(){
    console.log(this);
    }, false);
    							

    same for inline element this

    MDN: this

    Now. I know this

    1. left of dot(.) will indicate value of this
    2. window (no dot)

    3. undefined (strict mode IIFE)

    4. object (left of dot('.') for a method call)
    5. newly constructed object (constructor: new keyword)

    6. window (inside setTimeout)
    7. element fired the event, inside event handler

    8. this has access to all inherited properties
    9. use bind, call, apply to set value of this explicitly

    Day of a programmer


    time wasted at work

    pass by

    primitive by value

    
    function foo(a){
        a = 55;
    }
    							
    
    var a = 7;
    
    foo(a);
    
    a; //7
    							

    primitive types: boolean, string, number

    object is pass by ref

    
    function foo(speaker){
        speaker.name = 'Paul Irish';
    }
    
    var speaker = {name : 'Addy Osmani'};
    
    foo(speaker);
    
    console.log(speaker);//Object {name : "Paul Irish"}
    							

    replace object parameter

    
    function foo(speaker){
        speaker = {name : 'Paul Irish'};
    }
    
    var speaker = {name : 'Addy Osmani'};
    
    foo(speaker);
    
    console.log(speaker);//Object {name : "Addy Osmani"}
    							

    Call by Sharing

    • If u change the parameter, it wont affect
    • If u change INTERNALS, changes will propagate


    call by sharing
    by Ref, check this one

    What is JavaScript?

    How JavaScript works?

    a single-threaded, non-blocking, asnchronous concurrent runtime



    I am a programmer, give me detail

    maintain a call stack, event loop, queue, etc.



    are these in JS?

    no. they are in JavaScript implementation.


    Help, I'm stuck in an event-loop

    what is call stack?

    
    function multiply(a,b){
        return a * b;
    }
    
    function square (n){
        return multiply(n,n);
    }
    
    function consoleSquare(n){
        var squared = square(n);
        console.log(squared);
    }
    							
    
    consoleSquare(3);
    							
    js strack trace

    MDN: event loop
    event loop explained

    get out of there

    Summary

    1. two stages of function call: creation, execution
    2. ExecutionContext: scope chain, variable Object, this

    3. Scope chain: collection of current + all parent Execution context
    4. Closure: Save states and create encapsulation

    5. left side of "." helps to defines values of this
    6. use bind, call, apply to set value of this explicitly

    7. changing properties of passed object will propagate
    8. JS Implementation: call stack, event loop, queue

    Deleted Scenes

    only 50 min

    1. inheritance
    2. types, boolean, array, +, equality
    3. problem with typeof
    4. timer
    5. strict mode
    6. promise
    7. small caveats like dot, comma, etc.
    8. dating with JS
    9. regex

    Need more !!!

    Frequently misunderstood JS Concepts
    u reuined JS
    JS comma
    JS parts i struggled to remember.
    Angus ES6

    Free tip

    Look Busy at Work

    1. Ctrl + 1 when big brother is around
    2. Use headphone or mute

    3. Always carry extra bag and print out
    4. do ur personal work, but leave after ur manager

    5. always leave a extra jacket on your chair
    6. compose email during office hours, send it midnight or weekends



    Look busy

    One thing

    left side of dot (.) helps to define value of this

    
    foo();
    //window.foo();
    							
    
    a.b();
    							

    Thank You






    MD Khan / @mdkhan005

    www.thatJSdude.com

    (youtube.com/user/khanLearning)

    Question?

    goo.gl/dV2puW

    MD Khan / @mdkhan005

    www.thatJSdude.com

    (youtube.com/user/khanLearning)