A JavaScript block-scoped means that the variable defined within a block will not be accessible outside the block. Variables declared inside a { } block cannot be accessed from outside.
{
let variable_name = value;
}
// varibele can NOT be used here
ES6 introduced two important new JavaScript keywords: let
and const
to provide Block Scope in JavaScript.
Note: Variables are accessed from outside the block If you use var
keyword to declare a variable inside a { } block.
JavaScript Block scope examples
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
{
let x = 100;
console.log(x)
}
console.log(x)
</script>
</body>
</html>
Output:
Function level (Local) Scope
Variables declared within a JavaScript function, become LOCAL to the function. The variables in this scope level are restricted to access only inside the function where it is declared.
Variables declared with var
, let
and const
are quite similar when declared inside a function.
function myFunction() {
let carName = "Maruti";
// var carName = "ABC";
// const carName = "XYZ";
// code here CAN use carName
}
// code here can NOT use carName
Global Scope
A variable declared outside a function becomes GLOBAL, it can be accessed from anywhere in a JavaScript program. You can use var
, let
and const
to declare it.
let a = "hello";
function greet () {
console.log(a);
}
greet(); // hello
Do comment if you have any doubts or suggestions on this JS variable scope topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version