Ehsan Ghanbari

Experience, DotNet, Solutions

Hoisting in JavaScript

One of the key concepts of every programming language is the Scope. In JavaScript, variable and function scope is a little bit different and so cool! you can have multiple var (variable) in a function, All of them run well if you declare at the top of the function. (although you won't get any kind of error if you declare at the end of the function) For example:

 
console.log(variable);    // undefined

Var variable="something";
Now, notice about the following code:

var x = "something ";

console.log(x); // something

if (true) {

        var x = "another thing";

        console.log(x); // another thing

}

console.log(x); // another thing.

 

As you can see, the value of x changed during the scope and finally, the changed value returned. So in JavaScript, scope affects the outer of its own. Now if you change the above code as a function scope, the output will be different:

 

var x = "something ";

console.log(x); // something

Function Test() {

        var x = "another thing";

        console.log(x); // another thing

};

Test();

console.log(x); // something 
 

The value of x(I mean "another thing) is in the scope of Test function only. so functions create a new scope in JavaScript and block is not a scope just like C#, C++, …

There is another interesting feature in JavaScript, which is about the variable declaration. Take this:

 

 (function () {

        var a = 1;

        alert(a + " and " + b );

        var b = 2;

    })();

 

 

as I mentioned It’s not a syntax or compile error, but if you run this function it will alert "a and undefined". in these cases you should just hoist the variable, Hoisting is the act of moving the declarations to the top of the function. And you should move them on top! the JavaScript looks ahead to find all the variable declarations and hoist them to the top of the function. Variables in JavaScript are hoisted, it means Rather than being available after their declaration, they might actually be available beforehand. So if you hoist the above function's variables, it would be like this:

 

(function () {

        var a = 1;

        var b = 2;

        alert(a + " and " + b );

  })();
 

Rather than variable hoisting, we have function hoisting too, for example:

 

foo();  // TypeError , undefined

foo2(); // defined



Var foo=function(){

       //operation

};



Foo2(){

// operation

};
 

We called the function (I mean foo2()) before the declaration. Notice that foo() is not a function at all in line 1 and function definition hoisting only occurs for function declarations.

 



Object Literals and benefits in java scripts

JavaScript, by default does not come with built-in namespace or class but as it's extremely a flexible language you can create namespace in JavaScript by object literals. Based on wikipedia definition "literal is a notation for representing a fixed value in source code."  you can simply create Object literal by using: 

  1. A colon which separates the property name from value.
  2. A comma which separates each name and value pair from the next.

 

For example:

var myInfo = {
    Name: "Ehsan",
    Age: 25,
    Job: "Developer"
};

 

You can also define the nested object literal like this:

 

var myInfo = {

Info1:{
    Name: "Ehsan",
    Age: 25,
    Job: "Developer" 
    }, 
Info2:{
    Website:"ehsanghanbari.com",
    Mail:"[email protected]"
    }
};

 

Object literals make for good code organization, means of encapsulating data, enclosing it in a tidy package to minimize the use of global variables which can cause problems when combining code. Imagine if you wanted to write all of the code above in your functions, it would be something like stars war!

By using object literal there is no need to invoke constructors directly or maintain the correct order of arguments passed to functions and unobtrusive event handling.

Rather than static values, object literal could contain kinds of value, such as attribute, array or function:

 

Var obj={
        Title: "a good title",
        Books: ["JavaScript", "Domain Driven Design"],
        order:  function() {console.log("blah blah");
           }
}

 

In comparison to the constructor, constructors need to be executed so it will be slower. But object literals need to be parsed (defined) in loading the script.

Note: When you define an object as literal, you build the object by code; so if you use this keyword it will no meaning because it does not exist yet.



Prototypes in JavaScript

JavaScript is a prototypical based language. In JavaScript objects are pairs of keys and values and these keys are Strings. Rather than keys and values, JavaScript objects have one another attribute called prototype which is a pointer to another object. prototype property allows you to add properties and methods to an object.

 In regular form, We can add a property to an object using Object.defineProperty like this:

 

var obj = new Object.create(null);
Object.defineProperties(obj, 'Name', { age: "24", propertyIsEnumerable: true });

 

But in inheritance, JavaScript only has one construct: objects and each object has an internal link to another object called the prototype. It is a prebuilt object that simplifies the process of adding custom properties and methods to all instances of an object. You can add a prototype to an existing function:

 

function Person(name, family) {
    this.name = name;
    this.family = family;
}

var obj = new Person("ehsan", "Ghanbari");
obj.prototype.age = "23";

 

Functions can be used to create class-like functionality in JavaScript, and all functions have a prototype property. a prototype is actually an instance of an object and every function in JavaScript has one whether you use it or not(like the constructor in C#). Here is another example of using prototype:

 

function Car(color,model) {
    this.color = color;
    this.model = model;
}
Car.prototype.manufacturer = 'hunda';

var santafe = new Car("white", "new");

 

Read more:

  1. http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype

 



JavaScript Variables

Variables store information so that it can be used later! Like many other programming languages, JavaScript has variables. JavaScript variables can hold a value of any data type. A variable's value can change during the script.

 

Var name;
Var age;
Var x,y,z;

 

Note: If you try to assign a value to a non-existent variable, JavaScript will create the variable for you.

You can refer to a variable by name to see its value or to change its value. The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically.

Note: JavaScript variable names are case sensitive. And it's better to start with a letter or underscore "_".

 

Variable Scope

Local Variables:

For example parameters of a function is always local to the same function:

 

 function sample( name, family) {
        name = "ehsan";
        family = "ghanbari";
    }

 

local variables are available only within the section of code in which they were defined

 

Global variable:

A global variable has the global scope which means it is defined everywhere in your JavaScript code. Take a look at this example:

 

var culture = "something";                       
function sample( ) {
   base.culture = "base culture";                          
   return null;
}

function sample2() {
   var localVar="this culture";                    
   return null;

}

 

Definitely, the variable in the sample is global (because of base) and the one in sample2 is local.

 

Read more:

  1. http://www.tutorialspoint.com/javascript/javascript_variables.htm
  2. http://webcheatsheet.com/javascript/variables.php



About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
using Log4net in asp.net MVC4
How to use PagedList In asp.net MVC
Redis as a cache server
Domain driven design VS model driven architecture
What's the DDD-lite?
Multiple submit buttons in asp.net MVC