One, foreword

Recently, in the process of writing a project, I found myself hesitating for a few seconds in the face of some empty zeros and strings when judging if statements

Sometimes it’s even horrible to write ugly code

if(str ! = =' ') {// do some things
}
Copy the code

Today, specially wrote this article to record, so that their long long memory, at the same time behind free to flip through the little Red book

Second, the test

Consider the following:

  • String is empty
  • Value is zero
  • undefined
  • null
  • Object property that does not exist
  • NaN

String is empty

if (' ') {
  console.log('Access empty string, can pass')}/ / no output
Copy the code

Value is zero

if (0) {
  console.log('Access 0, can pass')}/ / no output
Copy the code

undefined

if (undefined) {
  console.log('Access undefined, can pass')}/ / no output

if(!undefined) {console.log('Not undefined, can pass')}// not undefined, can pass
Copy the code

null

if (null) {
  console.log('NULL, can pass')}/ / no output

if(!null) {console.log('Non-null, can pass')}// Non-null, can pass
Copy the code

Object property that does not exist

let obj = {
  foo: "foo".num: 0
}

if (obj.bar) {
  console.log('Access object without attribute can pass')}/ / no output

if (obj.foo) {
  console.log('Can access existing properties of an object through')}// Access existing attributes of the object
Copy the code

NaN

if(NaN) {console.log('Access NaN, can pass')}/ / no output
if(!NaN) {console.log('Not for NaN, can pass')}// No NaN, can pass
Copy the code