In JavaScript ES6, the const keyword can unexpectedly be altered even though it is intended to be constant

While experimenting with ES6, I came across an interesting feature - const values cannot be changed or reassigned. However, I noticed that in certain scenarios, it seems like we can change them. Can someone explain this?

{
   const name = 'unchangable';
   sayName = (name) => {
     console.log(name);
   }

}

sayName('changed');

Answer №1

When it comes to changing values in functions, remember that you are actually printing the value that is passed to the function and not the constant name itself.

Here's an example to illustrate this point:

const name = 'unchangable';
sayName = (newName) => {
     name = newName; // This will result in an error
}

sayName('New Name')

Your code should be like the following:

const name = 'unchangable';
sayName = (someName) => { 
     // There is no relationship between `someName` and the const `name`
     console.log(someName); 
}

sayName('New Name');

Answer №2

It's essential to grasp the concept of scope and closures in JavaScript.

Each time you define a function, you are essentially establishing a new level of scope. Anything defined within that function is accessible by that function as well as any other functions nested inside it. For instance:

function sayFirstName(firstName) {
   //This function can access firstName
   function sayFullName(fullName) {
       //This function can access firstName and fullName
       console.log(firstName, fullName);
   }
}

Whenever the JavaScript engine encounters an RHS operand (a value on the right side of =) that appears to be a variable name, it will search for that variable locally in the scope. If not found, it will traverse up through all enclosing scopes.

Using the previous example, if fullName isn't found within sayFullName, the JS engine will look through variables declared in the scope of sayFirstName. If still not found, it will then search the global scope, which in the browser is the window object. Failure to find the variable anywhere will result in an Error being thrown.

Now let's consider a scenario where you declare a const name in the outer scope and proceed to create a new function, sayName. This function has its own separate scope where everything, including function arguments, is distinct.

What happens when you execute this code:

console.log(name);

The JS engine interprets this as an RHS operation, attempting to provide the value of name as the first argument to console.log. It starts searching for name beginning with the local function scope of sayName, where it finds the variable defined in the arguments list. Therefore, it never searches beyond the function scope to locate the const name.

You could simplify the function like so:

sayName = (foo) => {
  console.log(foo);
}

The outcome would remain unchanged.

Answer №3

Const behaves unexpectedly in two scenarios.

  • An object literal specified as const.
  • A const reference pointing to an object.

Answer №4

The issue lies in the fact that a new local variable is being created within your function.

If you were to write out the shorthand function in full, it would look like this:

   sayName = function(name) {
       console.log(name)
   }

In this case, the variable 'name' is only accessible within the function and not from outside of it. To correct this, try running your code with the following adjustments:

{
   const name = 'unchangable';
   sayName = (nameInput) => {
     name = nameInput;
     console.log(name);
   }
}
sayName('changed');

This will attempt to update the value of the constant 'name' with the new string input and then display it on the console.

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

Error encountered in React: When a parent component tries to pass data to a child

I have a Quiz object that I need to pass a single element of (questionAnswerPair) to a child component called QuestionAnswer. Although the Quiz data is fetched successfully and iterated through properly, there seems to be an issue with passing the Questio ...

How to generate PDF downloads with PHP using FPDF

I am attempting to create a PDF using FPDF in PHP. Here is my AJAX call: form = $('#caw_auto_form'); validator = form.validate(); data = form.serializeObject(); valid = validator.form(); //alert("here"); ajax('pos/pos_api.php',data,fun ...

Real-Time Chat Update Script

Recently, I've been delving into PHP and attempting to create a live chat web application. The data for the chat is stored in a MySQL database, and I have written a function called UpdateDb() that refreshes the chat content displayed in a certain div ...

The Express GET route does not support parameters or additional paths

I am facing an issue with making a fetch request when trying to add additional path or parameters... Here is what I want to achieve: const fetchOwnerCardList = () => { fetch("http://localhost:5000/api/card/ownerCards", { method: "GET", header ...

Can you point me to the location where the 'req' parameter is specified?

I've been exploring a new authentication approach detailed in this article. One issue I'm encountering is locating where the req parameter is declared in the snippet below. It seems like my code won't compile because this parameter isn&apos ...

IE8 does not properly execute AJAX call to PHP file

It's strange, it works perfectly fine in Firefox. This is the JavaScript code I'm using: star.updateRating=function(v, listid) { xmlHttp=GetXmlHttpObject(); if (xmlHttp==null) { alert("Looks like AJAX isn't supported by your browser!" ...

struggling to incorporate API Json response data into my HTML file using AngularJS

Below is the code I am currently using: angular.module('ngApp', []) .factory('authInterceptor', authInterceptor) .constant('API', 'http://myserver.com/app/api') .controller('task', taskData) function task ...

Is there a way to restrict the number of times I can utilize slideToggle function?

When I continuously click on a div element in an HTML website that triggers the .slideToggle() method, it will keep opening and closing for as many times as I click. The problem arises when I stop clicking, as the <div> continues to toggle open and c ...

Get a collection of images packed into a single zip file

My current function downloads multiple images and saves them to a user's "download" folder, although it only works in Chrome. I am looking to enhance this function by combining the downloaded images into a single zip file. Below is my existing code. ...

How to create dynamic options in a select dropdown based on the selection of another dropdown using HTML, JavaScript, or PHP

There are two dropdown menus here. <select name="firstdropdown" id="firstDropdown"> <option value="choiceOne">Choice One</option> <option value="choiceTwo">Choice Two</option> </select> <select name="seconddropdown ...

Issues with HTML formatting after using JQuery .load()

Hey there StackOverflow community! I've encountered a problem that I need help with. Whenever I use the following code: $("#specificDIV").load("new.html") The HTML content loads into the div, but the CSS and JS don't work properly. The formatt ...

What sets TypeScript apart from AtScript?

From what I understand, TypeScript was created by Microsoft and is used to dynamically generate JavaScript. I'm curious about the distinctions between TypeScript and AtScript. Which one would be more beneficial for a JavaScript developer to learn? ...

Attempt to resend email if unsuccessful

I have implemented nodemailer in my node application for sending emails. However, I am encountering an issue where the email sometimes fails to send and generates an error message. Typically, it takes two or three attempts before the email is successfully ...

The Controller is failing to pass JSON Data to the AJAX Call

When trying to access JSON data in the Controller, it is not being retrieved in the Success function and instead showing an error message "Failed to load resource: the server responded with a status of 406 (Not Acceptable)" or executing the Error function. ...

Adjusting the X-axis in Highstock: Tips and Tricks

Is there a way to adjust the X axis on this chart? My goal is to shift it so that it only covers half of the width, leaving the other half blank for future plotlines. Any suggestions on how to achieve this? Thanks! :) ...

The .remove() method is ineffective when used within an Ajax success function

I am facing an issue with removing HTML divs generated using jinja2 as shown below: {% for student in students %} <div class="item" id="{{ student.id }}_div"> <div class="right floated content"> <div class="negative ui button compa ...

Is there a way to modify the style value within AngularJS?

<div class="meter"> <span style="width: 13%"></span> </div> I have the following HTML code snippet. I am looking to update the width value using AngularJS. Does anyone have a solution for this issue? ...

Tips for transforming intricate JavaScript arrays into a unified array and iterating through to create a table

I need help combining two arrays that contain objects and reassigning the values in a standard format. Can anyone provide some guidance? Thank you. Here is my current situation: array1 = [{Apple: Ken, Orange: Mary, Melon: Tina, Strawberry: Jessica, Mango ...

Modify the find function within LoopBack

Looking to customize the remote method find in Loopback, I attempted the following approach in my model: 'usestrict'; module.exports = function(Movimenti) { Movimenti.once('attached', function(obj) { Movimenti.find = function(fi ...

Issue: Retrieve comments via AJAX (from database) in Laravel 5.2

Currently, I am developing a comments section for posts where users can leave comments without the need to refresh the page. However, I am facing an issue in displaying these comments instantly on the post without any page refresh. This is how I have stru ...