JavaScript Function Call Crashes Script

Currently, I am delving into the world of JavaScript by exploring . I find it beneficial to tackle the exercises provided before progressing to the next chapter as a way to practice.

After completing chapter 4 and reviewing the exercises found at the end of the chapter, you can access them via this link:

I have just started working on the first exercise question.

I have managed to successfully complete the initial two sections of the first exercise question which are:

Create a range function that accepts start and end parameters and returns an array with all numbers between start and end inclusive.

Next, create a sum function that takes an array of numbers and calculates the total sum. Run the previous program to verify if it indeed returns 55.

The code I used looks like this:

// Your implementation here.
function range(start, end)
{
  var rangearray = new Array();
  for(var i = start; (i <= end + 1); i++)
    rangearray.push(i);
  return rangearray;
}

function sum(numarray)
{
  var result = 0;
  for(var numb in numarray)
    result += parseInt(numarray[numb]);
  return result;
}

console.log(sum(range(1, 10)));
// → 55 (desired output achieved without difficulty)

However, I am struggling with the bonus task associated with the same exercise, even though it seems relatively straightforward:

As an additional assignment, modify your range function to accept an optional third argument indicating the step value to build the array. If no step is given, the elements increase by one increment as per the old behavior. The function call range(1, 10, 2) should produce [1, 3, 5, 7, 9]. Ensure it functions properly with negative step values such as range(5, 2, -1) resulting in [5, 4, 3, 2].

This is the code snippet I have been using:

// Your implementation here.
function range(start, end, step)
{
  var rangearray = new Array();
  end = (end < start) ? end - 1 : end + 1;
  step = (typeof step === 'undefined') ? 1 : parseInt(step);
  for(var i = start; ((step < 0) ? (i >= end) : (i <= end)); (i += step))
  {
    rangearray.push(i);
  }
  return rangearray;
}

function sum(numarray)
{
  var result = 0;
  for(var numb in numarray)
    result += parseInt(numarray[numb]);
  return result;
}

console.log(range(5, 2, -1));
// → [5, 4, 3, 2] (expected output)

Upon running the code, I encountered a warning stating that it has taken longer than 2 seconds to execute, with an option to abort. This message repeats after 10 seconds, leading to the following error upon abortion:

Error: Aborted (line 204 in function tick)

Called from line 9 in function range

Called from line 25

Any advice or assistance on resolving this issue would be greatly appreciated. :)

Answer №1

Make sure to update the value of i correctly.

i += step; 

It should be written as:

i = i + step;
 // or
 i += step;

If you don't increment the value of i properly, it will result in an infinite loop causing the browser to crash.

Answer №2

Congratulations! You've encountered this message because you've successfully created an infinite loop in your code! It's a common mistake, so don't worry too much. The loop you made won't stop running because "i" is not incrementing to reach the end value. Instead of just performing mathematical operations without updating the value of "i", remember to use "+=" to properly assign it as itself plus the "step". I removed the ternary operator for "end" as it was unnecessary. Your JavaScript skills are on point!

One helpful tip: avoid using a ternary operator within a for loop.

// Check out your revised code.
function range(start, end, step)
{
    var rangearray = new Array();
    step = (typeof step === 'undefined') ?     
                           1 : parseInt(step);
    var i = 0;
    for(  i = start; i <= end ; (i += step) )
        {rangearray.push(i);}
    return rangearray;
}

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

Is there a way to transfer table data from one table to another table using AngularJS?

I have a situation where I need to transfer data from one table to another. There are four buttons available: Right, AllRight, Left, and AllLeft. When the Right button is clicked, only the selected row should move to the left side table. When the AllRight ...

Waiting for a method to finish in Node.js/Javascript

Currently, I am in the process of creating a trade bot for Steam. However, I have encountered an issue where the for-loop does not wait for the method inside it to finish before moving on to the next iteration. As a result, the code is not functioning as i ...

Error: Attempting to access property 'toLocaleLowerCase' of an undefined value

I've been working on a custom pipe following the instructions carefully, but I keep encountering an error when trying to filter my list. Below is the code for my custom pipe: import { Pipe, PipeTransform } from '@angular/core' ...

PHP - The variable $_SESSION['var1'] has not been set within the index.php file

My index.php page is causing me some confusion. <?php session_start(); if (!isset($_SESSION['var1'])) { echo "session not started..."; die(); } else { echo "session started"; die(); } ?> Within the page, there is a login form that connec ...

Learn how to activate static methods in JavaScript while also restricting the utilization of instance functions without the necessity of using the new operator

What is the best way to allow the usage of static methods while restricting the use of instance functions without utilizing the new operator? In this scenario, the constructor will trigger an exception if it is called without the new operator. However, thi ...

Utilizing a personalized service within an extended RouterOutlet component in Angular 2 for streamlined authentication

In my quest to establish authentication in Angular 2, I turned to an insightful article (as well as a previous inquiry on SO) where I learned how to create a custom extended RouterOutlet: export class LoggedInRouterOutlet extends RouterOutlet { public ...

What is the best method to initialize a JavaScript function only once on a website that uses AJAX

Currently, I am facing an issue with a javascript function that needs to be contained within the content element rather than in the header. This is due to a dynamic ajax reload process which only refreshes the main content area and not the header section. ...

Utilizing Index Match with multiple conditions across various rows in Google Sheets

Currently, I am facing the challenge of matching date and time along with metric categories across multiple rows in a data sheet. My daily practice involves recording metrics in a structured manner, with rows organized by time intervals and dates. It woul ...

What is the reason for Convert.ToInt32(Byte) and Convert.ToInt32(Byte[]) to compile successfully, while Convert.ToInt32(byte[]) causes a runtime exception to be thrown?

Every time I attempt to use Convert.ToInt32(byte[]), I encounter an invalidCastException. I'm curious if this is a common issue or if I am making a mistake. Can someone explain why a compiler error is not thrown when using a byte[] in a method withou ...

Error: Please provide the required client_id when setting up Google Sign-In with Next-Auth

I have been trying to implement the Sign in with Google option in my Next.js application using next-auth. Below is a snippet of my [...nextauth].js file located in the api/auth folder: import NextAuth from "next-auth"; import Google ...

Clarification on Initializing Mersenne Twister with an Array

Attempting to achieve cross-platform consistent random number generation with a 32-bit seed has been a challenge. Many suggestions lead to utilizing the Mersenne Twister algorithm or creating a custom implementation. Upon examining the source code, there ...

Determine if each element in an array is present in the MongoDB document's array

Is it possible to determine whether a specific element exists within an array in a MongoDB document? For instance: If we have the following document { "_id": "A", "userId": "B", "selectedUsers": ["C", "D"] } and another array ["E", "C"]. ...

Utilize Jquery's "find" function to showcase an image

I am attempting to showcase an image using jQuery. I have a function that accepts ID and PATH as parameters. The ID indicates the section (each section is an HTML page that loads upon user action). Additionally, there is a text area where I am displaying t ...

The $route.reload() function seems to be ineffective in Internet Explorer

I'm currently using AngularJs to develop an application. The issue I am encountering is related to data not being refreshed in IE, even after executing the $route.reload() function. Strangely enough, this problem only occurs in Internet Explorer and w ...

Guide on replacing buttons with <a> tags in express.js posts

I've incorporated handlebars as my chosen templating engine and I'm utilizing buttons to trigger app.post() in my JavaScript file. <form method="POST" action="/smo_assessment"> <div class="container" id="div1"> <h3 id="header" ...

Detecting when the cursor leaves an input field in JavaScript

Hello there! Interested in learning how to detect when the cursor leaves an input field? Once the cursor has exited the input field Run a notification with the message "some Text"; ...

What could be the reason my dropdown menu is not appearing on hover?

Currently, I am in the process of developing a menu using angularJS and google app script within a dialog box. I have been referring to this sample code for guidance. Instead of pasting all my code here, I can summarize what I have come up with: var a ...

ways to establish pathways for a function within express

My controller, var express = require('express'); var router = express.Router(); var mysql = require('mysql'); var connection = mysql.createConnection({ // connectionLimit : 100, //important host: 'localhost', user ...

I'm so confused about the operation of each method in this context

I am experimenting with a simple process involving setTimeout function. My goal is to make the letters of a name appear individually and gradually at different times. For example, if the name is NAZ, I want the letters to appear in this order: first N, the ...

Utilizing one JavaScript file and consistent classes for multiple modals

Is it possible to have multiple modals using the same JS file, classes, and IDs? I created this code: <button id='myBtn'>Order/Discount</button> <div id='myModal' class='modal'> <div clas ...