JavaScript Scope

Scope

 
In JavaScript, scope refers to the current context of code.

A variable’s scope is the context in which the variable exists.

The scope specifies from where you can access a variable and whether you have access to the variable in that context.

In JavaScript, a variable can be globally or locally defined

 

Local Scope

 
Variables declared with “var” keyword inside a function have local scope within the function. They can not be accessed outside the function.

For example :

function hello() {
  var strName = "John";
  // Code inside hello() can use variable strName
  alert("Inside function, name = " + strName);
}

// Code outside hello() can't use variable strName
alert("Outside function, name = " + strName);

A variable with local scope exists only within the confines of the function in which it was created.

 

Global Scope

We can create global variables in following ways :
 

1) Declare the variable using a var statement outside any function.


var strName = "Dave";

function hello() {
  // prints Dave
  console.log("Inside function, name = " + strName);
    strName = "John";
}
hello();
// prints John
console.log("Outside function, name = " + strName);

 

2) Omit the var statement while declaring a variable.

Even within a function scope, if you omit the var statement while declaring a variable, it’s created by default in the global scope.

function hello() {
    strName = "John";
    return strName;
}

strName = "Dave";
var str = hello();
alert("name = " + strName);

 
In the above example, you may be expecting the alert to display:

name = Dave

However, it displays :

name = John

That’s because the global variable strName has been overridden inside the function.

Defining global variables pollutes the common namespace shared by everyone, introducing the possibility of accidental name collisions.

So, unless you intend a variable to be shared throughout your program, always declare it with var.

 

Summary:

  1. Avoid declaring global variables.
  2. Declare variables as locally as possible.
  3. Avoid adding properties to the global object.
  4. Use the global object for platform feature detection.

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags