-2

There is two kind of JavaScript code for investigating empty/full variable:

if(variable == ''){}

if(!variable){}

I tested both of them, and I achieved identical result. Now I want to know, (first) are they equivalent? And (second) which one is more standard for checking empty/full variable?

var variable1 = 'string';
var variable2 = 12;
var variable3 = true;


if(variable1 == ''){alert('empty-one');}
if(variable2 == ''){alert('empty-one');}
if(variable3 == ''){alert('empty-one');}

if(!variable1){alert('empty-two');}
if(!variable2){alert('empty-two');}
if(!variable3){alert('empty-two');}

As you see, there is no alert.

Shafizadeh
  • 9,960
  • 12
  • 52
  • 89
  • What is your definition of "empty"? Is `variable` always a string? Could it be a number, an object, an array, a boolean, undefined, null...? – JJJ Nov 28 '15 at 14:19
  • Possible duplicate of [How do you check for an empty string in JavaScript?](http://stackoverflow.com/questions/154059/how-do-you-check-for-an-empty-string-in-javascript) – Kenney Nov 28 '15 at 14:19
  • the best answer for your question regarding "more standard" (if that even exists), it's that it depends. It depends on which kind of variable are you expecting to have. Also, providing "empty" variables with the proper kind will help you the most. So for example, if you expect variable `someString` to be a string, then when you don't want to pass it you should still pass an empty string, i.e. `""` – eAbi Nov 28 '15 at 14:25

3 Answers3

3

In javascript null,'',0,NaN,undefined consider falsey in javascript.

In one sense you can check empty both way

But your first code are checking is it ''

and your 2nd condition is checking is your value are one of them (null,'',0,NaN,undefined)

In my view your 2nd condition is better then first as i don't have to check null,'',0,NaN,undefined seperately

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
3

First is not standard, it only works for defined empty string.

Other will work if value is not truthy ( means something meaningful)

e.g var a;

a == '' will give false result
! a     will produce true

e.g. var a = null;

a == '', // false
! a      // true

var a = false;

a == '' // fase
! a     // true

var a = NaN

a == ''  // false
! NaN     // true

true == 'true' // false, Boolean true is first converted to number and then compared

0 == '' // true, string is first converted to integer and then compared

== uses The Abstract Equality Comparison Algorithm to compare two operands

For more detail visit http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3

Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
1

No they are not equivalent. In case first it checks whether the value of variable is equal to the empty string('') or not. So case first will be true iff variable's value is ''. But second case will be true for all the values which are falsey i.e. false, 0, '', null, undefined.

Hitesh Kumar
  • 3,508
  • 7
  • 40
  • 71