What is block scope in JavaScript?
Last Updated :
14 Feb, 2024
Block scope in JavaScript refers to the scope of variables and functions that are defined within a block of code, such as within a pair of curly braces {}
. Variables and functions declared with let
and const
keywords have block scope.
Variables declared inside a block are only accessible within that block and any nested blocks. They are not accessible outside of the block in which they are defined. This means that variables declared within a block cannot be accessed before their declaration or outside of the block.
Example: Here, the variable x
is declared inside the block created by the if
statement. It is accessible within that block but not outside of it. If you try to access x
outside of the block, you’ll get a reference error because x
is not defined in that scope.
Javascript
function exampleFunction() {
if ( true ) {
let x = 10;
console.log(x);
}
}
exampleFunction();
|
Share your thoughts in the comments
Please Login to comment...