Monthly Archives: January 2016

JavaScript Hoisting

If we execute below Javascript code, what will the browser console display:

var temp = 'outside global';
function foo(){
    console.log(temp);
    var temp = 'inside function';
};
foo();

The console will log undefined.
Function-level scope. Functions create new scopes in Javascript, blocks like if statements and for loops do not create a new scope. A variable declaration simply tells the interpreter that a variable exists. By default it initializes the variable to undefined.
In Javascript, variable declarations are “hoisted” to the top of the current scope. Variable assignments, however, are not.
The declaration (but not the assignment) of temp gets hoisted to the top of foo(). So our code gets interpreted as though it were:

var temp = 'outside global';
function foo(){
    var temp;
    console.log(temp);
    temp = 'inside function';
};
foo();

So we have a new variable temp inside of foo() that is initialized to undefined, which is what it holds when we hit our log statement.

In JavaScript, a variable can be declared after it has been used. In other words; a variable can be used before it has been declared. JavaScript only hoists declarations, not initialization. Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it’s declared. This behavior is called “hoisting”, as it appears that the variable declaration is moved to the top of the function or global code.

Why hoisting?

The JS code interpretation performed in two passes. During the first pass, the interpreter / compilation processes variable and function declarations. The second pass is actually code execution step. The interpreter processes function expressions and undeclared variables. JS engine actually will compile your JavaScript code before it interprets it. Part of the compilation phase was to find and associate all declarations with their appropriate scopes (lexical scope). So, the best way to think about things is that all declarations, both variables and functions, are processed first, before any part of your code is executed. So, one way of thinking, sort of metaphorically, about this process, is that variable and function declarations are “moved” from where they appear in the flow of the code to the top of the code. This gives rise to the name hoisting. Only the declarations themselves are hoisted, while any assignments or other executable logic are left in place. If hoisting were to re-arrange the executable logic of our code, that could wreak havoc.

For one thing, JavaScript engines don’t get the luxury (like other language compilers) of having plenty of time to optimize, because JavaScript compilation doesn’t happen in a build step ahead of time, as with other languages. For JavaScript, the compilation that occurs happens, in many cases, mere microseconds (or less!) before the code is executed. To ensure the fastest performance, JS engines use all kinds of tricks that are well beyond the scope of this blog.

var a =2;

Encountering var a, Compiler asks Scope to see if a variable a already exists for that particular scope collection. If so, Compiler ignores this declaration and moves on. Otherwise, Compiler asks Scope to declare a new variable called a for that scope collection. Compiler then produces code for Engine to later execute, to handle the a = 2 assignment. The code Engine runs will first ask Scope if there is a variable called a accessible in the current scope collection. If so, Engine uses that variable. If not, Engine looks elsewhere as per scope hirerachy. If Engine eventually finds a variable, it assigns the value 2 to it. If not, Engine will raise its hand and yell out an error.

To summarize: two distinct actions are taken for a variable assignment: First, Compiler declares a variable (if not previously declared) in the
current Scope, and second, when executing, Engine looks up the variable in Scope and assigns to it, if found.

Advertisements

Conceptual View for JavaScript Promises

Imagine this scenario: I walk up to the counter at a fast-food restaurant, and place an order for a cheeseburger. I hand the cashier $2.47. By placing my order and paying for it, I’ve made a request for a value back (the cheeseburger). I’ve started a transaction. But often, the chesseburger is not immediately available for me. The cashier hands me something in place of my cheeseburger: a receipt with an order number on it. This order number is an IOU (“I owe you”) promise that ensures that eventually, I should receive my cheeseburger. So I hold onto my receipt and order number. I know it represents my future cheeseburger, so I don’t need to worry about it anymore — aside from being hungry! While I wait, I can do other things, like send a text message to a friend that says, “Hey, can you come join me for lunch? I’m going to eat a cheeseburger.” I am reasoning about my future cheeseburger already, even though I don’t have it in my hands yet. My brain is able to do this because it’s treating the order number as a placeholder for the cheeseburger. The placeholder essentially makes the value time independent. It’s a future value. Eventually, I hear, “Order 113!” and I gleefully walk back up to the counter with receipt in hand. I hand my receipt to the cashier, and I take my cheeseburger in return. In other words, once my future value was ready, I exchanged my value-promise for the value itself. But there’s another possible outcome. They call my order number, but when I go to retrieve my cheeseburger, the cashier regretfully informs me, “I’m sorry, but we appear to be all out of cheeseburgers.” Setting aside the customer frustration of this scenario for a moment, we can see an important characteristic of future values: they can either indicate a success or failure. Every time I order a cheeseburger, I know that I’ll either get a cheeseburger eventually, or I’ll get the sad news of the cheeseburger shortage, and I’ll have to figure out something else to eat for lunch.

Because Promises encapsulate the time-dependent state — waiting on the fulfillment or rejection of the underlying value from the outside, the Promise itself is time-independent, and thus Promises can be composed (combined) in predictable ways regardless of the timing or outcome underneath. Moreover, once a Promise is resolved, it stays that way forever — it becomes an immutable value at that point — and can
then be observed as many times as necessary. Note: Because a Promise is externally immutable once resolved, it’s now safe to pass that value around to any party and know that it cannot be modified accidentally or maliciously. This is especially true in relation to multiple parties observing the resolution of a Promise. It is not possible for one party to affect another party’s ability to observe Promise resolution.
Immutability may sound like an academic topic, but it’s actually one of the most fundamental and important aspects of Promise design, and shouldn’t be casually passed over.
That’s one of the most powerful and important concepts to understand about Promises. With a fair amount of work, you could ad hoc create the same effects with nothing but ugly callback composition, but that’s not really an effective strategy, especially because you have to do it over and over again. Promises are an easily repeatable mechanism for encapsulating and composing future values.

4 enlightening rules for this keyword in Javascript

Note : Most of the content is from Kyle Simpson’s book (You Don’t Know JS- this & Object Prototypes) I have modified some things ans well as deleted some to ease my understanding

What’s mystery of this
We said earlier that this is not an author-time binding but a run time
binding. It is contextual based on the conditions of the function’s invocation. this binding has nothing to do with where a function is declared, but has instead everything to do with the manner in which
the function is called. When a function is invoked, an activation record, otherwise known as an execution context, is created. This record contains information about where the function was called from (the call-stack), how the function was invoked, what parameters were passed, etc. One of the properties of this record is the this reference, which will be used for the duration of that function’s execution.

  1. Default binding
    this rule is the default catch-all rule when none of the other rules apply. Consider following code snippet

    function foo() {
    console.log( this.a );
    }
    var a = 2;
    foo(); // 2
    

    The first thing to note, if you were not already aware, is that variables declared in the global scope, as var a = 2 is, are synonymous with global-object properties of the same name. They’re not copies of each other, they are each other. Think of it as two sides of the same coin.
    Second, we see that when foo() is called, this.a resolves to our global variable a. Why? Because in this case, the default binding for this applies to the function call, and so points this at the global object.
    If strict mode is in effect, the global object is not eligible for the
    default binding, so the this is instead set to undefined:

    function foo() {
    "use strict";
    console.log( this.a );
    }
    var a = 2;
    foo(); // TypeError: `this` is `undefined`
    
  2. Implicit Binding
    function foo() {
    console.log( this.a );
    }
    var obj = {
    a: 2,
    foo: foo
    };
    obj.foo(); // 2
    

    at the point that foo() is called, it’s preceeded by an object reference to obj. When there is a context object for a function reference, the implicit binding rule says that it’s that object that should be used for the function call’s this binding. Because obj is the this for the foo() call, this.a is synonymous with obj.a. Only the top/last level of an object property reference chain matters to the call-site.

    function foo() {
    console.log( this.a );
    }
    var obj2 = {
    a: 42,
    foo: foo
    };
    var obj1 = {
    a: 2,
    obj2: obj2
    };
    obj1.obj2.foo(); // 42
    

    One of the most common frustrations that this binding creates is
    when an implicitly bound function loses that binding, which usually
    means it falls back to the default binding of either the global object or undefined, depending on strict mode.

  3. Explicit Binding
    With implicit binding, as we just saw, we had to mutate the object in
    question to include a reference on itself to the function, and use this property function reference to indirectly (implicitly) bind this to the object. But, what if you want to force a function call to use a particular object for the this binding, without putting a property function reference on the object?
    “All” functions in the language have some utilities available to them
    (via their [[Prototype]]—more on that later), which can be useful
    for this task. Specifically, functions have call(..) and apply(..)
    methods. Technically, JavaScript host environments sometimes provide functions that are special enough (a kind way of putting it!) that they do not have such functionality. But those are few. The vast majority of functions provided, and certainly all functions you will create, do have access to call(..) and apply(..). They both take, as their first parameter, an object to use for the this, and then invoke the function with that this specified. Since you are directly stating what you want the this to be, we call it explicit binding.

    function foo() {
    console.log( this.a );
    }
    var obj = {
    a: 2
    };
    foo.call( obj ); // 2
    

    Invoking foo with explicit binding by foo.call(..) allows us to force
    its this to be obj. With respect to this binding, call(..) and apply(..) are identical. The difference is that apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly. A useful mnemonic is “A for array and C for comma.”

    function foo() {
    console.log( this.a );
    }
    var obj = {
    a: 2
    };
    var bar = function() {
    foo.call( obj );
    };
    bar(); // 2
    setTimeout( bar, 100 ); // 2
    // hard-bound `bar` can no longer have its `this` overridden
    bar.call( window ); // 2
    

    We create a function bar() which, internally, manually calls foo.call(obj), thereby forcibly invoking foo with obj binding for this. No matter how you later invoke the function bar, it will always manually invoke foo with obj. This binding is both explicit and strong, so we call it hard binding. Since hard binding is such a common pattern, it’s provided with a builtin utility as of ES5, Function.prototype.bind. The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

    function foo(something) {
    console.log( this.a, something );
    return this.a + something;
    }
    var obj = {
    a: 2
    };
    var bar = foo.bind( obj );
    var b = bar( 3 ); // 2 3
    console.log( b ); // 5
    
  4. new Binding

    When a function is invoked with new in front of it, otherwise known
    as a constructor call, the following things are done automatically:
    1. A brand new object is created (aka constructed) out of thin air.
    2. The newly constructed object is [[Prototype]]-linked.
    3. The newly constructed object is set as the this binding for that
    function call.
    4. Unless the function returns its own alternate object, the newinvoked function call will automatically return the newly constructed object.

    function foo(a) {
    this.a = a;
    }
    var bar = new foo( 2 );
    console.log( bar.a ); // 2
    

    By calling foo(..) with new in front of it, we’ve constructed a new
    object and set that new object as the this for the call of foo(..). So
    new is the final way that a function call’s this can be bound. We’ll call this new binding.

new in JavaScript – Enlightenment for me

Below content is extract from Kyle Simson’s book You Don’t Know JS- this & Object Prototypes. It enlightened me and my misnomer @ new keyword in JavaScript. Here is what he explains

JavaScript has a new operator, and the code pattern to use it looks basically identical to what we see in those class-oriented languages; most developers assume that JavaScript’s mechanism is doing something similar. However, there really is no connection to class-oriented functionality implied by new usage in JS.First, let’s redefine what a “constructor” in JavaScript is. In JS, constructors are just functions that happen to be called with the new operator in front of them. They are not attached to classes, nor are they instantiating a class. They are not even special types of functions. They’re just regular functions that are, in essence, hijacked by the use of new in their invocation.

For example, consider the Number(..) function acting as a constructor, quoting from the ES5.1 spec:15.7.2 The Number Constructor. When Number is called as part of a new expression it is a constructor:it initialises the newly created object. So, pretty much any ol’ function, including the built-in object functions like Number(..) can be called with new in front of it, and that makes that function call a constructor call. This is an important but subtle distinction: there’s really no such thing as “constructor
functions,” but rather construction calls of functions. When a function is invoked with new in front of it, otherwise known as a constructor call, the following things are done automatically:

  1. A brand new object is created (aka constructed) out of thin air.
  2. The newly constructed object is [[Prototype]]-linked.
  3. The newly constructed object is set as the this binding for that function call.
  4. Unless the function returns its own alternate object, the new invoked function call will automatically return the newly constructed
    object.
function foo(a) {
this.a = a;
}
var bar = new foo( 2 );
console.log( bar.a ); // 2

By calling foo(..) with new in front of it, we’ve constructed a new object and set that new object as the this for the call of foo(..). So new is the final way that a function call’s this can be bound.