开发者

How is it that if statements check types?

开发者 https://www.devze.com 2023-02-09 20:05 出处:网络
I come from a C# background a开发者_运维技巧nd need to become more familiar with JS.I\'m reading a book and in this example:

I come from a C# background a开发者_运维技巧nd need to become more familiar with JS. I'm reading a book and in this example:

var as = document.getElementsByTagName('a');
for(var i=0;i<as.length;i++){
    t=as[i].className;
    //Check if a link has a class and if the class is the right one
    if(t && t.toString().indexOf(popupClass) != -1)
    {
       //...
    }

Part of the if statement doesn't make sense. What is if(t)? I am used to if statements checking boolean values, but t is a string, right?


The if statement does type coercion.

if (o) block;

will only run the block. if o is "truthy"

The following values are falsy:

"", null, undefined, false, 0, NaN

The rest are truthy.

A good article can be found here

More to the point you have lots of dead code.

var as = document.getElementsByTagName('a');
for(var i=0;i<as.length;i++){
    t=as[i].className;
    // no need to check for whether t exists. No need to cast it to a string
    if(t.indexOf(popupClass) !== -1) // use !== for strict equality
    {
       //...
    }


if(t) checks if t is truthy.

http://11heavens.com/falsy-and-truthy-in-javascript

In this specific case, the most likely purpose of the check was to eliminate the possibility that t is null or undefined.


JavaScript performs automatic type conversion. These values evaluate to boolean false:

  • null
  • undefined
  • 0
  • ""
  • false
  • NaN

Anything else evaluates to true.

So it tests whether t has some truthy value and then performs some operation on t. If this wasn't done (e.g. if t is undefined or null), t.toString() would throw an error.


Have a look at the 'How good C# habits can encourage bad JavaScript habits' posts.

Basically, all these values are the same (false):

false
null
undefined
"" // empty string
0
NaN // not a number

So if(t) checks if the object is false, null, undefined, etc, etc...


if(t) is checking to see if t is a valid object. if(t) is like if(t != null).


Type casting

JavaScript is a weakly typed language, so it will apply type coercion wherever possible.

// These are true
new Number(10) == 10; // Number.toString() is converted
                      // back to a number

10 == '10';           // Strings gets converted to Number
10 == '+10 ';         // More string madness
10 == '010';          // And more 
isNaN(null) == false; // null converts to 0
                      // which of course is not NaN

// These are false
10 == 010;
10 == '-10'

In order to avoid that the use of the strict equal operator is recommended.

But this does still not solve all the issues that arise from JavaScript's weak typing system.

Source: JavaScript Garden

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号