Brody
Brody

Reputation: 1

Having trouble understanding why my JS isnt working

Nothing is happening for me when I run this code.

var myarray = [2,2,2];

for ( var i = 0 ; i < myarray.length ; i++ ) {
  total = total + myarray[i];
}
alert("The total is " + total);

Upvotes: 0

Views: 20

Answers (3)

Armando Mendivil
Armando Mendivil

Reputation: 102

A nice way to solve it is using reduce as below, cheers! ;)

var arr = [1, 2, 3];


var total = arr.reduce((acum, current) => acum + current);

console.log(total);

Upvotes: 0

icdevin
icdevin

Reputation: 144

Try defining total outside of the loop first.

var myarray = [2, 2, 2];
var total = 0;
for (var i = 0; i < myarray.length; i++) {
  total += myarray[i];
}
alert(`The total is ${total}!`);

Something was happening, but you likely couldn't see it. Try to open the developer console in your browser if you're using one to run this, you'll see the error being generated.

Upvotes: 1

Rotem jackoby
Rotem jackoby

Reputation: 22068

Just declare your variable and initialise it:

var total =0;
for ( var i = 0 ; i < myarray.length ; i++ ) {
  total = total + myarray[i];
}
alert("The total is " + total);

Upvotes: 0

Related Questions