Loading...

Javascript Global Variables-How to create and access them in JS

Javascript Global Variables-How to create and access them in JS

What are the variables in JS?

Variables in JavaScript are containers that can store values that can be accessed, updated, or used as and when required by the user. An important idea that we should understand is that variables aren’t themselves values but they are sort of like boxes where different values can be stored and modified.

let name = Jack; var age = 20;
Code language: JavaScript (javascript)

We can declare variables in javascript using “var“.Both these keywords allow the declaration of a variable. Now an obvious question is why we require two keywords to perform the same function. This is where the concept of scoping comes into the picture.

What is scope in JS?

Scope in JavaScript refers to the current context of code, which determines the accessibility of variables to JavaScript. The two types of scope are local and global:

  • Global variables are those declared outside of a block(using var, window object).
  • Local variables are those declared inside of a block(using let, const).

Global Variables

Variables defined outside any function, block, or module scope have global scope. We can access variables in global scope from any point in the application. Global variables are available for the lifetime of the application.

A variable declared inside a function will be undefined when called from outside the function:

function getUsername() { var username = "Jack"; } getUsername(); console.log(`Outside function : ${username}`);
Code language: JavaScript (javascript)

When we run the code above, JavaScript will throw the ReferenceError: username is not defined on the console.log() line. This is because the username variable scope is limited locally inside the getUsername function, so it can’t be accessed outside the function.

But when we declare the variable outside of the function, we can log the variable both inside and outside the function:

var username = "Jack"; function getUsername() { console.log(`Inside function : ${username}`); } getUsername(); console.log(`Outside function : ${username}`);
Code language: JavaScript (javascript)

We will see both console.log can access the username variable because it’s considered a global variable:

OUTPUT > Inside function : Jack > Outside function : Jack
Code language: JavaScript (javascript)

Global variables that we declared are kept inside a global object. In the browser, our global variables are automatically assigned as a property of the window object. We can access the username variable using username or window.username as in the following example:

var username = "Jack"; console.log(`window.username: ${window.username}`);
Code language: JavaScript (javascript)

But this kind of behavior is only triggered when we create a variable using the var keyword. Variables created with either the let or const keyword won’t be assigned as a property of the window object.

let username = "Jack"; console.log(`window.username: ${window.username}`); // window.username: undefined
Code language: JavaScript (javascript)

Var statement

The var statement declares a function-scoped or globally-scoped variable, optionally initializing it to a value. var declarations, wherever they occur, are processed before any code is executed. This is called hoisting and is discussed further below.

Variable hoisting

Another unusual thing about variables in JavaScript is that we can refer to a variable declared later, without getting an exception.

Variable hoisting JS

This concept is known as hoisting. Variables in JavaScript are, in a sense, “hoisted” (or “lifted”) to the top of the function or statement. However, variables that are hoisted return a value of undefined. So even if we declare and initialize after we use or refer to this variable, it still returns undefined.

/** * Example 1 */ console.log(x === undefined); // true var x = 3; /** * Example 2 */ // will return a value of undefined var myvar = 'my value'; (function() { console.log(myvar); // undefined var myvar = 'local value'; })();
Code language: JavaScript (javascript)

The above examples will be interpreted the same as:

/** * Example 1 */ var x; console.log(x === undefined); // true x = 3; /** * Example 2 */ var myvar = 'my value'; (function() { var myvar; console.log(myvar); // undefined myvar = 'local value'; })();
Code language: JavaScript (javascript)

Because of hoisting, we should try to place all var statements in a function as near to the top of the function as possible. This best practice increases the clarity of the code.

let and const are hoisted but not initialized. Referencing the variable in the block before the variable declaration results in a ReferenceError, because the variable is in a “temporal dead zone” from the start of the block until the declaration is processed.

console.log(x); // ReferenceError const x = 3;
Code language: JavaScript (javascript)

Creating Global Variables

We can create global variables by creating a property of the global object. In the browser context, this means that we create it as a property of the window object. In web pages, the global object is a window, so you can set and access global variables using the window.variable syntax.

There’re a few ways to do this. One way is to define it as a property of the window object. Then we can reference it as foo or window.foo anywhere in our code.

window.foo = 1;
Code language: JavaScript (javascript)

Another way is to use the var keyword in the top level of our code. That is, it’s not nested in any block. We can define it as follows,

var foo = 1;
Code language: JavaScript (javascript)

Accessing global variables

We can get and set global variables just like how we declared it. For example, if we declared:

window.foo = 1;
Code language: JavaScript (javascript)

Then we can reference window.foo and assign values to them. If we declare it with var at the top level as in:

var foo = 1;
Code language: JavaScript (javascript)

Then we can either write:

foo = 1; //or window.foo = 1;
Code language: JavaScript (javascript)

Accessing a global variable is required a lot of times. If a variable is going to be used throughout the program it is important that we declare the variable in the global scope. But, because JavaScript allows the re-declaration of the same variables, it can easily become a problem if a function is using a variable with the same name as a global variable in its scope.

Normally accessing this variable’s value will return the value of the current scope variable. For example,

var age = 21; function checkAge() { var age = 18; console.log(age); // Output: 18 } checkAge();
Code language: JavaScript (javascript)

Here, the function’s age variable overshadows the global age variable. This is the default behavior in not only JavaScript but some other languages as well. But JavaScript has the answer to this problem.

Using the global window object, we can access the global variable. The window object is the global object that represents the browser window. All the variables declared in the global scope become the variable of the window object. To access this window object, we have to use the object dot notation.

window.age; //Assign a value window.age = 30;
Code language: JavaScript (javascript)

Why global variables should not be used frequently?

Software developers “globally” consider creating global variables bad for a reason.

First, because they can access the variable from anywhere, that means any part of our code that calls the variable can change its value. This means any other developer will find it hard to reason about the role that the variable plays in our code. This also makes it hard to debug when we find errors in your program.

Global variables also make it difficult for testing code separately for obvious reasons. If the variable we need is at line 7 on a different file and our function is at line 2000 of another file, we still need to run these files together, even if they have nothing else in common.

A global variable will exist through the lifetime of our application, occupying memory resources as long as the application is running. If we have thousands of code lines and that global variable is used only in two or three lines, then our global variable will keep that memory occupied when it should be released for other tasks.

Principle of Least Privilege

There’s a software engineering called the “principle of least privilege (or exposure)”, which suggests that proper software design hides details unless and until it’s necessary to expose them. We often do exactly this in module design, by hiding private variables and functions inside closure and exposing only a smaller subset of functions/properties as the public API.

Block scoping, where variables are localized to a specific block(eg-if block…), is an extension of this same mindset. Proper software puts variables as close as possible, and as far down in scoping/blocking as possible, to where it’s going to be used.

We know this exact principle instinctively. We already know that we don’t make all variables global, even though in some cases that would be easier. Why? Because it’s bad design. It’s a design that will lead to (unintentional) collisions, which will lead to bugs.

So, we stick our variables inside the function they are used for.

Also when we nest functions inside of other functions, we nest variables inside those inner functions, as necessary and appropriate. And so on.

Conclusion

To conclude, global variables are good only when it’s built into the JavaScript engine. Your code will be easier to understand, debug and control when the scope of the declared variables is limited to the part of the code that actually uses it. That is all for now. Hope you learned something new today.

Sharing is caring

Did you like what Krishnaditya Biswas wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far