Having trouble retrieving the global variable within a while loop

I'm facing a challenge while working on this coding problem. It seems that I can't access the global variable within the while loop, as it returns undefined whenever I try to do so.

function calculateSum(arr1, arr2, arr3) {
  let sum1 = 0;
  let sum2 = 0;
  let sum3 = 0;
  let first = [];
  let second = [];
  let third = [];
  
  while (arr1.length !== 0) {
    var poppedItem = arr1.pop();
    sum1 += poppedItem;
    first.push(poppedItem);
  }
  
  while (arr2.length !== 0) {
    var poppedItem = arr2.pop();
    sum2 += poppedItem;
    second.push(poppedItem);
  }
  
  while (arr3.length !== 0) {
    var poppedItem = arr3.pop();
    sum3 += poppedItem;
    third.push(poppedItem);
  }
  
  while (sum1 === sum2 && sum2 === sum3 && sum3 === sum1) {
    // The following two console logs are not functioning correctly.
    console.log(sum1, sum2, sum3);
    console.log(arr1, arr2, arr3);
    
    if (sum1 > sum2) {
      var x = first.pop();
      sum1 -= x;
    } else if (sum2 > sum3) {
      var y = second.pop();
      sum2 -= y;
    } else {
      var z = third.pop();
      sum3 -= z;
    }
  }
}

console.log(calculateSum([3, 2, 1, 1, 1], [4, 3, 2], [1, 1, 4, 1]));

Answer №1

Your method equal() is not returning any value, which means that if you try to console it, the output will be undefined. Make sure to add a return statement in your method to avoid this issue.


Modified Code Snippet Included

function equal(h1, h2, h3){
    let sum3 = 0;
    let third = [];
    let count = 0;
    while (h3.length !== 0){
        var popped = h3.pop();
        sum3 += popped;
        third.push(popped);
        // global variables inside the while loop
        console.log(sum3)
    }
}

console.log(equal([ 3, 2, 1, 1, 1 ], [ 4, 3, 2 ], [ 1, 1, 4, 1 ]));

Answer №2

Defining Key Terms

Understanding Global Variables and Scope

Exploring Lexical Scope


Common Misconceptions

1. Confusion about the concept of global variables.

Variables are confined within a function's lexical scope and are assessed sequentially, moving from local scope to parent scope to global scope (window in a browser, global in nodejs). What may seem like "global scope" is actually the local scope of the equal function or a while loop.

2. Expecting a return value from equal without using a return statement

console.log(equal([3, 2, 1, 1, 1], [4, 3, 2], [1, 1, 4, 1]));

The equal function does not return anything, hence nothing will be displayed on the console.

3. Misunderstanding the evaluation process of JavaScript

JavaScript executes code synchronously (refer to this for more insights). Hence, your while loops are executed one after another until the length of each array being evaluated reaches 0. The final while loop will only come into play afterward.

while(sum1 === sum2 && sum2 === sum3 && sum3 === sum1)

This loop will iterate only if all three conditions hold true. When you run equal as shown:

equal([3, 2, 1, 1, 1], [4, 3, 2], [1, 1, 4, 1])

The final while loop will yield false (represented in pseudo code):

sum1 = (3 + 2 + 1 + 1 + 1) = 8 
sum2 = (4 + 3 + 2) = 9 
sum3 = (1 + 1 + 4 + 1) = 7
---
sum1 != sum2 && sum2 != sum3 && sum3 != sum1

As a result, the iteration won't take place, and the output of console.log(sum1, sum2, sum3), within the final while loop, won't be printed.

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

Tips for integrating html2canvas with Vue JS?

One hurdle I encountered was the absence of a shorthand for document.getElementById in Vue. To address this, I created a custom function similar to this one. Another challenge I am currently grappling with is the perceived limitations of the html2canvas do ...

Leveraging the power of Auth0 and Prisma in aggregating user data

In my current project, I am developing a Next.js application with Auth0 as the authentication system. Users are authenticated using the standard middleware: import { withMiddlewareAuthRequired } from '@auth0/nextjs-auth0/edge'; export default wi ...

What is the most efficient way to extract arrays from a multidimensional array where a particular column has a non-empty value?

I am working with a multidimensional array as shown below: $array = [ 0 => [ "id" => 1, "name" => "Sammy", "phone" => "2348055643322", "email" => "<a href="/cdn-cgi/l/email-protection" ...

Verify whether an HTML element lies within another HTML element

Consider this example: <div id="President"> <div id="Congressman"> <div id="Senator"> <div id="Major"></div> </div> </div> </div> Is there a simple way in JavaScript or jQuery to determine ...

Error thrown: Uncaught TypeError - Attempted to access 'params' property of undefined object in the context of StudentDetails

I've encountered an issue where I need to transfer student application data from my server-side to my client-side. Whenever a new student application is created, I want to display their information on my StudentDetails.jsx file. Here is my Server.js c ...

How can I create a route using associations for /users/me in Sails.js?

My primary model is called Accounts. Additionally, I have several Has Many models such as Notifications and Friends Within my file named main.js, I would prefer to execute commands like: socket.get('/users/me/notifications'); instead of: soc ...

Error: Exceeded Maximum Re-Renders. React has set a limit on the number of renders to avoid infinite loops. Issue found in the Toggle Component of Next.js

I am struggling with setting a component to only display when the user wants to edit the content of an entry, and encountering an error mentioned in the title. To achieve this, I have utilized setState to manage a boolean using toggle and setToggle, then ...

Calculate the cumulative values in ng-repeat using AngularJS

I used ng-repeat to iterate through a JSON array. I calculated the number of nights by utilizing the dayDiff() function. Now, I need to find the total number of nights for all invoices. My project is built with AngularJS. Is there a way to retrieve the to ...

What are the steps to integrate Webpack into an EJS Reactjs Express MongoDb application?

I have incorporated EJS, Express/NodeJs, and MongoDB into the project, along with ReactJs as an addition. My next step is to introduce Webpack for bundling both EJS and ReactJs files together. Although the end goal is to transition the p ...

Adjusting the text and background hues using JavaScript results in an immediate reversal

Attempting to dynamically change the text color and background color based on user input in the textbox. While it initially works, the color changes only flash for a brief moment before reverting back. <!DOCTYPE html> <html> <head> ...

AngularJS ng-view is a directive that views the application

I am currently struggling to create an angular js menu. I have been working on my code, but the pages are not loading as expected. Do you think I missed something or did I forget to include all the necessary scripts? I am fairly new to angular and could us ...

Retrieve recently appended DOM elements following the invocation of createComponent on a ViewContainerRef

I have a current function in my code that dynamically creates components and then generates a table of contents once the components are added to the DOM. This service retrieves all h3 elements from the DOM to include in the table of contents: generateDy ...

How to smoothly transition a div from one location to another using animations in an Ionic3-Angular4 application

I'm attempting to incorporate some animation into my Ionic 3 mobile app. Specifically, I want to shift a div from one location to another. In the code snippet provided below, I am looking to move the div with the "upper" class after the timeline-item ...

Detecting collisions in Three.js

I seem to be overlooking something quite fundamental, as I can't seem to find a solution in the documentation or any other working code examples. I am currently creating a basic museum using THREE.js libraries. While most of it is set up, I need to im ...

Sometimes, it feels like TypeScript's async await does not actually wait for the task to complete before moving on

Recently, I have been transitioning to using the async await pattern more frequently instead of the traditional Promise syntax because it can help in keeping the code structure cleaner. After some experimentation, I felt like I had a good grasp on how to u ...

Managing form submissions in React with inputs spread across multiple components

I've been working on a ReactJS project with a form that is divided into multiple components. The main component imports all the child components, each containing input boxes, along with a submit button: My issue lies in trying to get all the componen ...

How can the AngularJS model be updated while using long polling with Ajax?

How can I update the model using ajax long polling method? To start, I will load the default list: For example: - id1 - id2 - id3 Next, I set up an ajax long polling process in the background that runs every 5 seconds. When the ajax call receives an upd ...

Replicate and $(document).ready()

My form has required fields that need to be completed. To alert users about blank fields, I have implemented the following code: $(document).ready(function() { $('input.required:text').focus(function() { $(this).css({'background ...

Is there a way to continue a failed fetch request?

I am curious about the possibility of resuming an incomplete fetch request if it fails due to a non-code-related issue, like a lost network connection. In one of my current projects, we send a large download via AJAX to the client after they log in. This ...

Vue.JS - Dynamically Displaying Property Values Based on Other Property and Concatenating with

I have a reusable component in Vue.js called DonutChart. <donut-chart :chartName="graphPrefix + 'PerformanceDay'" /> The value of the property graphPrefix is currently set to site1. It is used as part of the identifier for the div id ...