Krzysztof Wanat
Krzysztof Wanat

Reputation: 11

Why are for...of and for loop behaving differently?

Just was performing simple task in JS which was to take integer as an input, divide it into single digits and multiply them ignoring all zeros in it.

I have solved it but had some troubles which were simply solved by changing the loop. I am just curious why the code did not work properly with the for loop and started to work as I it for for of loop. I could not find out the answer by my self. If somebody could tell where I am wrong.

First one works as intended, second one always returns 1.

function digitsMultip1(data) {
  var stringg = data.toString().split("", data.lenght);
  for (let elements of stringg) {
    if (elements != 0) {
      sum = parseInt(elements) * sum
    } else {
      continue
    };
  }
  return sum;
}
console.log(digitsMultip1(12035))


function digitsMultip2(data) {
  var sum = 1;
  var stringg = data.toString().split("", data.lenght);
  for (var i = 0; i > stringg.lenght; i++) {
    if (stringg[i] != 0) {
      sum = parseInt(stringg[i]) * sum
    } else {
      continue
    };
  }
  return sum;
}
console.log(digitsMultip2(12035))

Upvotes: 1

Views: 55

Answers (1)

mplungjan
mplungjan

Reputation: 177975

There is no big difference. for..of works in newer browsers

The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, Array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.

Several typos

length spelled wrong

> (greater than) should be < (less than) in your for loop

Now they both work

function digitsMultip1(data) {
  var sum=1, stringg = data.toString().split("");
  for (let elements of stringg) {
    if (elements != 0) {
      sum *= parseInt(elements)
    } else {
      continue
    };
  }
  return sum;
}
console.log(digitsMultip1(12035))


function digitsMultip2(data) {
  var sum = 1, stringg = data.toString().split("");
  for (var i = 0; i < stringg.length; i++) {
    if (stringg[i] != 0) {
      sum *= parseInt(stringg[i]) 
    } else {
      continue
    };
  }
  return sum;
}
console.log(digitsMultip2(12035))

You might want to look at reduce

const reducer = (accumulator, currentValue) => { 
  currentValue = +currentValue || 1; return accumulator *= currentValue 
}

console.log(String(12035).split("").reduce(reducer,1));

Upvotes: 2

Related Questions