JavaScript - ScopeBlock Scope : Before ES6 (2015), JavaScript variables 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, are LOCAL to the function:
< !DOCTYPE html>
< html>
< body>
< h2>JavaScript Scope< /h2>
< p>< b>carName< /b> is undefined outside myFunction():< /p>
< p id="demo1">< /p>
< p id="demo2">< /p>
< script>
function myFunction() {
let carName = "Mahindra";
document.getElementById("demo1").innerHTML = typeof carName + " " + carName;
}
myFunction();
document.getElementById("demo2").innerHTML = typeof carName;
< /script>
< /body>
< /html>
Output :JavaScript ScopecarName is undefined outside myFunction(): string Mahindra undefined 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 = "Mahindra"; // Function Scope
}
function myFunction() {
let carName = "Mahindra"; // Function Scope
}
function myFunction() {
const carName = "Mahindra"; // Function Scope
}
Global JavaScript Variables
A variable declared outside a function, becomes GLOBAL.
< !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 = "Mahindra";
myFunction();
function myFunction() {
document.getElementById("demo").innerHTML = " Car company name is : " + carName;
}
< /script>
< /body>
< /html>
Output :JavaScript ScopeA GLOBAL variable can be accessed from any script or function. Car company name is : Mahindra Global Variables in HTML : With JavaScript, the global scope is the JavaScript environment.In HTML, the global scope is the window object. Global variables defined with the var keyword belong to the window object:
< !DOCTYPE html>
< html>
< body>
< h2>JavaScript Scope< /h2>
< p>In HTML, global variables defined with < b>var< /b>, will become window variables.< /p>
< p id="demo">< /p>
< script>
var carName = "Toyota";
// code here can use window.carName
document.getElementById("demo").innerHTML = "I can display " + window.carName;
< /script>
< /body>
< /html>
Output :JavaScript ScopeIn HTML, global variables defined with var, will become window variables. I can display Toyota « Previous Next Topic » (JS - Date and Math Objects) |