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.
Example:
// This part of code cannot use firstName
function myFunction() {
let firstName = "Krishna";
// This part of code can use firstName
}
This part of code cannot use firstName
Example: Below is an example of Local scope.
Javascript
function foo() { var x = '1' ; console.log( 'inside function: ' , x); } foo(); // Inside function: 1 console.log(x); // Error: x is not defined |
Output (In Console):
inside function: 1
x is not defined
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