Section 2.1: Falsy VSTruthy Value and == VS ===

Falsy VS Truthy Value and == VS ===

  • Falsy values: undefined, null, 0, '', NaN
  • Truthy values: Not falsy values
var height;

    if (height) {
        console.log('Variable is defined');
    } else {
        console.log('Variable has NOT been defined');
    }

In this code above, the result is: Variable has NOT been defined, because height is undefined -- falsy value

So, if we insert height = 23 before if, height will become a truthy value. The result will be Variable is defined

	var height;
    height = 23;
    if (height) {
        console.log('Variable is defined');
    } else {
        console.log('Variable has NOT been defined');
    }

But again, if height = 0; , it will return Variable has NOT been defined

    var height;
   height = 0;
   if (height) {
       console.log('Variable is defined');
   } else {
       console.log('Variable has NOT been defined');
   }

Next I will talke about the ||, == and ===.

   var height;
    height = 0;
    if (height || height === 0) { // height == 0)
        console.log('Variable is defined');
    } else {
        console.log('Variable has NOT been defined');
    }

"||" means "or". Therefore, if will check the two conditions, if one of the condition is met, it will console.log 'Variable is defined'. Here, height === 0, so it returns Variable is defined.

Operation == is called "lenient" or "normal" equality. == only compares the value, it does not compair the type of value.
Operation === is called “strict” or “identical” equality. === compares the value and type. if var a=0, and int b=0, a=b returns false, because the type is different.

    console.log(23 == '23')  //--- ture
    console.log(23 === '23') // ---false
posted @ 2022-01-23 23:54  鑫仔Alan  阅读(31)  评论(0编辑  收藏  举报