Global scope
Variables declared Globally (outside of any function) have Global Scope and Global variables can be accessed from anywhere in a program. Similar to function scope variables declared with var, let and const are quite similar when declared outside a block.
let keyword:
let x = 2; // Global scope
const keyword:
const x = 2; // Global scope
var keyword:
var x = 2; // Global scope
Example: Below is an example of Global scope.
Javascript
// Global scope var x = '1' const y = '2' let z = '3' console.log(x); // 1 console.log(y); // 2 console.log(z); // 3 function getNo() { console.log(x); // x is accessible here console.log(y); // y is accessible here console.log(z); // z is accessible here } getNo(); |
1 2 3 1 2 3
What is Variable Scope in JavaScript ?
Variable scope is the context of the program in which it can be accessed. In programming, a variable is a named storage location that holds data or a value. Think of it as a container that you can use to store and manipulate information in your code. Variables allow you to work with data in a flexible way, as the values they hold can change during the execution of a program.
Table of Content
- Variable Scope
- Block scope
- Function scope
- Local scope
- Global scope
In JavaScript, you can declare variables using the var
, let
, or const
keywords. Here’s a brief overview of each:
Variable Declaration |
Description |
---|---|
The oldest way to declare variables. It has function scope and is hoisted. |
|
Introduced in ECMAScript 6 (ES6). It has block scope and is also hoisted. |
|
Also introduced in ES6. It is used to declare constants and has block scope. Unlike |
Now, let’s delve into the concept of Variable Scope in JavaScript:
Contact Us