JavaScript Variables: Declaration and their Scopes

“The basis of programming is to define the data and then manipulate the defined data.” This statement defines that every programming language requires data to be processed. There is nothing in programming without the data. So, JavaScript also defines their data using the variables. Here is the post from our experts on the topic: “JavaScript Variables: Declaration and their Scopes” where we will see different ways of declaring JavaScript variables and their scopes. This topic seems to be very simple, but there are subtle nuances in declaring and defining scopes of variables in JavaScript that are most important to know.

JavaScript Variables: Declaration and their Scopes

What are JavaScript variables?

In JavaScript, variables are the containers that hold the re-usable data. It is just like “named storage” for the data. In lemon terms, we can say that a variable is like a “box” for data with a uniquely named sticker on it and a defined value inside it. Also, the containers/box value can be changed as many times as needed. When the value is changed, the old value is removed from the container/box, and the new value is stored in it.

For example, there is a box named “Language” having the value “English” which can be represented in JavaScript as:

var Language = “English”;

Now if the value in the box is changed, then the old value will be removed and the new value will be stored in it. If the value of Language is changed to “Java”, then the old value “English” will be removed and the new value will be stored like this:

var Language = “Java”;

JavaScript variables are defined data in three different parts:

  1. Variable Declaration: This is the first step where the variable registers its scope i.e. where it can be used.
  2. Variable Initialization:  This is done after declaration where the javascript engine assigns some space or memory to the variable. By default, the declared variable will take a value of “undefined” before assignment.
  3. Variable Assignment: This is done at last where the variable is assigned some value based on the standard javascript data types using the assignment “=” operator.

Here are some of the examples:

var Language;            // variable declaration with name Language with initialized value as undefined 
Language = "javascript"  //Assignment of value javascript to variable Language

var Language="English"; //variable declaration with name Language and assigned value English

Ways to declare a variable in JavaScript : 

Using “var” keyword: Before ES2015/ES6, JS variables were solely declared using the “var” keyword. It is generally not used in the ES2015/ES6 javascript version. Here is a simple example of variable declaration using the “var” keyword in a single line.

var user=”Joe”, age=25, isMarried=false;

Using “let” and “const” keywords: To create a variable in JavaScript ES2015/ES6 version, we need to use “let” for the variable whose value can be changed and “const” for those variables whose values remain the same or cannot be changed. Creating a variable using the “let” keyword is almost the same as “var” but it only differs with their scopes.

Here is a simple example of variable declaration using the “let” and “const” keywords.

let user="Joe", age=25, isMarried=false;  //using let keyword
user="Phobe", age=27, isMarried=true; //variable with let keyword can change their values

console.log("User:" + user + ", Age:" + age + ", isMarried:" + isMarried); 
//User:Phobe, Age:27, isMarried:true

const newUser="Monika", newAge="27", newIsMarried = false; //using const keyword
newUser= "Jack", newAge="23",newIsMarried = true; // Uncaught TypeError: Assignment to constant variable

Also, a variable declared with “const” must be initialized.

const user; //SyntaxError: missing initializer

If you declare an object using the “const” keyword, you are allowed to change their properties.

const user = {};
user.name = "Chandler" //no error

Scope a variable in JavaScript : 

The scope of a variable means “where the variable or defined data can use its value”. In JavaScript, scopes are of two types:

  1. Global scope.
  2. Local scope.

The below example defines the types of scopes:

var lang = "livescript";    //lang is declared and initialized globally

function change() {
  var lang = "javascript";   //same lang is defined as a local variable in function
  console.log(lang);          //prints the local value of lang i.e. javascript
}

change( );          //calling of function change

console.log(lang);  //prints the global value of lang i.e. livescript

But the scope of the variables in JavaScript can also be referred as “function scope” and “block scope”.

Function scope: Creating a variable inside the function creates a new local scope as function scope.

Block Scope: It will be scope like a variable inside “if”, “‘for”, “foreach”, or normal “{ }” block.

“Var” scope:

Before the introduction of ES2015/ES6, the variables declared using the “var” keyword were scoped only to the function (local scope) and the global scope i.e. they are visible through blocks. The code inside { } does not necessarily have a local scope.

if (true) {
  var user = "Joe"; //No local scope but act as a global scope
}
console.log(user); // Joe, declaration inside { } block as global

Note: The “var” declaration is hoisted (processed) at the start of the function but the assignments are not. This means that the variable declared using “var” are processed at the start of the function i.e. it doesn’t matter whether they are declared at the end or the start of the function, they will be processed at the beginning of the function but their assignments are processed at the place where the assignment is done.

Let’s understand the same through an example:

function whichLang() {
  console.log(lang) // undefined i.e. assignments are not processed at the start of the function
   
  lang = "javascript"; // assignment - when the execution reaches it.
  console.log(lang); //javascript - assignment done in previous statement

  var lang; // declaration processed at the start of the function.
}
whichLang();

“let” scope:

The scope of the variable changed after the introduction of the JavaScript version ES2015/ES6 when the variables were declared using “let” and “const”. They are followed globally as well as locally with function and local scopes.

Let’s understand the same with an example using the “let” and “var” keywords:

//using var
function scopeVar() {
  var a = 5;    // variable scoped to scopeVar() function as a global scope

  if (true) {
    var a = 10;      // same variable will override the a=5
    console.log(a);  // prints 10 
  }
  console.log(a);    // prints 10
}
scopeVar();
//using let
function scopeLet() {
  let a = 5;    // variable scoped to scopeVar() function as a function local scope

  if (true) {
    let a = 10;      // new variable with local scope to if block
    console.log(a);  // prints 10 
  }//scope of variable a of if block ends here

  console.log(a);    // prints 5 declared at the start of the function
}
scopeLet();

That’s it for now. I hope you understand the basic concepts of JavaScript Variables: Declaration and their Scopes now which has always been a sort of confusion for javascript beginners.

Read more on Computer Programming articles:-

 Computer Programming Articles

Contribute to EduTechLearners:-

Please write comments if you want to share more information regarding the above notes. If you want more notes/books on any topics please mail us or comment below. We will provide you as soon as possible and if you want your notes to be published on our site then feel free to contribute on EduTechLearners or email your content to contribute@edutechlearners.com (Your Name will publish the contents).

Leave a Reply