7. How does JavaScript define the scope of variables? Explain with the help of an example.
medium

In JavaScript, the scope of a variable refers to the visibility and accessibility of that variable within the program. There are two main types of scopes in JavaScript: global scope and local scope.


Global scope is the default scope in JavaScript, which means that variables defined outside of any function or block will be accessible from anywhere within the program. Global variables are created in the global object, which is a special object in JavaScript that contains all of the globally available functions and objects. Here is an example of a global variable:

var globalVar = "Hello, World!";
console.log(globalVar); // Outputs "Hello, World!"

In this example, the globalVar variable is defined outside of any function or block, and can be accessed from anywhere within the program.

Local scope, on the other hand, refers to the visibility and accessibility of variables within a specific function or block. Local variables are created when a function is called, and they exist only within that function. Here is an example of a local variable:

function myFunction() {
  var localVar = "Hello, World!";
  console.log(localVar); // Outputs "Hello, World!"
}
myFunction();
console.log(localVar); // Outputs "ReferenceError: localVar is not defined"

In this example, the localVar variable is defined within the myFunction() function, and can only be accessed from within that function. When the function is called, the localVar variable is created and its value is printed to the console.

However, when the function is finished executing, the localVar variable is no longer accessible, and a "ReferenceError" is thrown if it is tried to access it outside of the function.