JS Scope

JS Tutorial

JS Version

JS Objects

JS Function

JS Classes

JS Async

JS HTML DOM

JS Browser BOM

JS Web API

JS AJAX

JS JSON

JS vs JQUERY

JS Graphics

JavaScript Scope

Block Scope

Before ES6 (2015), JavaScript had only Global Scope and Function Scope.

ES6 introduced two important new JavaScript keywords: let and const.

These two keywords provide Block Scope in JavaScript.

Variables declared inside a { } block cannot be accessed from outside the block:

Example

{

  let x = 2;

}

// x can NOT be used here

Variables declared with the var keyword can NOT have block scope.

Variables declared inside a { } block can be accessed from outside the block.

Example

{

  var x = 2;

}

// x CAN be used here

Local Scope

Variables declared within a JavaScript function, become LOCAL to the function.

Example

// code here can NOT use carName

function myFunction() {

  let carName = “Volvo”;

  // code here CAN use carName

}

// code here can NOT use carName

Local variables have Function Scope

They can only be accessed from within the function.

Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.

Local variables are created when a function starts, and deleted when the function is completed.

Function Scope

JavaScript has function scope: Each function creates a new scope.

Variables defined inside a function are not accessible (visible) from outside the function.

Variables declared with var, let and const are quite similar when declared inside a function.

They all have Function Scope:

function myFunction() {

  var carName = “Volvo”;   // Function Scope

}

function myFunction() {

  let carName = “Volvo”;   // Function Scope

}

function myFunction() {

  const carName = “Volvo”;   // Function Scope

}

Global JavaScript Variables

A variable declared outside a function, becomes GLOBAL.

Example

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Scope</h2>

<p>A GLOBAL variable can be accessed from any script or function.</p>

<p id=”demo”></p>

<script>

let carName = “Volvo”;

myFunction();

function myFunction() {

  document.getElementById(“demo”).innerHTML = “I can display ” + carName;

}

</script>

</body>

</html>

Output

JavaScript Scope

A GLOBAL variable can be accessed from any script or function.

Global Scope

Variables declared Globally (outside any function) have Global Scope.

Global variables can be accessed from anywhere in a JavaScript program.

Variables declared with var, let and const are quite similar when declared outside a block.

They all have Global Scope:

var x = 2;       // Global scope

let x = 2;       // Global scope

const x = 2;       // Global scope