Why should I use string.length == 0 over string == “” when checking for empty string in ECMAScript?

不问归期 提交于 2019-12-05 00:15:54
Shog9

I actually prefer that technique in a number of languages, since it's sometimes hard to differentiate between an empty string literal "" and several other strings (" ", '"').

But there's another reason to avoid theString == "" in ECMAScript: 0 == "" evaluates to true, as does false == "" and 0.0 == ""...

...so unless you know that theString is actually a string, you might end up causing problems for yourself by using the weak comparison. Fortunately, you can avoid this with judicious use of the strict equal (===) operator:

if ( theString === "" )
   // string is a string and is empty

See also:

The problem is that if theString is set to 0 (zero) your 2nd example will evaluate to true.

The correct answer is correct and it's important to understand type checking. But as far as performance, a string compare is going to lose to .length method every time, but by a very very small amount. If you aren't interested in shaving milliseconds from your site speed, you may want to choose what is more readable / maintainable to you and , more importantly, your team.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!