Local and Global Variable in Javascript

Rumman Ansari   Software Engineer   2023-03-26   5539 Share
☰ Table of Contents

Table of Content:


  • Scope refers to the part of the program in which a variable can be accessed.
  • JavaScript has two types of scopes: Local and Global.
  • Variables with global scope can be accessed anywhere in the program, and the variables with a local scope can be accessed within the block or function within which they are declared.

Example Here name1 is a global variable and name2 is a local variable


var name1 = "ben";
myFunction();
function myFunction() {
var name2 = "bob";
   console.log(name1);
    console.log(name2);
    }
  console.log(name2);

Console

ben
bob
Uncaught ReferenceError: name2 is not defined

Here's a table that explains the difference between local and global variables in JavaScript:

Feature Local Variables Global Variables
Scope Defined within a function block or code block, they are only accessible within the block they are declared in. Defined outside of any function or code block, they are accessible from anywhere in the code, including inside functions or code blocks.
Lifetime Created when the function or code block is executed, and destroyed when the function or code block completes execution. Created when the script is loaded, and destroyed when the page is closed or the script is unloaded.
Access Can only be accessed within the function or code block where they are declared. Can be accessed from anywhere in the code, including within functions or code blocks.
Naming Conflicts Cannot cause naming conflicts with variables declared in other functions or code blocks, or with global variables. Can cause naming conflicts with variables declared in other functions or code blocks, or with other global variables, leading to unexpected results.
Memory Usage Uses less memory than global variables, as they are created and destroyed only when the function or code block is executed. Uses more memory than local variables, as they are created and stored in memory throughout the entire script execution.
Performance Generally faster than global variables, as they can be accessed more quickly due to their limited scope. Generally slower than local variables, as they are accessed more slowly due to their global scope and potential naming conflicts.