In JavaScript, local scope refers to the accessibility of variables, functions, and objects within a function or a block of code. Variables, functions, and objects declared within a local scope are only accessible within that scope and cannot be accessed outside of it.
In JavaScript, the local scope is created using the var
, let
, or const
keywords to declare variables inside a function or a block of code.
function myFunction() {
var x = 10; // x is a local variable
}
Similarly, the syntax for declaring a local variable using let
or const
keyword is as follows
function myFunction() {
let y = 20; // y is a local variable declared using let keyword
const z = 30; // z is a local variable declared using const keyword
}
Local scope in JavaScript
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
function printMessage() {
let message = "Hello, World!"; // local variable
console.log(message);
}
printMessage();
console.log(message);
</script>
</body>
</html>
Output:
In the above example, the message
variable is declared within the printMessage
function, making it a local variable. This means that it can only be accessed within the printMessage
function and not outside of it.
When we call the printMessage
function, it will log the message
variable to the console. However, when we try to access the message
variable outside of the function, we get a ReferenceError
because the variable is not defined in the global scope.
Differences between function scope and block scope
In JavaScript, variables and functions have different scopes that determine where they can be accessed within a program. The two main scopes in JavaScript are function scope and block scope. Here are the main differences between them:
Feature | Function Scope | Block Scope |
---|---|---|
Declaration Syntax | var or let | let or const |
Accessible in | Function and nested functions | Block where it’s declared |
Scope Length | Extends until the end of the function | Extends until the end of the block |
Visibility | Not visible outside the function | Not visible outside the block |
Declaration Hoisting | Hoisted to the top of the function | Hoisted to the top of the block |
Examples | Variables declared inside a function | Variables declared inside an if statement or for loop |
Function scope:
function myFunction() {
let x = 5; // local variable
console.log(x); // output: 5
}
console.log(x); // output: Uncaught ReferenceError: x is not defined
Block scope:
if (true) {
let y = 10; // block-scoped variable
console.log(y); // output: 10
}
console.log(y); // output: Uncaught ReferenceError: y is not defined
Comment if you have any doubts or suggestions on this JS basic topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version