Exploring the world of array initialization in Javascript

function calculateAverage() {
  var total = 0;
  var arr = [];
  while (true) {
    var input = Number(prompt("Please enter a value"));
    if (input !== 0) {
      arr.push(input);
      total = arr.reduce(
        (accumulator, currentValue) => accumulator + currentValue
      );
    } else {
      alert("Values in array: " + arr);
      alert("Total sum: " + total);
      alert("Average: " + (total / arr.length));
      break;
    }
  }
}

I have developed a JavaScript program to calculate the sum, average of numbers in an array, and display the array. The code is functioning correctly, but I have a question regarding it.

When I initialize the empty array var arr=[]; outside the while loop, the program works as expected. However, when I declare it within the if block, the program only prints the last number added to the array during execution.

Being new to JavaScript, I am wondering if this issue relates to global versus local variables?

Any insights would be greatly appreciated.

Thank you!

Answer №1

By placing var arr = [] within the if block, you are essentially resetting the array with each iteration of the loop before adding new inputs. This means that the array will only hold the most recent input value. var arr = [] is a shorthand for

var arr;
arr = [];

The first line declares the variable while the second line assigns an empty array to it. If the variable already has a value, it gets overwritten by this new assignment, causing the previous contents to be lost.

You may have been taught that variable declarations using var are "hoisted" to the top of the function. However, this only applies to the declaration itself, not the actual assignment. So if the declaration and assignment are inside a loop, the variable gets reinitialized on every iteration.

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 determine if a watcher function executed right away in Vue 3?

When working with vue3, if I encounter a situation like this watch(loading, (new_val, old_val) => { // How can I determine whether this function was triggered immediately or after the initial run? }, {immediate:true}); Is there a way to achieve som ...

What is the solution to fixing the Vue 2 error when using Node 12?

Issue with Node 12: It seems that there is an error related to the node-sass library in Node 12. Error message from Node: node-pre-gyp ERR! node -v v12.1.0 node-pre-gyp ERR! node-pre-gyp -v v0.10.3 node-pre-gyp ERR! not ok ...

What is the best way to extract the ID from an event in TypeScript?

HTML Code: <ion-checkbox color="dark" checked="false" id="1on" (ionChange)="onTap($event)" ></ion-checkbox> TypeScript Code: onTap(e) { console.log(e); console.log(e.checked); } I am trying to retrieve the id of the checkbox. H ...

Exploring the world of three.js, webGL, and GLSL through the magic of random

When using three.js to call a fragment shader, I have a shader that specifies a color for my material in rgb format. I am trying to figure out a way to multiply those colors by a random value. The code I currently have is as follows: gl_FragColor = vec4( ...

Importing JSON data from a URL to display in an HTML table

Looking to utilize the Untappd API for a beer menu project, I've encountered an issue. The goal is to showcase the JSON data received from the server and organize it into an HTML table. Despite successfully importing data from a local list.json file ...

Connecting JavaScript and PHP strings

My goal is to transfer a JavaScript string to a PHP processing script and compare them. Upon successful match, I intend to conduct a simple validation process and if it passes, send an email notification. To provide context, below is a snippet of my curre ...

Embracing the power of dynamic imports in Next.js 10 with SDK integration for

I attempted to dynamically import the TRTC SDK using Next.js 10: const TRTC = dynamic(() => import('trtc-js-sdk').then((module) => module.NamedExport), { ssr: false }); However, I encountered an error stating "TRTC.createClient is not a co ...

Switch out a new js file every time the page is reloaded

I have a JS file with various objects (var), and I'm looking to dynamically load a different object each time the page is loaded. For instance, upon page load, a new object 'temp' should be created with data from one of the objects in the JS ...

Troubleshoot: How to Fix the socket.io net::ERR_CONNECTION_TIMED_OUT

I am facing an issue with my website's real-time chat functionality. It works perfectly on localhost without any errors. However, when I try to run it on the server, I encounter the following error: http://my.domain:52398/socket.io/?EIO=3&transpo ...

${IDHERE} element's text color not changing when tab is switched

One dilemma I encountered involves displaying a percentage on a webpage with 2 tabs. The percentage is originally shown on the tab that is open when the page loads. The JavaScript code I used is quite straightforward: adaPercentColor(percent, ada) { ...

Issue with react-table: data not displayed upon initial load and after refreshing the page

I am currently working on a project that involves rendering table data from an API using fetch. However, I'm encountering an issue where the table data disappears when navigating to a different page or refreshing the current page. Any assistance or ad ...

Update article translation dynamically in Vue without needing to refresh the page

ArticleController public function index() { $locale = Lang::locale(); // $locale = Lang::getLocale(); $articles = Article::withTranslations($locale)->get(); return $articles; } resources/assets/js/pages/articl ...

Look up a string array using a specified user and provide the indexes of the matching string array elements

I am facing an issue with finding the indexes of phrases that contain a specific keyword in an array. var possibleValues=["contacts","delete","new contact","add","display"]; The user input can vary, it could be "contacts" or even "how to create a contac ...

Node.js 5.0.0 facing compatibility issues with installing NPM packages

I'm currently in the process of setting up my npm packages that are required for my code to function properly. Unfortunately, every time I attempt to install any npm package, I am faced with the same error message: Your system is configured for Node ...

Steps for triggering a click event on a div with a button role within a class containing multiple elements

Can anyone help me figure out how to auto-click every button in Instagram's "hide story from" settings using console? I tried the following code: for (let i = 0; i < 300; i++) { document.getElementsByClassName('wbloks_1')[i] ...

The "angular2-image-upload" npm package encountering a CORS issue

Using the angular2-image-upload library for uploading files has been a smooth process until recently. After upgrading from version 0.6.6 to 1.0.0-rc.1 to access new features in future, I encountered issues with image uploads. The errors I faced were: htt ...

Iterate over a collection of objects to find connections between the starting and ending points, and retrieve the number of occurrences

My challenge involves analyzing an array of objects containing origin and destination data, and the total volume of objects moving between locations. I am specifically looking to compare flow counts between two cities. For example, when the origin is Vanco ...

Ways to verify if the current date exists within a TypeScript date array

I am trying to find a way in typescript to check if the current date is included in a given array of dates. However, even after using the code below, it still returns false even when the current date should be present within the array. Can anyone please pr ...

Running shell commands through child_process in JavaScript

Is there a way to execute shell commands from the browser and display the result on the UI using child_process? I'm having trouble fetching the results from the command line asynchronously. Is there something I'm overlooking here? const exec = ...

Retrieve the current height of the iFrame and then set that height to the parent div

Within a div, I have an iFrame that needs to have an absolute position for some reason. The issue is that when the iFrame's position is set to absolute, its content overlaps with the content below it. Is there a way to automatically adjust the height ...