DEV Community

Cover image for Think Like JavaScript: Where Does Your Variable Live?
s mathavi
s mathavi

Posted on

Think Like JavaScript: Where Does Your Variable Live?

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.

Block scope

Earlier JavaScript had only Global Scope and Function Scope. let and const are the two new important keywords that were introduced by the ES6 and these two keywords provide Block Scope in JavaScript.Variables that are declared inside a { } block cannot be accessed from outside the block.

let variable!!

{
 let x = 2;
}
x cannot be used here
Enter fullscreen mode Exit fullscreen mode

var variable!!

{
 var x = 2;
}
x can be used here

Enter fullscreen mode Exit fullscreen mode

Function scope

JavaScript has function scope and each function creates a new scope. Variables defined inside a function are not accessible from outside the function and variables declared with var, let and const are quite similar when declared inside a function.

var variable!!

function myFunction() {
   var firstName = "Krishna";   // Function Scope
}
Enter fullscreen mode Exit fullscreen mode

let variable!!

function myFunction() {
let firstName = "Krishna"; // Function Scope
}

Local scope

Variables declared inside a function become local to the function. Local variables are created when a function starts and deleted when the function is executed. Local variables have Function Scope which means that they can only be accessed from within the function.

function foo() {
    var x = '1';
    console.log('inside function: ', x);
}

foo();          // Inside function: 1
console.log(x); // Error: x is not defined
Enter fullscreen mode Exit fullscreen mode

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

// 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();
Enter fullscreen mode Exit fullscreen mode

Reference From:https://www.geeksforgeeks.org/javascript/what-is-variable-scope-in-javascript/

Top comments (0)