JavaScript Tutorial

Javascript Scope

Scope in JavaScript refers to the accessibility or visibility of variables, functions, and objects within a particular part of the code. It determines where variables and functions can be accessed and used.

JavaScript has two main types of scope:

Global scope

Variables declared outside of any function or block have global scope. They can be accessed from anywhere in the code, including inside functions and blocks.

Input:-

Output:-

The variable message is global scoped. It can be accessible everywhere in the script.

Local scope

Variables declared within a function or block have local scope. They are only accessible within the specific function or block where they are defined.

Input:-

Output:-

When the JavaScript engine executes the say() function, it creates a function execution context. The variable message that declares inside the say() function is bound to the function execution context of say() function, not the global execution context.

So this variable will have access within the function only, not outside of it.

Input:-

Output:-

In the above code, if we use the variable without calling the function, then the variable will be undefined, and the input won't be generated. In this case, the error will generate related to the undefined variable.

Go back to Previous Course