What is function scope in JavaScript?
Function scope in JavaScript refers to the scope of variables and functions that are defined within a function. Variables and functions declared with the var
keyword have function scope.
Variables declared inside a function are accessible only within that function and any nested functions. They are not accessible outside of the function in which they are defined. This means that variables declared within a function cannot be accessed before their declaration or outside of the function.
Example: Here, the variable x
is declared inside the exampleFunction()
function. It is accessible within that function and also within the innerFunction()
nested inside it. However, x
is not accessible outside of exampleFunction()
.
Javascript
function exampleFunction() { var x = 10; // Variable x has function scope console.log(x); // Output: 10 function innerFunction() { console.log(x); // Output: 10 } innerFunction(); } exampleFunction(); // console.log(x); // Error: x is not defined |
Output
10 10
Contact Us