DEV Community

Johan H. Guzman Gil
Johan H. Guzman Gil

Posted on • Edited on

JavaScript - Global variable

Hi, in this episode I will talk about Global variable in JavaScript.

Let's write the next code:

function print(text) {
 var helloWorld = text;
 console.log(helloWorld);
}

print('hello my aliens') // => hello my aliens
console.log(helloWorld) // => error: Uncaught ReferenceError: helloWorld is not defined
Enter fullscreen mode Exit fullscreen mode

The program is going to print the variable helloWorld inside the function but outside the function it will break the code

If we want to have access to the variable hellowWorld outside the function print we need to remove the reserved word var and our code will look like this:

function print(text) {
 helloWorld = text;
 console.log(helloWorld);
}

print('hello my aliens') // => hello my aliens
console.log(helloWorld) // => hello my aliens
Enter fullscreen mode Exit fullscreen mode

And we will see two identical messages.

But the big question is, WHY THIS HAPPENS?
When JavaScript are compiling, and he found the word helloWorld without the reserved word var, it will put the variable helloWorld on top of the file because it thinks that you are going to use it below.

Your compiled code will look like this:

var helloWorld;

function print(text) {
 helloWorld = text;
 console.log(helloWorld);
}

print('hello my aliens') // => hello my aliens
console.log(helloWorld) // => hello my aliens
Enter fullscreen mode Exit fullscreen mode

This method of using the global variable will work but is not recommended. There are multiple ways to have a global variable, but the complexity of the code will determine which one is the correct one. Some example of these are use a session store, create a function that return the value, enums, or use a dictionary

Top comments (1)

Collapse
 
abhishekpakhare97 profile image
Abhishek Ramesh Pakhare

Nice I information you have provided 😁😁