Assigning a value to a variable can prevent the occurrence of an

My recursive code consists of two pieces aiming to print out half of the array recursively until we reach arrays of length 1. Surprisingly, the code without variable assignment runs infinitely, while the code with variable assignment behaves as expected.

Any ideas why this is happening?

Runs infinitely, CAUTION

function half(arr) {
  halfway = Math.floor((arr.length) / 2)
  console.log(arr)
  if (arr.length > 1) {
    half(arr.slice(0, halfway));
    half(arr.slice(halfway));
  }
  return
}

half([1, 2, 3, 4, 5]);

Does not run infinitely

function half(arr) {
  halfway = Math.floor((arr.length) / 2)
  console.log(arr)
  if (arr.length > 1) {
    var a = arr.slice(0, halfway);
    var b = arr.slice(halfway);
    half(a);
    half(b);
  }
  return
}

half([1, 2, 3, 4, 5]);

I initially thought that maybe mutability plays a role here, but I can't see how it would cause this effect. I presumed that we pass a new array into the function every time it's called...

Answer №1

Due to the absence of var, let, and const, the variable halfway in this code snippet has global scope, akin to writing window.halfway. Consequently, all recursive calls manipulate and access the same singular variable.

Within the 1st function, the value undergoes modification during the initial recursive call before it can be utilized in the subsequent one. This scenario, tested by me, actually resulted in a sort of Stack Overflow error (or rather a Maximum call stack size error), quite fitting for this platform :-).

Contrastingly, in the 2nd function, the value is utilized twice prior to the commencement of the recursive calls, subsequently being altered by both in consecutive succession.

The issue is resolved by incorporating const:

function half1(arr) {
  const halfway = Math.floor((arr.length) / 2)
  console.log(arr.toString())
  if (arr.length > 1) {
    half1(arr.slice(0, halfway));
    half1(arr.slice(halfway));
  }
  return
}

function half2(arr) {
  const halfway = Math.floor((arr.length) / 2)
  console.log(arr.toString())
  if (arr.length > 1) {
    var a = arr.slice(0, halfway);
    var b = arr.slice(halfway);
    half2(a);
    half2(b);
  }
  return
}

const data = [1, 2, 3, 4, 5];
half1(data);
console.log("------------------------")
half2(data);

As a final note: had the code been adorned with 'use strict';, the entire issue could have been detected and averted by the JS compiler. The peculiar effectiveness of this directive (initiating such extensive repercussions merely by adding a seemingly "dead and unused" string at the beginning of the code) is not one that I particularly appreciate, but we must utilize the tools at our disposal.

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

The sorting capabilities in Thonny Python are not performing to my expectations

I attempted to organize the marks in my code from highest to lowest, but encountered a problem with numbers that have 2 or more digits. Any assistance would be greatly appreciated. Thank you. print("**********STUDENT ANALYSIS**********") people ...

The AMP HTML file is unable to load due to the robots.txt file on https://cdn.ampproject.org restricting access

I've been trying to fetch and render my AMP HTML files individually, but they all seem to be encountering the same issue. According to the Search Console report, it says "Googlebot was unable to access all resources for this page. Here's a list: ...

Substitute placeholders in array with information using a loop

I have a question regarding implementing an autosort feature in JavaScript. I want my page to automatically sort data rows based on different time intervals selected by the user through checkboxes. The data updates every 3 seconds, and the autosort functio ...

Enhancing Function Calls for Better Performance in V8

Is V8 capable of optimizing repeated function calls with identical arguments? For instance, in the code snippet below, Variance is invoked twice with the same arguments. var Variance = require('variance'); function summary(items) { ...

Validating American phone numbers using regular expressions

I came across a Javascript regex that is used to validate the different formats in which US phone numbers can be written. However, there seems to be an issue with it: it fails to match the second rule within this specific group: The first group of three ...

Spirit.py navigates using javascript

Having trouble with Ghost.py. The website I'm trying to crawl uses javascript for paginated links instead of direct hrefs. When I click on the links, selectors are the same on each page so Ghost doesn't wait since the selector is already present. ...

The parameter provided should be in the form of a 12-byte string

Hey there, I am facing an issue while trying to delete an entry in my database. Despite attempting JSON.parse on the req.body and rearranging the routes in my routes file, I still can't seem to get it to work. Here is my controller: async function re ...

The Ajax function effortlessly receives the returned value and smoothly transitions to the error handling stage

When trying to retrieve data from an ajax request, my function needs to receive the returned data as an array of strings. During debugging, I am able to see the response, but at the same time, the error function is triggered. This is how my code looks: ...

showing information from a table column

Utilizing the jQuery DataTables plugin with a JSF <h:dataTable>. The page contains 86 records. +++++++++++++++++++++++++++++++++++++ + SN. + Name + Email + +++++++++++++++++++++++++++++++++++++ + 1 + Name 1 + Email 1 + + ...

Limit the elements in an array within a specified range of dates

Currently, I am working on implementing a filter functionality for a data array used in a LineChart within my Angular application using TypeScript. The structure of the data array is as follows: var multi = [ { "name": "test1", "series": [ ...

extracting a particular value from a JSON object using JavaScript

How can I extract a specific value from my JSON file using Node.js? var request = require("request"); var options = { method: "GET", url: "URL of my database", headers: { "cache-control": "no-cache&qu ...

Is it possible to utilize an Angular2 service with the DOM addEventListener?

Issue: I am encountering an problem where the service appears to be empty when trying to call it within an addEventListener. Html: <div id="_file0"> Service: @Injectable() export class FilesService { constructor(private http : Http) { } } Co ...

I'm running into an issue where I am unable to retrieve a variable from a separate

Struggling to populate a dropdown menu as I keep encountering an undefined error for all currencies when trying to reference them. A third party provided me with this code to simply fill the dropdown and make some text edits, but I'm puzzled as to wh ...

What are the steps for setting up API REST calls proxy for a frontend hosted on Netlify?

While testing locally, I am able to successfully post a call and access it through Netlify. However, once I host the frontend app on Netlify, the POST Proxy is being set to the Netlify URL. The hosted URL: Upon clicking "Sign Up" and then clicking on "Si ...

What is the best way to clear all input data that has been displayed in every input field within a React js application?

import React, { useState } from "react"; import axios, { Axios } from "axios"; import { ContainerDiv, InnerDiv, StyledButton, StyledInput, } from "./StyledComponents"; function WeatherCard() { const [input, SetInput ...

Is it possible to interact with a particular point or element within a canvas using languages like javascript, jquery, or selenium?

I am trying to figure out how to simulate a click at a specific position within a canvas. I have tried using coordinates, but so far haven't found a way to make it work. Any other suggestions would be greatly appreciated. It's important to note t ...

Is there a way to connect and interact with a different ng-controller's ng-model within a separate ng-controller?

Is it possible to access the ng-model from another ng-controller and if so, how can it be done? In this scenario, I am using two controllers. The first controller has a model called mddl1, while the second controller does not have any other model. However, ...

How can you make a variable function within an array loop in PHP?

At this moment, here is what I have: <?php $name = ($row1[2]); if($row1[45] == 1){ echo("<td class='nameSelect'>$name</td>"); } else{ echo("<td>$name</td>"); ...

C++ equivalent to Python's list append function

Currently diving into the world of C++ after spending time in Python. I'm curious if there is a method to add elements to an array in C++? myArray = {}; for (int i = 0; i < 10; ++i) { myArray.push_back(i); } Is there a similar approach avail ...

What is the reason behind the CSS not rendering when async:false is used?

I find it peculiar and am actively seeking an explanation for this anomaly. In my code snippet, the AJAX call seems to be causing unexpected behavior: $('.edit-config').click(function() { var that = this; var msg; ip ...