Friday, December 5, 2014

Scope in Javascript

JavaScript has two scopes : global scope and local scope
A variable declared inside a function definition has local scope
A variable declared outside a function definition has global scope

var name = "deepak";
function address() {
var location = "delhi";
}
view raw gistfile1.js hosted with ❤ by GitHub

"name" variable has global scope to the window object
"address" function has global scope to the window object
"location" variable has local scope to the function address()

When a variable declared without the keyword var then that variable become global variable.
 
var name = "deepak";
function address() {
var location = "delhi";
job = "Javascript Developer";
}
view raw gistfile1.js hosted with ❤ by GitHub

here "job" variable has global scope to the window object

A local variable can only be used inside the function where it is defined. It is hidden from outside the function. Global variable can be used anywhere in the program.

var name = "deepak";
function address() {
var location = "delhi";
job = "JavaScript Developer";
console.log(location);
}
console.log(name); // "deepak"
address(); // "delhi"
console.log(job); // "JavaScript Developer"
view raw gistfile1.js hosted with ❤ by GitHub

Lifetime of JavaScript variables

local variables are created when the function is invoked and garbage collected when the execution of function is completed. Global variables is created when it is declared and garbage collected when you close the page. So global has lifetime in the entire program.

var name = "deepak";
function address() {
var location = "delhi";
job = "JavaScript Developer";
}
console.log(name); // "deepak"
address();
console.log(job); // "JavaScript Developer"
console.log(location); // error
view raw gistfile1.js hosted with ❤ by GitHub

No comments:

Post a Comment