What are the inner workings of Javascript's const when used with primitive types compared to objects?

Recently, I stumbled upon an intriguing concept regarding the behavior of const when dealing with different data types such as number, string, Boolean, Object, and arrays.

const num1 = 10
num1 = 20 //throws error

const arr1 = [1,2,3,4]
arr1.push(5) //works
arr1.pop() //works
arr1[2] = 7 //works

arr1 = [2,3] //throws error

It appears that for array and objects, you can change their values but not reassign them while using const. Does this imply that there is no real advantage in declaring an object or array as a const since you can modify their values at any time?

If someone could shed some light on how exactly const operates behind the scenes, I would greatly appreciate it!

Answer №1

When using the const declaration, a read-only reference to a value is created. Although the value itself remains immutable, both arrays and objects can hold values that may be changed or updated. However, the variable identifier cannot be reassigned.

In this example, 'arr1' is a variable identifier:

const arr1 = [1,2,3,4]
arr1.push(5) // This works - changing the value
arr1.pop() // This works - changing the value
arr1[2] = 7 // This works - changing the value

Attempting to reassign 'arr1' will result in an error:

 arr1 = [2,3] // This throws an error - attempting to reassign the same variable

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can we incorporate dynamic HTML elements into a React JS application?

My code seems to be having an issue. I'm working on a registration form and trying to include an error message if the passwords entered do not match. For some reason, I am unable to dynamically add a para tag to my HTML. Any insights on why this could ...

Removing event notifications with Google Calendar API v3 (JavaScript): A Step-by-Step Guide

After creating a JSON object with event details, I attempted to add it to Google Calendar using the provided code snippet: function addEvent() { gapi.client.load('calendar', 'v3', function() { var request = gapi.client.calendar.e ...

How can you generate a Ref in React without utilizing the constructor by using React.createRef?

In the past, I relied on using constructor in React for just three specific purposes: 1. Initializing state as shown below: class App extends React.Component { constructor(props) { super(props); this.state = { counter: 0 }; } } H ...

Discovering a way to retrieve dropdown data when the dropdown value is changed

Can you please help me with loading dropdown data based on the value selected in the dropdown menu? I am trying to use this tutorial to create linked dropdowns: - This is the link I am referring to. When I choose the first option (ZILA SAHAKRI BANK LIMI ...

resolved after a new promise returned nothing (console.log will output undefined)

Here is my Promise Function that iterates through each blob in Azure BlobStorage and reads each blob. The console.log(download) displays the values as JSON. However, when trying to close the new Promise function, I want the resolve function to return the ...

Are there any comparable features in Angular 8 to Angular 1's $filter('orderBy') function?

Just starting out with Angular and curious about the alternative for $filter('orderBy') that is used in an AngularJS controller. AngularJS example: $scope.itemsSorted = $filter('orderBy')($scope.newFilteredData, 'page_index&apos ...

When encountering an OR operator, Javascript will cease execution of the remaining conditions

This is a basic JavaScript form-validation I created. All the document.form.*.value references are present on my page, except for the document.form.dasdasdas.value ==''. In the code below, the purpose is to display an error if any of the forms a ...

Updating code to insert elements into an array/data structure using Javascript

Hey everyone, I'm new to Javascript and I'm trying to make a change to some existing code. Instead of just returning the count of elements, I want to add each of the specified elements to an array or list. Here is the original code from a Seleni ...

Error encountered in Bootstrap 5: Popper__namespace.createPopper function is not defined

Currently using Django to host web pages. Focus is on enabling offline access by downloading all necessary resources to ensure webpage functionality, like Bootstrap 5. Attempting to utilize the dropdown menu feature in Bootstrap: Dropdowns depend o ...

Presentation - hyperlink only functioning for final slide

I have a question about Lean Slider, which you can check out at My goal is to link each slide to a different URL. However, I'm facing an issue where only the code in the last slide seems to be executed and applied to all other slides. For example, if ...

Using Javascript to update various element styles using their corresponding IDs

I am currently working on implementing a dark mode feature and I am encountering an issue when trying to change the CSS of multiple elements at once. This is my JavaScript code: var elem = document.getElementById('fonts'); for(var i= ...

Updating presence of HTML tag link based on ng-if condition

HTML: <a data-ng-if="price" data-ng-click="selected(price)"> <div> ... </div> </a> i am trying to figure out how to remove the <a></a> element when data-ng-if="!price" Can anyone provide guidance on th ...

Invoking a parent controller method from a directive in AngularJS

I have utilized a tree grid plugin from the following link: https://github.com/khan4019/tree-grid-directive and I made some customizations to its template: .directive('treeGrid', [ '$timeout', function($timeout) { return { ...

What steps can I take to prompt a ZMQ Router to throw an error when it is occupied?

In my current setup, I have a configuration with REQ -> ROUTER -> [DEALER, DEALER... DEALER]. The REQ acts as a client, the ROUTER serves as a queue, and the DEALER sockets are workers processing data and sending it back to ROUTER for transmission to ...

An error message indicating that the page is currently being unloaded has appeared

While working on a NodeJS-ReactJS Isomorphic App, I encountered an issue when clicking on a Link. An error message popped up saying: Uncaught (in promise) Error: Request has been terminated Possible causes: the network is offline, Origin is not allowed by ...

I am encountering an issue with express-session where it is failing to assign an ID to

Seeking assistance with utilizing express-session to manage user sessions on arcade.ly. I have not specified a value for genid, opting to stick with the default ID generation. However, an ID is not being generated for my session. An example of the issue c ...

Determining the size of <li> elements within Bootstrap 4's tab-content feature

I need some assistance with this issue. I am attempting to calculate the length of a list using Bootstrap 4's tab-content feature. However, when the tab is inactive upon page load, the length is showing as 0. Even after opening the tab, it remains at ...

During the execution of Sequelize sync() along with foreign key constraints, errors are encountered

I am currently working with three models: user.model.js, user-log.model.js, and address.model.js These models are responsible for creating tables in my database. However, the 'user_logs' and 'addresses' tables have foreign keys that re ...

Avoid duplicate calls to the same URL in node.js

I need to make multiple calls to the back-end with some of them targeting the same URLs. To optimize performance, I am caching the results. However, a problem arises when I call loadCached twice in quick succession with the same URL - it ends up triggering ...

Tips for managing a JSON response

Currently, I am facing a dilemma while using Python websockets to handle JSON objects. I have a working example with JavaScript that utilizes parseJSON as shown below: socket = io.connect("__socket address__"); socket.on("connect", function() {socket.emit ...