When I declare 'i' above the for loop, the output shows as 3 3 3, while declaring 'i' inside the for loop results in an output of 1 2 3

Setting up the variable i before the for loop will result in the output being 3 3 3.

let i;
for (i = 0; i < 3; i++) {
  const log = () => {
    console.log(i);
  }
  setTimeout(log, 100);
}

//Output 3 3 3

If i is declared within the for loop, the output will be 1 2 3:

for (let i = 0; i < 3; i++) {
  const log = () => {
    console.log(i);
  }
  setTimeout(log, 100);
}

//Output 1 2 3

Answer №1

By initializing i using let i = 0;, the scope of the variable i is limited to the block within the curly braces of the for loop.

If you declare i with let i; outside of the for loop, its scope is restricted to the block enclosing the for loop, not the actual for loop itself, resulting in the observed behavior.

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

Can firebase and express be integrated seamlessly?

I'm a newcomer to Express and I want to create a REST API with express.js that utilizes Firebase as its database. Can these two technologies actually work together? Here is the code snippet I tried: cons ...

jQuery-powered one-page site - Information in HTML or JavaScript

I am currently learning JavaScript and jQuery, with a strong grasp on HTML/CSS. I am working on developing a single-page front-end website using Bootstrap for layout design. My main focus now is on implementing functionality. Here is the scenario: There a ...

Exploring the capabilities of Angular and UIGrid for fetching table information

I have been utilizing Angular along with uigrid, which is an excellent library for displaying data in a tabular format. Everything looks good when displaying the table. However, when I update an item and click on a Save button that triggers a rest service ...

Clicking anywhere outside a popup menu in JavaScript will deactivate a toggle and hide it

I have three different menu options: home,Clinic, and About. When I click on the Clinic option, a Megamenu appears, and if I click on it again, the Megamenu is hidden. I want the Megamenu to hide when clicking anywhere on the webpage. The issue is that cu ...

Preserve identical elements within an array

I am looking to create an array of key:value pairs, even if there are duplicates present. My goal is to have an array of tasks, where each task consists of multiple operations. I only require the key/value for these operations. Currently, the value of th ...

The getElementById function can only select one option at a time and cannot select multiple options

I'm having an issue with a JavaScript function that is supposed to allow me to select multiple options, but it's only selecting the first one. Here is the JavaScript code: function index(){ var a="${staffindex}".replace("[",""); ...

AngularJS service does not halt for the success function to complete

I am facing an issue with my service where the success function in the controller is not being executed immediately. The compiler is parsing the lines after the service call, which is not the desired behavior. In debug mode, I noticed that there is a del ...

Do bluebird promises require the use of async keyword?

Currently, I am looking to integrate Bluebird promises into my project which is built using NodeJS, Express, and Mongodb. Below is an excerpt from my model file: const mongoose = require('mongoose') // Blue Bird mongoose.Promise = require(&apo ...

Errors encountered while running `npm install discord.js`

I am currently facing an issue while trying to install discord.js. Unfortunately, I keep encountering the following errors: npm ERR! cb() never called! npm ERR! This is an error with npm itself. Please report this error at: npm ERR! <https://npm.co ...

Strange Occurrences Linked to Meteor's Iron Router and Pub Sub

Trying to set up a route for a single post page that performs multiple tasks using iron:router Utilizes the template postPage Subscribes to the publications of singlePost, userStatus (displays status and information of the Author of the single post page) ...

Show a collection of titles for unique post types

I am currently showcasing a custom list of post types using the following code: <!-- Displaying post type list --> <?php $args = array( 'post_type'=>'artworks_post', 'title_li'=> __(&apo ...

activate hover interactions across multiple layers of elements

On my webpage, I have a grid of hidden images that fade in when the mouse hovers over them. The code for this functionality is as follows: HTML <img class="Image" src="./img/foo.png"> CSS .Image { opacity: 0; } JS $(".CircleImage").hover( funct ...

In Typescript, it is not possible to use generics as a function parameter in a

Looking for a solution regarding passing the union of two specific samples of generics to a function. The function in question is as follows: function myCommonFunc<T>({ data, render, }: { data: T; render: (data: T) => number; }) { return ...

Disappearing Act: The Vanishing React.js Dialog Component that Lurks

Currently, I am utilizing a Dialog component from Material-UI and, overall, it is functioning correctly. However, there is an issue where if I click away from the Dialog, it disappears as expected, but occasionally it remains in the DOM with an opacity of ...

The integration of Node.js and Socket.io with Phaser.js is experiencing difficulty when connecting to socket.io with the parameters "?EIO=3&transport

My node.js server is up and running, and my phaser.js game is functioning as expected. However, I am facing an issue where the 'connected' console log is not displaying when the game runs. Instead, I am receiving this error message on the client ...

Triggering a server-side event handler in ASP.NET using client-side JavaScript

I need help with implementing a countdown timer in JavaScript. When the timer reaches 0 seconds, I would like the page to trigger the button1_click event handler. Here's the scenario: I am working on a quiz engine where the quiz responses need to be ...

h1 tag set for jQuery AJAX activation

Currently working on a website that heavily relies on ajax. Encountering an issue that hasn't been solved through online resources. Now, I'm sharing my function for fetching a page: function loadTemplate(name, replaceWholePage = true){ $.wh ...

React virtual list module: Scrolling down through code commands

In my React Grid with Virtual Scrolling, I am facing a challenge with the lack of a "scroll to row feature." At times, I need to select a specific row programmatically and ensure that it is displayed to the user. Although I have the ID of the desired row ...

Utilizing Node.js and Jasmine: Preventing the invocation of a Promise function to avoid executing the actual code results in DEFAULT_TIMEOUT_INTERVAL

There is a function below that returns a promise. public async getAverageHeadCount(queryParams: Params, childNode: any, careerTrackId: string): Promise<Metric> { const queryId = this.hierarchyServiceApiUrl + "rolling-forecast/ahc/" + q ...

Updating a document using the parent and subdocument ID with the findOneAndUpdate method

Seeking the correct subdocument for modification of a specific field. Several attempts have been made: Book.findOneAndUpdate( { _id: req.params.id, chapters: { $elemMatch: { _id: req.params.subid } } }, { $set: { chapters: { title: ' ...