0

Noob problem.

In a Google Apps Script, I have an if statement that checks the value of a item in an array, which will either be a number, or blank:

var array = new Array();

array[0] = 1;

if (array[0] == '') {
 // this dos not execute
}

array[0] = 0;

if (array[0] == '') {
 // this executes
}

The contents of the second if statement get executed because it seems to be treating the 0 as a blank string. When I look at the value of array[0] in the debugger, it shows 0.0 (so it's definitely a number variable).

I first thought to use:

if (array[0] != 0 || array[0] == '')

but I can't use that because the actual if statement is a chain of OR operators like this:

if (array[0] == '' || array[1] == '' || array[2] == '') 

and the other values in the array are actually strings, not numbers.

How do I write the if statement so that it differentiates between a 0 number value and no data (blank)?

Employee
  • 2,231
  • 3
  • 33
  • 60

3 Answers3

4

Use ===

0 == ''  // true
0 === '' // false

Which equals operator (== vs ===) should be used in JavaScript comparisons?

Community
  • 1
  • 1
Matt
  • 20,108
  • 1
  • 57
  • 70
0

In javascript 0, '', false are called falsy. If you use a == operator on two falsy values - it's always true. Unless you use === operator.

http://www.sitepoint.com/javascript-truthy-falsy/

Are
  • 2,160
  • 1
  • 21
  • 31
  • That's not really why it works that way. The issue here is that when there's a number on one side of `==` and a string on the other, then the string is converted to a number before the comparison. The empty string is converted to 0 during that process, so the comparison made is `0 == 0` – Pointy Jan 23 '14 at 19:30
  • Also `NaN`, `undefined` and `null`. But using `==` on two falsey values is not always `true`. – cookie monster Jan 23 '14 at 19:30
  • For example, `NaN == 0` is `false`, though both those values are "falsy". – Pointy Jan 23 '14 at 19:31
  • These are all false: `NaN == NaN` `NaN == 0` `NaN == undefined` `NaN == null` `NaN == ""` `NaN == false` `undefined == 0` `undefined == ""` `undefined == false` `null == 0` `null == ""` `null == false` – cookie monster Jan 23 '14 at 19:33
  • And sometimes comparing a falsey value to a truthy value using `==` is `true`. – cookie monster Jan 23 '14 at 19:34
-2

You can use ===

For Example :

var array = new Array();

array[0] = 0;

if (array[0] === '') { // this doesn't execute }

if (array[0] == '') { // this executes }

zeomega
  • 345
  • 2
  • 6
  • 18