When to use const with objects in JavaScript?

Asked
Active3 hr before
Viewed126 times

9 Answers

90%

Thanks for contributing an answer to Stack Overflow!,So when declaring an object: when should I say: Now I must declare my object with const?, Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers , GitLab launches Collective on Stack Overflow

eg.

 const temp1 = 1;
 temp1 = 2 //error thrown here.

But

 temp1.temp = 3 // no error here. Valid JS code as per ES6

Now coming to Object. we can get immutable feature with Object by using Object.freeze

const temp3 = Object.freeze({
   a: 3,
   b: 4
})
temp3.a = 2 // it wont update the value of a, it still have 3
temp3.c = 6 // still valid but wont change the object
load more v
88%

Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment, and it can't be redeclared. ,The Destructuring Assignment syntax can also be used to declare variables.,The constant's name, which can be any legal identifier.,A constant cannot share its name with a function or a variable in the same scope.

const name1 = value1[, name2 = value2[, ...[, nameN = valueN]]];
load more v
72%

Use const when you declare:,Reassign a constant object,Reassign a constant array,Change the elements of constant array

The const keyword was introduced in ES6 (2015).

const
load more v
65%

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.,The const keyword creates a read-only reference to a value. The readonly reference cannot be reassigned but the value can be change.,Summary: in this tutorial, you’ll learn how to define constants by using the JavaScript const keyword.,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:

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.

.wp - block - code {
      border: 0;
      padding: 0;
   }

   .wp - block - code > div {
      overflow: auto;
   }

   .shcb - language {
      border: 0;
      clip: rect(1 px, 1 px, 1 px, 1 px); -
      webkit - clip - path: inset(50 % );
      clip - path: inset(50 % );
      height: 1 px;
      margin: -1 px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1 px;
      word - wrap: normal;
      word - break: normal;
   }

   .hljs {
      box - sizing: border - box;
   }

   .hljs.shcb - code - table {
      display: table;
      width: 100 % ;
   }

   .hljs.shcb - code - table > .shcb - loc {
      color: inherit;
      display: table - row;
      width: 100 % ;
   }

   .hljs.shcb - code - table.shcb - loc > span {
      display: table - cell;
   }

   .wp - block - code code.hljs: not(.shcb - wrap - lines) {
      white - space: pre;
   }

   .wp - block - code code.hljs.shcb - wrap - lines {
      white - space: pre - wrap;
   }

   .hljs.shcb - line - numbers {
      border - spacing: 0;
      counter - reset: line;
   }

   .hljs.shcb - line - numbers > .shcb - loc {
      counter - increment: line;
   }

   .hljs.shcb - line - numbers.shcb - loc > span {
      padding - left: 0.75 em;
   }

   .hljs.shcb - line - numbers.shcb - loc::before {
      border - right: 1 px solid #ddd;
      content: counter(line);
      display: table - cell;
      padding: 0 0.75 em;
      text - align: right; -
      webkit - user - select: none; -
      moz - user - select: none; -
      ms - user - select: none;
      user - select: none;
      white - space: nowrap;
      width: 1 % ;
   }
const CONSTANT_NAME = value;
Code language: JavaScript(javascript)
load more v
75%

It’s very important to understand const. It doesn’t imply immutability.,A variable is like a pointer to a value (it’s a pointer for objects, it’s an assigned value for primitives). const prevents the variable to be assigned to another value. We could say it makes the pointer immutable, but it doesn’t make the value immutable too!,Use the || or ternary operators to initialize const variables that need to be calculated based on some conditions.,First of all, don’t use var. There are a few differences between var, let and const and the most important one to me is that let and const remove the error-prone behavior with variable hoisting.

See this example:

// ❌ Don't do thisfunction foo() {  console.log(bar) // No error, but prints undefined  var bar = 1234}// ✅ This is betterfunction foo() {  console.log(bar) // ReferenceError: bar is not defined  const bar = 1234}
load more v
40%

const makes the variable binding immutable but it’s value can still be modified.,Object.freeze() ignores the value modification to an object but there is no restriction on the binding.,How does const extend to objects now that we know that it’s the binding that’s immutable and not the value? Let’s do that -,The error reads as “TypeError: Assignment to constant variable.” It appears that const has rendered the alligatorColor immutable.

They are usually globals (which eliminates the need to pass them around as function parameters) but globals are not safe if they can be changed by functions that have access to them. Let’s see why -

var canAlligatorsFly = false;

function isItFlying() {
   canAlligatorsFly = true;

   if (canAlligatorsFly) {
      console.log("Yeah I'm flying");
   }

   isItFlying(); // Yeah I'm flying
load more v
22%

const age; // errror as const cannot be kept un-initialized;
const age = 20;
const age = 21, // error as once declared const variable cann't be
// re-declared in same scope or different scope. 
load more v
60%

The const keyword is block-scoped i.e you can not access it outside its immediately containing block and follows the Temporal Dead Zone rule which states that a variable can’t be used before its declaration.,We can't access foo before the declaration according to the Temporal Dead Zone rule,,We can't access foo outside the containg if block.,Note: let and const are introuced in ES6 as a new way to declare variables. const variables can only be assigned during their declaration.

const foo = 'bar';
load more v
48%

It can be assign on the variable on declaration line.,Example 3: It describes the const variable and assigned it after declaration.,The property of a const object can be change but it cannot be change to reference to the new object,Example 1: It describes that the const variable cannot be reassigned.

load more v

Other "undefined-undefined" queries related to "When to use const with objects in JavaScript?"