Thursday, 13 April 2017

JavaScript and checking for 0

A friend and colleague who's new to the joys of JavaScript asked about checking for a value which is zero and I automatically suggested the old double tilde trick.

I worked up a JSFiddle to illustrate the concept:

let myArray = [
    0, "0", '0', [0],["0"],['0'], 
    1, "1", '1', [1],["1"],['1']
];

for (let value of myArray) {
    console.log(value, typeof value)
    console.info(
        "~~" + value + " === 0:",
        ~~value === 0);
}

But then I got to thinking about what else the value might be, like an object, string or an array of strings: {"name":"Fred"}, "Fred", 'Fred', [{"name":"Fred"},{"name":"Fred"}], ["Fred"], ['Fred'].

These, oddly, also equated to true when compared to 0. So I started thinking about checking the type and doing something interesting (complicated) but then I remembered the toString() method and all the issues I've had in the past with seeing [Object, Object] in pages I've been working on.

Perhaps I could use that and reverse the solution?

So instead of checking for 0 as a number I'd instead check for it as a string. This, then, is a solution that seems to work quite well:

let myArray = [
    0, "0", '0', [0], ["0"], ['0'], 
    1, "1", '1', [1], ["1"], ['1'], 
    {"name":"Fred"}, "Fred", 'Fred', [{"name":"Fred"},{"name":"Fred"}], ["Fred"], ['Fred']
];

for (let value of myArray) {
    console.log(value, typeof value)
    console.info(
        value + ".toString() === '0':", 
        value.toString() === '0');
}

Hope that helps someone, it's something I'll keep in mind in future!

No comments:

Post a Comment