Unclear outcomes from iterative loops

I have a question about this particular for loop:

for (var i=0,j=0;i<4,j<20;i++,j++) {
    a=i+j;
}
console.log(a);

Can someone explain why the output is 38? I initially expected it to be 6.

Answer №1

Check out the values of i and j, you will notice that they both reach 19 by the end of the loop, even if the condition causing the loop to stop is related to j

Open up your debugger and execute the following code:

for(var i=0,j=0;i<4,j<20;i++,j++){ 
  ab=i+j; 
  console.log("i", i); 
  console.log("j",j); 
  console.log("a", a); 
}

Answer №2

It is recommended to use the logical operator && instead of the comma operator in your code. I have included additional console.log statements to display the intermediate steps.

for(var i=0,j=0;i<4 && j<20;i++,j++){
  a=i+j; 

  console.log("a: "+a+ " i+j:" + (i+j))
}
console.log(a);

To illustrate the difference between comma separated conditions and && separated conditions, compare the original version of your for loop with the updated version:

for(var i=0,j=0;i<4,j<20;i++,j++){
   a=i+j;
   console.log("(i<4, j<20): " + (i<4, j<20))
   console.log("(i<4 && j<20): " + (i<4 && j<20))

 }
 console.log(a);

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

Flag form field as invalid in AngularJS

Struggling to implement server-side form validation in an AngularJS app? Finding it tricky to invalidate a form field and show an error message? Here's the setup of my app: I have a model 'client' with a controller Accounts.controller(&ap ...

Is the jQuery AJAX call using POST method being retrieved as $_GET?

Below is a snippet of code that I've successfully implemented: <script type="text/javascript"> $(document).ready(function() { // Initializing the table $('#table_1').tableDnD({ onDrop: function(table, row) { $.tab ...

Utilizing Chained Conditions in React JSX

Although the code below is functional and yields the desired outcomes, I can't help but question if there's a better way to do it. { Conditon1?<ChildComponent />:Condition2?<p>Hi</p>:<p>Bye</p> } I'm partic ...

"Uncaught ReferenceError: $ is not defined in a JavaScript/Vue.js

Currently, I am working on the javascript/vue.js page found at this link. In this file, I have added the following code: $(document).ready(function() { myIP(); }); function myIP() { $.getJSON("//freegeoip.net/json/?callback=?", function(data) { / ...

Delay in displaying Promise API call in NextJS

Currently, I am encountering an issue while making calls to an API function that I have already set up and confirmed to work flawlessly in other projects. Interestingly, I have utilized the same backend API calling method in another project as well as with ...

Ways to incorporate radio buttons, checkboxes, and select fields into a multi-step form using JavaScript

In the snippet below, I have created a multi-step form where users can provide details. The issue is that currently only text input fields are being accepted. The array of questions specifies the type of input required for each question: Question no.1 req ...

Developing a custom logging middleware with morgan

I am trying to develop a middleware using morgan. I have attempted to export the middleware function and then require it in app.js. However, I am facing an issue where it is not working as expected. Middleware: const morgan = require('morgan&apos ...

Tokenizer method utilizing strings

Imagine a scenario where strings adhere to this specific format: id-string1-string2-string3.extension In this case, id, string1, string2, and string3 can all vary in length, with extension being a standard image extension type. To illustrate, here are a ...

Localization support is working partially in a Node Express application that uses Handlebars for templating

Whenever I visit a URL with the ?lang=en query parameter, the English translation is never used. However, the Hungarian text changes work perfectly fine, displaying text to test on Hungarian in the default "hu" language without any issues. What could be ca ...

Efficiently transmitting WebSockets events/messages to multiple controllers in AngularJS

Incorporating AngularJs, I created a factory to manage a WebSocket connection effectively. Here is the code: .factory('WebSocketConnection', function () { var service = {}; service.callbacks = []; service.connect = func ...

Errors that occur during Javascript runtime in the Express framework

I'm currently working on an Express app with several routes. One of them looks like this: router.post('/upload', (req, res) => { let audioFile = req.files.audioFile; const file = __dirname + '/../' + req.body.uploadLocation ...

Issue with Angular: PDF rendering delayed until window resize

Recently, I encountered an issue with rendering a PDF in Chrome while using an AJAX call with Angular. Strangely, the PDF would only show up in the browser if I resized the window or opened the console. Surprisingly, everything worked fine in Firefox. Jav ...

Top recommendation for utilizing $scope variables in Angular applications

Currently, I am working on a new project and I want to ensure that I am correctly utilizing $scope. After watching an informative video on best practices, Miško mentioned that manipulating $scope properties directly may not be the best approach. Typical ...

Assistance needed with implementing jQuery tabs

I'm looking to add a link that takes me directly to content within a non-default tab on another page. Here's the code snippet that explains what I need: My Code: This is from my profile_edit.php page: The javascript: <script src="Javascrip ...

Is there a way to incorporate electron methods within Svelte files, specifically in Svelte 3, or is there an alternative approach to achieve this integration?

Currently, I am deep into a project that involves Svelte 3 and Electron 12.0.5 working together harmoniously. For managing hash routing, I have integrated the svelte-spa-router package into my setup. Here is a glimpse of how my project structure appears: n ...

What is the process for obtaining a fresh token from Cognito using the frontend?

Currently, I am working with a react app that utilizes Cognito for user authentication. My main query revolves around making a call to Cognito using the refresh token in order to receive a new token. Despite researching various examples provided by Cognit ...

Firebug mistakenly detects phantom errors

<div id="video-player" data-src="http://www.youtube.com/embed..."></div> Inspect Element - Browser Developer Tools: Error: Access to property 'toString' denied I scanned the entire page (Ctrl+F) and could not find any reference t ...

What is causing my array of objects to constantly accumulate undefined elements?

My quick sort function implementation for the object users_total_likes is behaving unexpectedly. When compiled and run in the terminal or browser, it adds undefined values causing a TypeError: if(users[i][key] >= users[hi][key] && users[j][key] ...

The tooltip in nvd3 is displaying the index instead of the label

I'm encountering an NVD3 tooltip issue with my multichart (multiline chart). The XAxis labels are set as JAN, FEB, MAR... DEC. However, when I hover over the graph, it displays 0, 1, 2, 3... 11 as the tooltip title instead of the month names. Here is ...

Warning: React Element creation caution with flow-router integration

Whenever I incorporate the following code into my Meteor app: Home = FlowRouter.route("/", { name: "App", action(params) { ReactLayout.render(App); } }); An error message pops up in the Chrome console: Warning: React.createElement: type shoul ...