Reassigning Objects & Arrays using Const featured image

When working with numbers, strings and booleans with const we know through our previous blog post var-vs-const-vs-let that you cannot reassign a const variable. The same goes for any const variables even objects or arrays. But unlike simple variables, objects and arrays have methods and properties that let you modify the object or array.

Const Arrays


const numbers = [1,2,3];

The code above has an array variable called numbers holding three values. Even though the numbers array is a const you’re able to update or change the variable. For example, you can add another number to the numbers array by using the push method. Methods are actions you perform on the array or object.


const numbers = [1,2,3];
numbers.push(4);
console.log(numbers) // Outpusts [1,2,3,4];

With methods, we can modify our array by adding another value to the end of the array using the push method. Another way you could modify the array is to remove an item from the end by using the pop method. There is to many methods to go over in detail in one blog post but if you visit The Mozilla Developer Network you’ll find everything thing you need to know on arrays and everything to do with Javascript.

Const Objects

The modifying principle applies to an object for example.


const user = {
  name: "Gary",
}

user.age = 29
console.log(user) // {name: "Gary", age: 29


The code above creates a user object with a name property then it assigns a new age property to object. One thing to remember const does not stop array and objects from being modified it only stops the variable itself from being reassigned or being overwritten for example.


const user = {
  name: "Gary",
}

person = { name: "Bob" } // Uncaught TypeError: Assignment to constant variable.

If we attempt to override the user object with another object literal the console will throw an error. That’s because we are trying to reassign a user to a new object literal. However, if you modify the name property directly by assigning it a new value you will not get an error.


const user = {
  name: "Gary",
  age: 29,
}

person.name = "Bob";
person.location = "Belfast";
console.log(user) // {name: "Bob", age: 29, location: "Belfast"}

Summary

In short, you cannot reassign any variables declared with const. However, unlike simple variables ie numbers, strings, and booleans, objects & arrays provided additional properties and methods that let modify their values. Making it the ideal way to declare your structured data with the additional benefit of not being able to be reassigned by stray variables. Thank you for taking the time to read my post stay tuned into our blog for all the latest from Scaffold.