Monday

Javascript tips

Some important concepts:

1.  "hoisting" : Javascript moves all declarations to the top before executing the code. It other words, a variable can be used before it is declared.

Advice: If you want to avoid confusion, declare variables at the beginning of the function.
Note: Javascipt does this only for declarations. Initializations aren't hoisting to the top.
<script>
    var x = 3;  
    elem = document.getElementById("demo");      
    elem.innerHTML = "x is " + x + " and y is " + y; 
    var y = 4;  
    //result: x is 3 and y is undefined
</script>



<script>
    var x = 3; 
    var y;
    elem = document.getElementById("demo");      
    elem.innerHTML = "x is " + x + " and y is " + y; 
    y = 4;  
    //result: x is 3 and y is undefined
</script>



<script>
    var x = 3; 
    var y = 4; 
    elem = document.getElementById("demo");      
    elem.innerHTML = "x is " + x + " and y is " + y; 
    //result: x is 3 and y is 4
</script>


<script>
    x = 3; 
    y = 4; 
    elem = document.getElementById("demo");      
    elem.innerHTML = "x is " + x + " and y is " + y; 
    var x, y;
    //result: x is 3 and y is 4
</script>

2.  
var a = 1 >> declares the variable in the current scope which can be local or global.
       a = 1 >> if the variable couldn't be found anywhere in the scope chain, it becomes global.This usage is very bad practice!!!

3.  Arrow functions aren't same with regular functions. 'this' keyword not bound to the element when it is used in arrow functions.
Try not to use arrow functions with constructors, click handlers, class/object methods!



No comments:

Post a Comment