Search code examples
javascriptparseint

how to parse Zero (0) as integer in JavaScript


I am working on a basic calculator that takes input like this " 100 + 10/2 + 3 + 0 " and returns the output in a separate field. when I break this thing into an array zero is not parsed as integer. My code is as following

var arr = ["100", "+", "0"];
arr = arr.map(x => parseInt(x) || x);

console.log(arr);


Solution

  • Zero is a falsy value, so short-circuiting won't work here. You need to check explicitly

    var arr = ["100", "+","0"];
    arr = arr.map( x => x == 0 ? 0 : (parseInt(x) || x));
    console.log(arr);