JavaScript const

To declare variables that are constant, the ‘const‘ keyword is used. These constant variables are block scoped like the variables declared using let but they cannot be reassigned or redeclared. If the constant is an object or an array, its items can be updated or removed. This declaration creates a constant whose scope can be either global or local to the block in which it was declared, but global constants does not become the property of the window object unlike var variables. Also, they need to be initialised with a value during declaration as they can’t be changed later.

Mutating Constant Variables

Attempting to reassign a constant variable throws a TypeError: “Assignment to constant variable”.

  1. Behaviour of const on String, Number and Boolean:
1
2
3
4
5
6
7
8
9
const demoNumber=1;
const demoString="Hello";
const demoBoolean=true;

demoNumber=7;
demoString="World";
demoBoolean=false;

// throws TypeError in all the three cases

Here, we cannot reassign any value(even the same value) in these variables.

  1. Behaviour of const on Arrays:

Arrays also throw the same error when we try to reassign it.

1
2
3
4
const demoArray = [1, 2, 3];
demoArray = [4,5,6];

console.log(demoArray); // throws TypeError

However, constant arrays can be mutated i.e its elements can be changed, or elements can be added or removed from a constant array. Functions can also be carried out in constant arrays.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const demoArray = [1, 2, 3];

demoArray[0]=4;
console.log(demoArray); // demoArray=[4,2,3]

demoArray.push(5);
console.log(demoArray); // demoArray=[4,2,3,5]

demoArray.shift();
console.log(demoArray); // demoArray=[2,3,5]

demoArray.sort((currentItem,nextItem)=>{
return nextItem-currentItem;
})
console.log(demoArray); // demoArray=[5,3,2]
  1. Behaviour of const on Objects:

Objects also throw TypeError when we try to reassign it.

1
2
3
4
const demoObject = { key1 : 1, key2 : 2 };
demoObject = { key3 : 3, key4 : 4, key5 : 5 };

console.log(demoObject); // throws TypeError

Similar to arrays, constant objects can also be mutated i.e properties can be changed, added or deleted.

1
2
3
4
5
6
7
8
9
10
const demoObject = { key1 : 1, key2 : 2 };

demoObject.key3=3;
console.log(demoObject); // demoObject={ key1 : 1, key2 : 2, key3 : 3 }

demoObject.key2=4;
console.log(demoObject); // demoObject={ key1 : 1, key2 : 4, key3 : 3 }

delete demoObject.key1;
console.log(demoObject); // demoObject={ key2 : 4, key3 : 3 }
  • So, in short, variables declared using ‘const’ cannot be reassigned or redeclared, but constant arrays and objects can be mutated but not reassigned.

Global Variables in Modules

In JavaScript any variable that is declared outside any function or block is said to be in global scope and that variable is called global variable. The Global Object provides variables and functions that are available everywhere. It is named window in browser and global in Node.js and have different names in different environments.

Global Variables in Browser

In a browser, global functions and variables are declared with var to make it a property of the global object. For example:

1
2
3
4
5
6
7
var global=5;
var globalFunction =function(){
console.log(10);
}

alert(window.global); //5 (became a property of window object)
window.x(); //10

If let was used, it wouldn’t become property of the global object

1
2
3
let global=5;

alert(window.global); //undefined (doesn't become a property of window object)

Global Variables in Node.js

In Node.js, any variable declared outside any function has only file scope. Each individual file has its own global scope. Modules are files that contain a class or a library of functions for a specific purpose. Modules can load each other and use special directives import and export to interchange functionality. Each module has its own top-level scope and any global variables are in the files are actually visible to the particular file only.

What happens to the global variable in a module, if the module is imported?

When a module containing a global variable is imported to another file, the variable itself is not passed to the file. Only the specified functions are imported to the file. If the specified functions use global variables in their implementation, that value alone is copied and not the whole variable.

In browser, a variable can be made global by explicitly assigning it to a window property. For example:

1
2
window.user= "Harry";
alert(window.user); //Harry

Using global variables is generally discouraged, because it can be modified anywhere in the code and can lead to errors. Also, debugging code is clearer, much less prone to errors and easier to test when global variables are not used.

Prototypes in JavaScript

A Prototype is an object that acts as the built in property for any object in JavaScript. It’s represented by ‘__proto__‘ in browsers. Since it is an object, it has its own prototype which results in making a Prototype Chain. This chain ends when a prototype is null. To access the prototype of an object, the method ‘Object.getPrototypeOf()’ is used(Note: This method is not the prototype of the object but simply points to its prototype).

When a property needs to be accessed from an object, and if it’s not present in the object itself, it is searched for in the object’s prototype. If it is not found there, the prototype’s prototype is searched. The chain is traversed till the property is found or prototype is null(in which case, undefined is returned). From this, it is evident that the scope of the object extends to its prototype object also.

‘Object.Prototype’ is the most basic prototype that all objects have by default. Its prototype is null. However, not all objects have ‘Object.Prototype’ as its prototype. For example:

1
2
3
4
5
6
7
const currentDate=new Date();
const datePrototype=Object.getPrototypeOf(currentDate);
const object=Object.getPrototypeOf(datePrototype);

console.log(datePrototype); // Date.Prototype
console.log(object); //Object{}
console.log(Object.getPrototypeOf(object)); //null

An object created using ‘new Date()’ has the prototype ‘Date.prototype’. The prototype of Date object is ‘Object.Prototype’.

Modifying Prototypes

Any object’s prototype can be modified by adding a property, changing an existing property or by deleting an existing property. But it is generally considered to be a bad practice. Prototypes are global in nature, so it’s easy to get a conflict when modifying prototypes. If two libraries add a same method with different implementations, one implementation will overwrite the other.

In modern programming, modifying prototypes is approved only in one instance and that’s during polyfilling. Polyfilling is the term used, when substituting a method that exists in JavaScript specification that is not yet supported by a particular JavaScript Engine. The substitute can then be implemented manually without affecting the built-in prototype.