Open In App

Global and Local variables in JavaScript

Last Updated : 20 May, 2024
Like Article

Global Variable

Global variables are those defined outside of any function, making them accessible from anywhere within the script. Regardless of the keyword used for declaration, they all behave similarly and possess a global scope. Even variables declared without a keyword inside a function are considered global.

Local Variable

When you use JavaScript, local variables are defined within functions in JavaScript. They are confined to the scope of the function that defines them and cannot be accessed from outside. Attempting to access local variables outside their defining function results in an error.

How to use variables

  • The scope of a variable or function determines what code has access to it.
  • Variables that are created inside a function are local variables, and local variables can only be referred to by the code within the function.
  • Variables created outside of functions are global variables, and the code in all functions has access to all global variables.
  • If you forget to code the var keyword in a variable declaration, the JavaScript engine assumes that the variable is global. This can cause debugging problems.
  • In general, it’s better to pass local variables from one function to another as parameters than it is to use global variables. That will make your code easier to understand with less chance of errors.

Example 1: In this example, we will declare variables in the global scope so that they can be accessed anywhere in the program.

let petName = 'Rocky' // Global variable

function myFunction() {
    fruit = 'apple'; // Considered global
    console.log(typeof petName +
        '- ' +
        'My pet name is ' +

    typeof petName +
    '- ' +
    'My pet name is ' +
    petName +
    'Fruit name is ' +

string- My pet name is Rocky
string- My pet name is RockyFruit name is apple

Explanation: We can see that the variable petName is declared in the global scope and is easily accessed inside functions. Also, the fruit was declared inside the function without any keyword so it was considered global and was accessible inside another function. 

Example 2: In this example, we will declare variables in the local scope and try to access them at different scopes.

let petName;
function myfunction() {
    let petName = "Sizzer"; // local variable
function anotherFunc() {
    let petName = "Tom"; // local variable


Explanation: We can see that the variable petName is declared in global scope but not initialized. Also, the functions are accessing the inner variable where each function has its own value for the variable petName.

Where to use which variable

  • It’s tempting to resort to global variables for their apparent simplicity, but they often lead to issues. Since any function can modify a global variable, it’s easy to unintentionally alter them or make errors like misspelling variable names, especially in larger applications. Debugging such issues can become cumbersome.
  • In contrast, local variables offer a solution by reducing the risk of naming conflicts. Different functions can use identical names for local variables without causing clashes. This minimizes errors and debugging challenges. Therefore, except for a few specific cases, it’s advisable to encapsulate code within functions to ensure variables remain local.
  • Remember, misspelling a variable name that’s already declared results in a new global variable being created. To prevent this, always declare variables with keywords and ensure they’re declared before use in the code.

Note: Use local variables whenever possible. Always use the var keyword to declare a new variable before the variable is referred to by other statements.

Previous Article
Next Article

Similar Reads

Difference between global and local variables in Postman
Postman is a powerful API development tool which offers a feature known as environment variables. These variables are used for efficient testing and development of APIs by allowing users to manage dynamic values across requests easily. Table of Content Difference between global and local variables in PostmanSteps to create Global VariableSteps to c
3 min read
JavaScript Global Variables
What are global variables in JavaScript?JavaScript Global Variables can be accessed outside any function or block. JavaScript global variables are declared within the window object or outside any block or scope. A variable declared without a keyword is also considered global even though it is declared in the function. Below are some examples to see
1 min read
How to declare Global Variables in JavaScript ?
Global Variables Global variables in JavaScript are variables declared outside of any function. These variables are accessible from anywhere within the script, including inside functions. Global variables are declared at the start of the block(top of the program)Var keyword is used to declare variables globally.Global variables can be accessed from
2 min read
Why to avoid global variables in JavaScript ?
Global variables are variables that are declared or defined outside any functions in the script. This indicates that global variables can be accessed from anywhere in the particular script and are not restricted to functions or blocks. JavaScript global variables can also be declared from within a function or block and then can be accessed from any
4 min read
What is local, script and global scope in Node.js ?
Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that NodeJS is not a framework and it’s not a programming language. Most people are confused and understand it’s a framework or a programming language. We often use Node.js for building back-end services like APIs l
4 min read
JavaScript Local Variables
What are Local Variables in JavaScript?JavaScript local variables are declared inside a block ({} curly braces) or a function. Local variables are accessible inside the block or the function only where they are declared. Local variables with the same name can be used in different functions or blocks. Local variables are deleted after a function is
2 min read
How to create and use global variables in Postman?
Postman is an API(application programming interface) development tool that helps to build, test and modify APIs. It can make various types of HTTP requests(GET, POST, PUT, PATCH), save environments for later use, and convert the API to code for various languages(like JavaScript, and Python). In this article, we will learn How do you create and use
2 min read
How to Add or Apply Global Variables in VueJS ?
In Vue.js, we can have global variables that are applied by attaching them to the Vue instance prototype. These are accessible throughout the components of the application. This is helpful for data management and sharing. In this article, we will see the two different approaches to adding or applying global variables in VueJS with practical example
3 min read
How to Create Global Variables Accessible in all Views using Express/NodeJS ?
In Express.js, global variables can be immensely useful for sharing data across multiple views or middleware functions. Whether it's storing user authentication status, site-wide configurations, or any other frequently accessed data, global variables streamline development and enhance code organization. Table of Content Using app.localsUtilizing re
4 min read
Explain the concept of local variables in Postman.
Variables enable you to store and reuse values in Postman. By storing a value as a variable, you can reference it throughout your collections, environments, requests, and test scripts. Variables help you work efficiently, collaborate with teammates, and set up dynamic workflows. In this article, we will learn The concept of local variables in Postm
2 min read