Scope in Functions


Scope decides where a variable can be used in a program. In JavaScript, variables can have different scopes depending on where they are created.

When variables are created inside a function, they are only available inside that function. This helps protect data and prevents conflicts between different parts of the program.

Understanding scope is very important for writing safe, clean, and bug-free JavaScript code.

Types of Scope in JavaScript

  1. Global Scope  – variables declared outside functions 
  2. Local Scope   – variables declared inside functions 
  3. Block Scope   – variables declared using let or const inside { }

Knowing these scopes helps you control how data is shared in your program.

Here, the variable message is created outside the function, so it is available everywhere in the program.

This is called a global variable.

In this example, the variable number is created inside the function. It can only be used inside that function.

Trying to use it outside will cause an error because it does not exist there.

This example shows block scope. The variable value exists only inside the if block.

By understanding scope, students can avoid common mistakes, protect data, and write professional-quality JavaScript code.