1.

How to validate decimal numbers in JavaScript

Answer»

Yes, constants do exist in JavaScript. The “const” keyword is used to create constant in JavaScript.

The const variables in JavaScript must be assigned a value when they are declared. Once declared, you cannot change and declare the value of constant again.

For example:

const val = 100;

Another example include:

const PI = 3.14159265359;

With const, you can declare local variables with block scope rather than function scope. Let’ say we have a constant variable “a”. After declaring a value LIKE a constant variable, you can’t assign a new value to it.

Here’s an example wherein we are trying to reassign value to a const variable. As expected an error generates:

// declared a constant variable. const val= 150; // Error, SINCE we try to assign a new value to the constant val = 0;

The following also gives an error since we are trying to change the primitive value:

const PI = 3.14159265359; PI = 3.14;

You cannot even reassign a constant array. Let us see an example for this:

<!DOCTYPE HTML> <html> <body> <p id="myid"></p> <script> try {   const department = ["Finance", "HR", "MARKETING", "Operations"];   department = ["Operations", "IT", "Accounting", "Production"]; // error } catch (e) {   document.getElementById("myid").innerHTML = e; } </script> </body> </html>

The output displays an error as shown below since we cannot assign to a constant variable:

TypeError: Assignment to constant variable.


Discussion

No Comment Found