Everything you need as a full stack developer

How const works with objects and arrays

- Posted in JavaScript by

TL;DR Declaring a variable with const in JavaScript makes its value constant and unchangeable. However, assigning an object or array to a const variable only freezes the reference, allowing modifications to properties or elements without error. Reassigning the entire object or array triggers a TypeError.

The Magic of const: Unlocking Understanding of Objects and Arrays in JavaScript

As a full-stack developer, mastering the intricacies of JavaScript is crucial for building robust and efficient applications. One concept that often raises questions is how const works with objects and arrays. In this article, we'll delve into the world of immutable variables, exploring the behavior of const when applied to these fundamental data structures.

Understanding const

Before diving into the specifics, let's recap what const does in JavaScript. When you declare a variable using const, you're essentially making it constant – its value cannot be reassigned or modified directly. This is in contrast to variables declared with let or var, which can have their values changed.

const PI = 3.14; // cannot be reassigned
PI = 2.71; // SyntaxError: Assignment to constant variable.

Objects and const

Now, let's see how const interacts with objects. When you assign an object to a const variable, the entire reference is frozen in place. However, if you try to modify the object itself – by adding or removing properties, for example – nothing will stop you.

const person = { name: 'John', age: 30 };
person.name = 'Jane'; // no error!
console.log(person); // { name: 'Jane', age: 30 }

Notice that modifying an object's existing properties does not trigger a TypeError. However, attempting to replace the entire object with a new reference will indeed result in an error.

const person = { name: 'John', age: 30 };
person = {}; // TypeError: Assignment to constant variable.

Arrays and const

The story is similar for arrays. Declaring an array with const ensures that its original reference remains intact, but modifying the array's elements or adding/removing items will not raise any errors.

const colors = ['red', 'green', 'blue'];
colors.push('yellow'); // no error!
console.log(colors); // [ 'red', 'green', 'blue', 'yellow' ]

However, attempting to reassign the entire array with a new reference will once again result in a TypeError.

const colors = ['red', 'green', 'blue'];
colors = ['black', 'white']; // TypeError: Assignment to constant variable.

Freezing Objects

To truly "freeze" an object, making it immutable, you can use the Object.freeze() method. This will prevent any modifications to the object's properties or structure.

const person = { name: 'John', age: 30 };
Object.freeze(person);
person.name = 'Jane'; // TypeError: Cannot add property name, object is not extensible.

Conclusion

In conclusion, const plays a crucial role in ensuring the integrity of your code. By understanding how it interacts with objects and arrays, you'll be better equipped to write robust, predictable applications that avoid common pitfalls. While modifying an object's or array's elements does not raise errors, attempting to reassign their references will indeed trigger TypeErrors.

As a full-stack developer, mastering the nuances of JavaScript is essential for crafting reliable software solutions. By grasping the behavior of const with objects and arrays, you'll be well on your way to creating scalable applications that meet the demands of your users.

Fullstackist aims to provide immersive and explanatory content for full stack developers Fullstackist aims to provide immersive and explanatory content for full stack developers
Backend Developer 103 Being a Fullstack Developer 107 CSS 109 Devops and Cloud 70 Flask 108 Frontend Developer 357 Fullstack Testing 99 HTML 171 Intermediate Developer 105 JavaScript 206 Junior Developer 124 Laravel 221 React 110 Senior Lead Developer 124 VCS Version Control Systems 99 Vue.js 108

Recent Posts

Web development learning resources and communities for beginners...

TL;DR As a beginner in web development, navigating the vast expanse of online resources can be daunting but with the right resources and communities by your side, you'll be well-equipped to tackle any challenge that comes your way. Unlocking the World of Web Development: Essential Learning Resources and Communities for Beginners As a beginner in web development, navigating the vast expanse of online resources can be daunting. With so many tutorials, courses, and communities vying for attention, it's easy to get lost in the sea of information. But fear not! In this article, we'll guide you through the most valuable learning resources and communities that will help you kickstart your web development journey.

Read more

Understanding component-based architecture for UI development...

Component-based architecture breaks down complex user interfaces into smaller, reusable components, improving modularity, reusability, maintenance, and collaboration in UI development. It allows developers to build, maintain, and update large-scale applications more efficiently by creating independent units that can be used across multiple pages or even applications.

Read more

What is a Single Page Application (SPA) vs a multi-page site?...

Single Page Applications (SPAs) load a single HTML file initially, handling navigation and interactions dynamically with JavaScript, while Multi-Page Sites (MPS) load multiple pages in sequence from the server. SPAs are often preferred for complex applications requiring dynamic updates and real-time data exchange, but MPS may be suitable for simple websites with minimal user interactions.

Read more