Define const in javascript

JavaScript const: Declaring Constants in ES6

Summary: in this tutorial, you’ll learn how to define constants by using the JavaScript const keyword.

Introduction to the JavaScript const keyword

ES6 provides a new way of declaring a constant by using the const keyword. The const keyword creates a read-only reference to a value.

const CONSTANT_NAME = value;Code language: JavaScript (javascript)

By convention, the constant identifiers are in uppercase.

Like the let keyword, the const keyword declares blocked-scope variables. However, the block-scoped variables declared by the const keyword can’t be reassigned.

The variables declared by the let keyword are mutable. It means that you can change their values anytime you want as shown in the following example:

let a = 10; a = 20; a = a + 5; console.log(a); // 25Code language: JavaScript (javascript)

However, variables created by the const keyword are “immutable”. In other words, you can’t reassign them to different values.

If you attempt to reassign a variable declared by the const keyword, you’ll get a TypeError like this:

const RATE = 0.1; RATE = 0.2; // TypeErrorCode language: JavaScript (javascript)

Unlike the let keyword, you need to initialize the value to the variable declared by the const keyword.

The following example causes a SyntaxError due to missing the initializer in the const variable declaration:

const RED; // SyntaxErrorCode language: JavaScript (javascript)

JavaScript const and Objects

The const keyword ensures that the variable it creates is read-only. However, it doesn’t mean that the actual value to which the const variable reference is immutable. For example:

const person = < age: 20 >; person.age = 30; // OK console.log(person.age); // 30Code language: JavaScript (javascript)

Even though the person variable is a constant, you can change the value of its property.

However, you cannot reassign a different value to the person constant like this:

person = < age: 40 >; // TypeError Code language: JavaScript (javascript)

If you want the value of the person object to be immutable, you have to freeze it by using the Object.freeze() method:

const person = Object.freeze(age: 20>); person.age = 30; // TypeErrorCode language: JavaScript (javascript)

Note that Object.freeze() is shallow, meaning that it can freeze the properties of the object, not the objects referenced by the properties.

Читайте также:  Java optional get if present

For example, the company object is constant and frozen.

const company = Object.freeze(< name: 'ABC corp', address: < street: 'North 1st street', city: 'San Jose', state: 'CA', zipcode: 95134 > >);Code language: JavaScript (javascript)

But the company.address object is not immutable, you can add a new property to the company.address object as follows:

company.address.country = 'USA'; // OKCode language: JavaScript (javascript)

JavaScript const and Arrays

Consider the following example:

const colors = ['red']; colors.push('green'); console.log(colors); // ["red", "green"] colors.pop(); colors.pop(); console.log(colors); // [] colors = []; // TypeErrorCode language: JavaScript (javascript)

In this example, we declare an array colors that has one element using the const keyword. Then, we can change the array’s elements by adding the green color. However, we cannot reassign the array colors to another array.

JavaScript const in a for loop

ES6 provides a new construct called for. of that allows you to create a loop iterating over iterable objects such as arrays, maps, and sets.

let scores = [75, 80, 95]; for (let score of scores) < console.log(score); >Code language: JavaScript (javascript)

If you don’t intend to modify the score variable inside the loop, you can use the const keyword instead:

let scores = [75, 80, 95]; for (const score of scores) < console.log(score); >Code language: JavaScript (javascript)

In this example, the for. of creates a new binding for the const keyword in each loop iteration. In other words, a new score constant is created in each iteration.

Notice that the const will not work in an imperative for loop. Trying to use the const keyword to declare a variable in the imperative for loop will result in a TypeError :

for (const i = 0; i < scores.length; i++) < // TypeError console.log(scores[i]); >Code language: JavaScript (javascript)

The reason is that the declaration is only evaluated once before the loop body starts.

Summary

  • The const keyword creates a read-only reference to a value. The readonly reference cannot be reassigned but the value can be change.
  • The variables declared by the const keyword are blocked-scope and cannot be redeclared.

Источник

const

The const declaration declares block-scoped local variables. The value of a constant can’t be changed through reassignment using the assignment operator, but if a constant is an object, its properties can be added, updated, or removed.

Читайте также:  Embedded sql in java

Try it

Syntax

const name1 = value1; const name1 = value1, name2 = value2; const name1 = value1, name2 = value2, /* …, */ nameN = valueN; 

The constant’s name, which can be any legal identifier.

The constant’s value. This can be any legal expression, including a function expression.

The destructuring syntax can also be used to declare variables.

const  bar > = foo; // where foo = < bar: 10, baz: 12 >; // This creates a constant with the name 'bar', which has a value of 10 

Description

The const declaration is very similar to let :

  • const declarations are scoped to blocks as well as functions.
  • const declarations can only be accessed after the line of declaration is reached (see temporal dead zone). For this reason, const declarations are commonly regarded as non-hoisted.
  • const declarations do not create properties on globalThis when declared at the top level of a script.
  • const declarations cannot be redeclared by any other declaration in the same scope.
  • const begins declarations, not statements. That means you cannot use a lone const declaration as the body of a block (which makes sense, since there’s no way to access the variable).
if (true) const a = 1; // SyntaxError: Lexical declaration cannot appear in a single-statement context 

An initializer for a constant is required. You must specify its value in the same declaration. (This makes sense, given that it can’t be changed later.)

const FOO; // SyntaxError: Missing initializer in const declaration 

The const declaration creates an immutable reference to a value. It does not mean the value it holds is immutable — just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object’s contents (e.g., its properties) can be altered. You should understand const declarations as «create a variable whose identity remains constant», not «whose value remains constant» — or, «create immutable bindings», not «immutable values».

Many style guides (including MDN’s) recommend using const over let whenever a variable is not reassigned in its scope. This makes the intent clear that a variable’s type (or value, in the case of a primitive) can never change. Others may prefer let for non-primitives that are mutated.

The list that follows the const keyword is called a binding list and is separated by commas, where the commas are not comma operators and the = signs are not assignment operators. Initializers of later variables can refer to earlier variables in the list.

Examples

Basic const usage

Constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters, especially for primitives because they are truly immutable.

// define MY_FAV as a constant and give it the value 7 const MY_FAV = 7; console.log("my favorite number is: " + MY_FAV); 
// Re-assigning to a constant variable throws an error MY_FAV = 20; // TypeError: Assignment to constant variable // Redeclaring a constant throws an error const MY_FAV = 20; // SyntaxError: Identifier 'MY_FAV' has already been declared var MY_FAV = 20; // SyntaxError: Identifier 'MY_FAV' has already been declared let MY_FAV = 20; // SyntaxError: Identifier 'MY_FAV' has already been declared 

Block scoping

It’s important to note the nature of block scoping.

const MY_FAV = 7; if (MY_FAV === 7)  // This is fine because it's in a new block scope const MY_FAV = 20; console.log(MY_FAV); // 20 // var declarations are not scoped to blocks so this throws an error var MY_FAV = 20; // SyntaxError: Identifier 'MY_FAV' has already been declared > console.log(MY_FAV); // 7 

const in objects and arrays

const also works on objects and arrays. Attempting to overwrite the object throws an error «Assignment to constant variable».

const MY_OBJECT =  key: "value" >; MY_OBJECT =  OTHER_KEY: "value" >; 

However, object keys are not protected, so the following statement is executed without problem.

You would need to use Object.freeze() to make an object immutable.

The same applies to arrays. Assigning a new array to the variable throws an error «Assignment to constant variable».

const MY_ARRAY = []; MY_ARRAY = ["B"]; 

Still, it’s possible to push items into the array and thus mutate it.

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jul 3, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Оцените статью