Sunday, 9 December 2018

How to define constants and what is the behaviour in of constant object?

How to define a constant?
You can create a constant using ‘const’ keyword.

Syntax
const variableName1 = value1 [, variableName2 = value2 [, ... [, variableNameN = valueN]]];

HelloWorld.js
const PI = 3.14;

console.log("Value of PI is : " + PI);

You can’t redefine a constant variable.

HelloWorld.js
const PI = 3.14;

console.log("Value of PI is : " + PI);

PI = 3.1;

When you try to run above application, you will end up in below exception.

SyntaxError: redeclaration of const PI


Naming Convention of constants
a.   A constant variable starts with a letter, underscore or dollar sign ($) and can contain alphabetic, numeric, or underscore characters
b.   Constant variable is in upper case letters.
Scope rules of constants
Constants are block-scope variables. Constant variable declared within a block is visible in that block only.

HelloWorld.js
{
  const PI = 3.1428
  console.log("Value of PI is " + PI);
  {
    const PI = 3.142
    console.log("Value of PI is " + PI);
    {
      const PI = 3.14
      console.log("Value of PI is " + PI);
    }
    console.log("Value of PI is " + PI);
  }
  console.log("Value of PI is " + PI);
}

When you ran above application, you can see below messages in console.

Value of PI is 3.1428
Value of PI is 3.142
Value of PI is 3.14
Value of PI is 3.142
Value of PI is 3.1428

Behaviour of constant object
When you define a constant variable, it creates a read-only reference to a value. It means the variable identifier can't be reassigned, but the value it holds can be changed.

HelloWorld.js
function print_admin_details(){
  console.log("name : " + ADMIN_EMPLOYEE.name);
  console.log("password : " + ADMIN_EMPLOYEE.password);
}

const ADMIN_EMPLOYEE = {'name': 'Krishna', 'password' : 'pwd123'};

print_admin_details();
console.log("Changing the admin name");

ADMIN_EMPLOYEE.name = 'Ram';
print_admin_details();


When you ran above application, you can see below messages in the console.

name : Krishna
password : pwd123
Changing the admin name
name : Ram
password : pwd123

As you see the output, name of the constant variable ADMIN_EMPLOYEE is changed to Ram.

Since arrays also objects in JavaScript, behavior is same for arrays also.

HelloWorld.js
const MY_HOBBIES = ["CHESS", "CRICKET", "FOOTBALL"];

MY_HOBBIES.push('COMPUTER PROGRAMMING');

console.log(MY_HOBBIES);


When you ran HelloWorld.js file, you can see below messages in console.

Array(4) [ "CHESS", "CRICKET", "FOOTBALL", "COMPUTER PROGRAMMING" ]




Previous                                                 Next                                                 Home

No comments:

Post a Comment