Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Dec 14, 2016

Hoisting in Javascript

You might have heard of Flag hoisting , but what the fuck is hoisting in JavaScript ?
There are two types of hoisting, variable hoisting and function hoisting.


Variable hoisting :


By default JavaScript move all declarations to the beginning of the current scope or current function.

Example 1 : Variable hoisting in very outer scope

x = 5; // Assign/defining 5 to x
console.log(x)                  
var x; // Declare x 
BUT this is How it will be Executed
var x; // Declare x 
x = 5; // Assign/defining 5 to x
console.log(x)   
Observation : See the difference var x; // Declare x   is set to the beginning for scope  

Nov 29, 2016

Closures In Javascript

Actual understanding : Closure is a function that stays alive or connected to its parent Scope or parent function even after Parent scope or parent functions execution is over.


Problem : Suppose you are told to write a function that increments counter value by 1, What will you do ?


Obviously We would Code
var counter = 0;

function add() {
    return counter += 1;
}
add(); //Outputs 1
add(); //Outputs 2
add(); //Outputs 3

Jun 13, 2016

Javascript Prototypes For Performance

Without Prototype : Lots of memory per object
  • Each time when you create object from below vehicle function,
  • the line function(name){  this.name = name;  }  is alocated memory each time the object is created,
  • so there are multiple instances of same function.
function vehicle(){
    this.name = 'truck';
    this.set_name = function(name){ 
        this.name = name; 
    }
}
var taxi = new vehicle();