How can we incorporate the final value in an iteration using a direction-agnostic for loop?

Implementing this solution, I aim to construct a for-loop that can operate regardless of whether the starting value is higher or lower than the ending value:

function calculateRange(startVal, endVal) {
    var val = startVal;
    for (var step = val > endVal ? -1 : +1; val !== endVal; val += step){
        // Perform actions with each value
        console.log(val);
    }
}

let startVal = 6;
let endVal = 3;
calculateRange(startVal, endVal);

Due to the use of val !== endVal in defining the for-loop (which appears necessary to make the loop direction-agnostic), the final value is not counted in the iteration process. Thus, in this scenario, the output appears as follows:

6
5
4

However, it is desired to include the final value endVal. Is there a method to integrate it within the for-loop, or is it essential to add it separately like so:

function calculateRange(startVal, endVal) {
    var val = startVal;
    for (var step = val > endVal ? -1 : +1; val !== endVal; val += step){
        //doSomething(val);
        console.log(val);
    }
}

let startVal = 6;
let endVal = 3;
calculateRange(startVal,endVal);

//doSomething(endVal);
console.log(endVal);

Answer №1

To halt when the value exceeds past the endVal:

val != endVal + step

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

What is the solution for the red underline issue with the @json Blade directive in VSC?

Everything seems to be functioning correctly with these variables, but I'm curious as to why they are underlined in red. Does anyone have a solution for this issue? https://i.sstatic.net/mzlkY.png Error message https://i.sstatic.net/4LajF.png ...

perform a JSON request in a RESTful manner

Can you explain the concept of making a RESTful JSON request? In the given scenario, when Backbone attempts to read or save a model to the server, it calls upon the function known as Backbone.sync. This function, by default, utilizes (jQuery/Zepto).ajax t ...

Flow object with Angular using ng-flow: Existing flow object

Just a quick question that I can't seem to find an answer for on my own or through searching online. Currently, I have a button set up for clicking and uploading files. However, I also want to incorporate drag and drop functionality using the same fra ...

Using JavaScript regular expressions to find text that is not contained within an HTML tag

I am in search of a Regex pattern that can be used in node.js to match all text that is not part of an HTML tag or element. The challenge is to match text like "5", "ELT.", "SPR", " ", "plo", "Unterricht", " ", "&nbsp", and "plo" from a given ...

Exploring jasmine-node: unraveling the mysteries of errors

As I embark on my journey to learn JavaScript, I decided to tackle some exercises on exercism.io. This platform provides pre-written tests that need to be passed. While things were going smoothly initially, I hit a roadblock with the latest exercise where ...

The JavaScript function is designed to only accept whole numbers as input

Whenever I invoke a JavaScript function and pass along 4 parameters, it only functions properly if the fourth parameter consists of integers exclusively. Below is the code snippet for my onchange function: onchange="weekchange(this, <?php echo $i ?> ...

Create a new array in JavaScript by comparing and finding the differences between two existing arrays

I have two arrays - array1 and array2. I want to compare both arrays and create a new array (array3) with values that are unique to array1. For example, 'mob2', 'pin', 'address2', 'city' are present in array1 but no ...

Are there any alternatives to jQuery address in the realm of dojo?

Currently, I am working on developing an ajax application using dojo. I am curious if there is a feature comparable to jQuery Address in terms of functionality. My goal is to implement ajax-based hash url navigation similar to Twitter and Facebook using do ...

Retrieve all instances of Mondays within a specified date range, filtering out specific dates from an array

I need a PHP function to find and display all Mondays between two given dates, excluding specific dates. I want to show all dates but mark the excluded ones with a strike-through using HTML. The code I have works well, but I believe there might be a more ...

Angular15: How can we properly provide support for legacy browsers?

I'm having issues with my Angular build on IOS12 as it's only displaying a blank page. Below are the dependencies listed in my package.json: "dependencies": { "@angular/animations": "^15.0.0", "@angular ...

The expected functionality of sending files via ajax is not happening as anticipated

I am having issues with passing file data along with other inputs to my ajax function. Despite my best efforts, the server is not receiving the files. I'm fairly new to using ajax and Jquery. Below is the code snippet of what I have attempted so far. ...

PHP Hourly Loop Across Midnight

I've dedicated considerable time to finding a solution to creating a loop that will display the time between specific $start_time and $end_time values, increasing by one hour in the format HH:MM. For example, if the $start_time is "22:00" and $end_tim ...

Browser crashes due to JavaScript for loop

I am facing an issue where a particular loop is crashing the browser when executed. This loop is part of a set of three functions designed to factorize quadratic equations. After conducting tests, I am confident that the problem lies within the loop itse ...

Iterate through an array and append individual elements to a fresh array - ensuring only a single item is present in the new

I have been working on a project where I need to call a backend API and retrieve a JSON response. I have come across various solutions, but none seem to address my specific problem. The JSON data returned from the API is structured like this: [ { ...

The output from the Compute function is not showing up in the TextBox as expected

I'm currently working on an HTML page that contains two textboxes and a button. I've created a Compute function to display the result in one of the textboxes, but unfortunately, it's not functioning as expected. No alerts are appearing on th ...

The view in my node is rendering a different ejs view, and I have verified that the path

Currently, I am using the render method for a view in EJS. The path is correct but the view in the route is an old one that I used for testing purposes. This is my server.js code: https://i.sstatic.net/Xl1Ct.png Here is my route: https://i.sstatic.net/ ...

Having trouble with jQuery Ajax not transmitting data properly in a CodeIgniter project?

I am brand new to the Codeigniter MVC framework. Whenever I attempt to send data through ajax from the views to the controller, I encounter an error. Please click here to view the image for more details. Here is the code snippet: views/ajax_post_view.php ...

Troubleshooting the NullInjectorError in Angular - Service Provider Missing?

I'm facing an issue in my code where I have buttons that should trigger pop-ups displaying details as a list when clicked. However, every time I click the buttons, I encounter the error mentioned below. It seems like I am unable to access the desired ...

Looking for a sophisticated approach in Spring MVC to manage the escaping and unescaping of strings being passed to the Front End

Currently, I am in the process of developing a web application utilizing Spring MVC. This project involves retrieving multiple objects from the Database, each containing strings as attributes. It's worth noting that I have no control over the format o ...

There was an error: "TypeError: Unable to access the equipmentImage property of

Help needed! I am encountering a strange error while trying to upload an equipment image from postman as form data. The error states: Type Error; Cannot read property equipmentImage. I am using express-fileupload for the image upload process. Can someone ...