JavaScript: const Statement


A constant is an identifier for a simple value. The value cannot be modified during the script's execution. In JavaScript, const statement creates a constant. Constants follow the same scope rules as JavaScript variables.


The current implementation of const is a Mozilla-specific extension and is not part of ECMAScript 5.


const varname1 = value1 , varname2 = value2,... varnameN = valueN


varname1, varname2......varnameN : Constant names.

value1, value2......value3 : Value of the constant.


The following web document displays the height and width and area of the rectangle.


<!DOCTYPE html>
<html lang="en">
<meta charset=utf-8>
<title>JavaScript const statement :  Example-1</title>
<link rel="stylesheet" type="text/css" href="example.css">
<h1>JavaScript : const statement</h1>
<script src="const-statement-example1.js"></script>

JS Code

const height = 400;
const width = 200;
var newParagraph = document.createElement("p");
var newText = document.createTextNode("Height is : "+height+" Width
is : "+ width +". So, Area of the Rectangle is " + height*width +
" sq.ft.");

View the example in the browser

Browser compatibility

- Supported Firefox & Chrome (V8).
- In the case of Safari 5.1.7 and Opera 12.00, you can change the value of the const after defining a variable with const.
- It is not supported in Internet Explorer 6-9, or in the preview of Internet Explorer 10.

Previous: JavaScript: return statement
Next: JavaScript: Function

Test your Programming skills with w3resource's quiz.

JavaScript: Tips of the Day

How do I redirect to another webpage?

window.location.replace(...) is better than using window.location.href, because replace() does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.

If you want to simulate someone clicking on a link, use location.href

If you want to simulate an HTTP redirect, use location.replace.

// similar behavior as an HTTP redirect

// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

Ref: https://bit.ly/37JdWH8