How do you declare Constant in JavaScript ?

Published: 09 June 2023
on channel: Wasiq Khan
32
1

In JavaScript, you can declare constants using the const keyword. Constants are variables whose values cannot be re-assigned once they are defined. Here's the syntax to declare a constant in JavaScript:

javascript
Copy code
const constantName = value;
Here's an example:

javascript
Copy code
const PI = 3.14159;
console.log(PI); // Output: 3.14159

// Trying to re-assign a value to a constant will result in an error
PI = 3.14; // Error: Assignment to constant variable
In the example above, PI is declared as a constant with the value of 3.14159. Any attempt to re-assign a value to PI will throw an error because it is a constant.

It's important to note that the scope of a constant is block-level. This means that a constant is only accessible within the block where it is defined or within nested blocks. For example:

javascript
Copy code
function example() {
const x = 10;

if (true) {
const y = 20;
console.log(x); // Output: 10
console.log(y); // Output: 20
}

console.log(x); // Output: 10
console.log(y); // Error: y is not defined
}
In the example above, the constant x is accessible both within the example function and the if block. However, the constant y is only accessible within the if block. Attempting to access y outside of the if block will result in an error.

By convention, constant names are usually written in uppercase to indicate that their values should not be changed, but this is not a strict requirement in JavaScript.


On this page of the site you can watch the video online How do you declare Constant in JavaScript ? with a duration of hours minute second in good quality, which was uploaded by the user Wasiq Khan 09 June 2023, share the link with friends and acquaintances, this video has already been watched 32 times on youtube and it was liked by 1 viewers. Enjoy your viewing!