Are u sure! – You know JavaScript? – goo.gl/dV2puW



Are u sure! – You know JavaScript? – goo.gl/dV2puW

0 1


JSconfusingParts

Things in JS confuses you. this is another attempt to escape confusion

On Github khan4019 / JSconfusingParts

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

function like an object could have property have a length property 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

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

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

Summary

two stages of function: creation, execution creates execution context (before running any code) First thing created is the scope chain then it creates variableObject create arguments, variable, determine this 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
								
function call creates execution context (before running any code) First thing created is the scope chain create arguments, variable, determine this 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?

garbage collector can not claim the variable you are holding How many closure you are creating variable reference: Dont use excessively large private variable 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']
							
can't explicity created available only when function begin execution arguments & named parameters references same value 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

function could have properties two stages of function call: Creation, Execution ExecutionContext: Scope chain, variableObj, this Jackie Chan, Kim Kardashian, super bowl Scope chain: collection of current + all parent Execution context Closure: save states and create encapsulation arguments: is an array like object 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

my button

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

left of dot(.) will indicate value of this window (no dot) undefined (strict mode IIFE) object (left of dot('.') for a method call) newly constructed object (constructor: new keyword) window (inside setTimeout) element fired the event, inside event handler this has access to all inherited properties 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

two stages of function call: creation, execution ExecutionContext: scope chain, variable Object, this Scope chain: collection of current + all parent Execution context Closure: Save states and create encapsulation left side of "." helps to defines values of this use bind, call, apply to set value of this explicitly changing properties of passed object will propagate JS Implementation: call stack, event loop, queue

Deleted Scenes

only 50 min

inheritance types, boolean, array, +, equality problem with typeof timer strict mode promise small caveats like dot, comma, etc. dating with JS 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

Ctrl + 1 when big brother is around Use headphone or mute Always carry extra bag and print out do ur personal work, but leave after ur manager always leave a extra jacket on your chair 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)