In JavaScript, there is a function scope concept, where each function creates a new scope. Variables that are declared inside a function are called local variables and in the function scope.
// The following variables are defined in the global scope
var num1 = 20,
num2 = 3,
name = 'Chamakh';
// This function is defined in the global scope
function multiply() {
return num1 * num2;
}
multiply(); // Returns 60
// A nested function example
function getScore() {
var num1 = 2,
num2 = 3;
function add() {
return name + ' scored ' + (num1 + num2);
}
return add();
}
getScore(); // Returns "Chamakh scored 5"
Note: Variables declared with let and const in a function are pretty similar when using var inside a function.
JavaScript Function Scope
Simple example code variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function.
However, a function can access all variables and functions defined inside the scope in which it is defined.
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
// Function Scope variables
var car1 = "Volvo";
var car2 = "BMW";
var car3 = "Tesla";
console.log(car1,car2,car3)
}
myFunction();
console.log(car1,car2,car3)
</script>
</body>
</html>
Output:
Comment if you have any doubts or suggestions on this JS 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