Powered by Blogger.

Knowledge Dojo

    • Home
    • JavaScript
    • _Concepts
    • Unity
    • C#
    • About
    • Contact

    Hoisting is a process in which all variables and method declarations are moved to the top of the executing program, no matter at what position we write them.
    In other words, a variable or a function can be used even before its declaration in a code block.
    doSomething();
    
    function doSomething()
    {
       val = 10;
       val += 11;
    
       console.log(val);
    
       var val;
    }
    
    Output
    21

    Here, we are assigning (val=10), altering (val += 11) and logging (console.log) the value of the variable val even before the declaration of the variable. Also, we are calling the method before its declaration and still the code is working. This mechanism is called Hoisting.
    Now, consider this hoisting mechanism:
    function doSomethingNew()
    {
       console.log(val);
       var val = 10;
    }
    
    doSomethingNew();
    Output
    undefined
    Calling the doSomethingNew() method gives undefined. But why?
    This is because the interpreter follows a defined flow which involves:
    Javascript interpreter flow

    In doSomethingNew() method, the variable val is declared first.
    In javascript, all variables are initialized with the default value undefined.
    Then we log the variable on Line 3 which will give undefined. Finally, the value 10 would get assigned to the variable val.
    So the actual code created by the interpreter would look like:
    function doSomethingNew()
    {
       var val;
       console.log(val);
    
       val = 10;
    }
    
    doSomethingNew();
    
    Now, using the val after assigning it value will give its value as 10 like the code below.
    function doSomethingAgain()
    {
       console.log(val);
       var val = 10;
       console.log(val);
    }
    
    doSomethingAgain();
    
    Output
    undefined
    10

    Scope for Hoisting

    The scope for hoisting is limited to the code block in which the code is executing. This means we are able to access the variables only in the code block where the variable is accessible.
    var a;
    
    function demo()
    {
       a = 10;
       var b = 20;
    
       console.log("Inside demo function");
       console.log(a);
       console.log(b);
    }
    
    demo();
    
    console.log("Outside demo function");
    console.log(a);
    console.log(b);
    
    Output
    Inside demo function
    10
    20
    Outside demo function
    10
    Uncaught ReferenceError: b is not defined
    As you can see, we get a reference error when we try to access the variable b outside demo function. This is because the scope of variable b is limited to demo method and we cannot use it outside.

    Strict Mode

    ES5 has a strict mode that prevents hoisting. All we need to do is to write 'use strict'; statement before the javascript code and the browser will give an error stating that the variable is not defined in case of hoisting.
    Function Arguments

    In a Javascript method, there exists a variable named “arguments” that contains all the parameters passed in the function call. “arguments” is an array like object which contains parameters at indices and a property “length”. 

    function add()
    {
        var sum = 0;
        for( var i=0; i < arguments.length; i++ )
        {
            sum += arguments[i];
        }
        return sum;
    }
    
    add(1,2); // gives result 3 i.e. 1 + 2
    add(1, 2, 3, 4); // gives result 10 i.e. 1 + 2 + 3 + 4
    
    arguments is not a real array so you won’t be able to push or pop elements from it directly without converting it into real array.
    To convert arguments into array, use:
    var args = Array.prototype.slice.call(arguments, 0);


    Breaking a ForEach loop

    Consider you are given an array named arr of integers containing the following values:

    var arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]; 

    If you are asked to iterate through the values in the loop, you may use the code like:

    arr.forEach( function(value){
     console.log('Current value: '  + value);
    });
    

    Javascript forEach loop demonstration

    If you are asked to break the loop as soon as you find the value 5. You will write a break statement just below the console.log statement. The code will look like this:

    arr.forEach( function(value){
     console.log(‘Current value: ‘ + value);
     if (value == 5)
      break;
    });
    

    But, the above code doesn’t work and gives the following error while executing.


    Javascript forEach loop with break statement does not work

    The reason for this error is that forEach is a method and you cannot use break statement inside method. So. you cannot use break statement in forEach method.

    How to break then?
    Well, you cannot break a forEach in Javascript. 
    Instead you can use alternative to forEach method i.e. every method which returns a boolean for each value that determines whether the execution should be continues if the return value is true or to stop iterating if the return value is false.


    arr.every(function(element, index) {
     // Do your thing, then:
     if (element == 5) 
     {
      console.log("Breaking...");
      return false;
     }
       else 
     {
      console.log("Current Value: " + element);
      return true;
     }
    });
    

    Using every in javascript to break execution

    Parentheses position matters
    Consider these two javascript methods:
    function foo()
    {
     return
     {
      data:0
     }
    }
    function bar()
    {
     return {
      data:0
     }
    }
    Notice what happens when you call foo() and bar().

    parentheses position matters in javascript methods

    Calling foo() gives result undefined while calling bar() gives an object.
    You can try this in the browser's console window in the inspector.
    This is because, in Javascript, the position of parentheses matters.

    In method 
    foo(), the return statement is executed and it returns the control to the caller. Since there is nothing against return statement so it gives undefined.

    In method bar(), the return statement has a parenthesis starting against it so it processes the block until the closing parentheses and the object are returned to the caller.
    Older
    ARTICLES

    IEnumerable vs ICollection vs IList vs IQueryable in C#

    Popular Posts

    • Object Creation Patterns in Javascript
    • IEnumerable vs ICollection vs IList vs IQueryable in C#

    Created with by BeautyTemplates

    Back to top