Utilizing const as the iteration variable in a for loop

I've grasped the concept of using var and let in a for loop in typescript/javascript, but can someone shed light on how and why a const variable as a loop variable behaves?

for (const i = 0; i < 5; i++) {
  setTimeout(function() {
    console.log(i)
  }, 100 * i);
}

My understanding is that when you declare a variable as const and assign it a value, that value cannot be changed.

However, it seems that the value is indeed changing in the console.log(). Shouldn't this trigger an error during compilation? What am I overlooking here?

I've prepared two examples to showcase this behavior.

Loop variable as a const

Const variable reassignment

Could someone provide some insight into this perplexing issue?

Answer №1

The code functions properly in Stackblitz due to the fact that it is executing transpiled code:

AppComponent.prototype.test = function () {
    var _loop_1 = function (i) {
        setTimeout(function () {
            console.log(i);
        }, 100 * i);
    };
    for (var i = 0; i < 5; i++) {
        _loop_1(i);
    }
};

However, adding the same snippet here will not work as it is not transpiled.

for (const i = 0; i < 5; i++) {
  setTimeout(function() {
    console.log(i)
  }, 100 * i);
}

https://i.sstatic.net/bVPLm.png

Answer №2

In response to your inquiry,

  test(){
    for(const i =0 ; i< 5; i++){
      setTimeout(function(){
        console.log(i)
      },100*i);
    }
  }

This piece of code can be rewritten as follows:

  test(){

    // can only be initialized once
    const i;
    for(i = 0 ; i< 5; i++){
      setTimeout(function(){
        console.log(i)
      },100*i);
    }
  }

Since every JavaScript variable is hoisted to the top of its scope, the const variable in this case belongs to the test() block and is not accessible outside of it.

To correct the code snippet:

  test(){

    // can be initialized multiple times within the block
    for(let i = 0 ; i< 5; i++){
      setTimeout(function(){
        console.log(i)
      },100*i);
    }
  }

The updated version would look like this:

  test(){

    let i;
    // can be initialized multiple times within the block
    for(i = 0 ; i< 5; i++){
      setTimeout(function(){
        console.log(i)
      },100*i);
    }
  }

Both const and let have block scope and are hoisted at the top of the block they are defined in. The key difference is that variables declared as const cannot be reinitialized.

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

Exploring Angular's Pipe Asset Library

I am currently developing an Angular 4 Pipe that will provide support for internationalization. My goal is to create an npm module so that other developers can benefit from this pipe as well. The pipe will utilize JSON data that developers will place in fi ...

Exploring objects nested within other types in Typescript is a powerful tool for

My journey with TypeScript is still in its early stages, and I find myself grappling with a specific challenge. The structure I am working with is as follows: I have a function that populates data for a timeline component. The data passed to this function ...

Is it possible to modify the text alignment of a div based on the dropdown selection

I'm having trouble getting the alignment to work with my dropdown list that styles the font of a div. It's frustrating because I usually find solutions easily on Google, but this time the align feature is really bugging me. <SCRIPT LANGUAGE=" ...

Selecting a specific element and attaching a particular class to this element, but directing it towards a different element that shares the same index in a separate node list

I am working on a project where I have two sets of identical images - one is displayed in a gallery format and the other set is hidden until its corresponding gallery image is clicked, creating a lightbox effect. For example: <ul id="gallery"> ...

Exploring the typing for DefaultRootState in React Redux Connect

I'm currently in the process of upgrading to the latest versions of TypeScript, React, and Redux. However, I've encountered a compiler error when using the connect function in React Redux: According to the React Redux documentation, I typed my r ...

After pressing the ASP.NET button, the JavaScript function is called followed by the C# function being executed

There is an issue that I'm facing: I have developed an ASP.NET page which includes an Update panel with an ASP.NET control. I have a JavaScript function for validation. When the button is clicked, I want to use onclientclick to trigger the JavaScrip ...

Error: The specified file or directory does not exist at location 'D:E-commerceJsfrontend ode_modules.axios.DELETE'

As I work on my e-commerce project using vanilla JavaScript and webpack with npm, I keep encountering an issue while trying to install axios. npm ERR! enoent ENOENT: no such file or directory, rename 'D:\E-commerceJs\frontend\node_mod ...

How to execute a function in a child process using node.js?

In my node.js application, I am receiving a file through a web request and need to perform a time-consuming conversion process on it. To prevent this task from affecting the main thread's performance, I currently have it triggered by a setTimeout() ca ...

Tips for capturing the output of a dynamically rendered component in Angular 8

I need to capture the output from a rendered component using ViewChild. The content of ViewChild is displayed after an ngIf condition is met. Here is the template code: <div *ngIf="isModalVisible" class="modal" tabindex="-1" role="dialog"> <di ...

What steps can I take to stop Google Maps from resetting after a geocode search?

As a beginner working with the Google Maps Javascript API v.3, I have written some code to initialize a map, perform an address lookup using the geocoder, re-center the map based on the obtained lat long coordinates, and place a marker. However, I am facin ...

Is there a way to run /_next/static/xxx.js using a script tag?

I have customized my next.config file (webpack) to generate a static JavaScript file (.next/static/loader.js). The original loader.js is an Immediately Invoked Function Expression (IIFE): (function stickerLoader(){ alert('Hello'); // ... so ...

What is the reason for the lack of variable assignment within the forEach method in Angular?

I am struggling with assigning a value to the variable "this.qdDias" and returning it. After using subscribe, I am unable to retrieve the value at the end of the method. Despite seeing the value in the console.log(this.qdDias), it becomes undefined when re ...

"Enhancing User Experience with jQuery: Implementing a Smooth Scroll Feature with Current

I could really use some guidance on this issue that's been causing me trouble. Take a look at this fiddle for reference: http://jsfiddle.net/NtUpw/ Currently, the code is functioning as expected. However, I'm facing an issue where when the curre ...

Transform a single data point into pixels by converting its latitude and longitude coordinates

I am facing a specific challenge where I have hit a roadblock after conducting some research. The issue at hand is this: I am working with a raster image that has known dimensions (800 x 800 px) I have two points within this image with their pixel and g ...

Event handler for "copy" on the iPad

Is it possible to bind an event handler to the copy event on iPad or iPhone devices? ...

Failure to Generate stats.json File When Building Angular 6 with --stats-json Flag

Currently, I am facing an issue with generating the stats.json file for my Angular 6 application. Despite trying a few different methods, the file is simply not being created. It seems that my system specifically requires "npm run" before every Angular CLI ...

After ngAfterViewInit, the @ViewChild element has not been defined

@ViewChild('videoPlayer') myVidElement: ElementRef; There is an HTML5 video element in the markup with the ViewChild specified as above However, I am facing an issue where the element is not accessible and is logged as undefined in both ngOnIni ...

Using jQuery UI autocomplete with special characters

Recently, I put together a simple jQuery example utilizing jQuery UI autocomplete feature. $(function() { //autocomplete $(".selector").autocomplete({ source: "getdata.php", minLength: 1 }); }) getdata.php: <?php if (isse ...

Steps for sending a POST request for every file in the given array

I am working on an angular component that contains an array of drag'n'dropped files. My goal is to make a POST request to http://some.url for each file in the array. Here is what I have been attempting: drop.component.ts public drop(event) { ...

Displaying images dynamically in React from a source that is not public

There are 3 image options being imported, determined by the value in the state which dictates which of the 3 to display. import csv from '../../images/csv.svg'; import jpg from '../../images/jpg.svg'; import png from '../../images/ ...