最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Empty String Comparison - Stack Overflow

programmeradmin3浏览0评论

I don't understand why one scenario evaluates false and the other true.

Scenario 1:

> '' == ''
true

Scenario 2:

> '' == ('' || undefined)
false

Is scenario 2 not asking if (empty string) is equal to: (empty string) OR undefined?

I'm sure I'm missing something fundamental here, which is really what I'm trying to figure out. I can easily code around this, but I'd like to learn why it's happening... for next time, ya know?

I don't understand why one scenario evaluates false and the other true.

Scenario 1:

> '' == ''
true

Scenario 2:

> '' == ('' || undefined)
false

Is scenario 2 not asking if (empty string) is equal to: (empty string) OR undefined?

I'm sure I'm missing something fundamental here, which is really what I'm trying to figure out. I can easily code around this, but I'd like to learn why it's happening... for next time, ya know?

Share Improve this question asked May 21, 2012 at 19:23 Aaron FrancisAaron Francis 912 silver badges7 bronze badges 1
  • 2 your question is just like saying that 2 == 3 || 2 is testing if 2 equals 3 or 2. If you really stop to think about it as a puter would read it, you can see that it doesn't make sense – Ruan Mendes Commented May 21, 2012 at 19:29
Add a ment  | 

3 Answers 3

Reset to default 12
'' == ( '' || undefined )

Is not the same as

( '' == '' ) || ( '' == undefined )

It's more along the lines of:

var foo = '' || undefined; // Results in undefined

And then paring foo to an empty string:

foo == ''; // undefined == '' will result in false

Explanation

The logical || is a short-circuiting operator. If the argument to its left is truthy, the argument to the right is not even evaluated. In JavaScript, '' is not considered to be truthy:

if ( '' ) console.log( 'Empty Strings are True?' );

As such undefined is returned and pared against an empty string. When you perform this logic within a the parenthesis, the '' and the undefined don't know about the impending equality check that is waiting to happen - they just want to know which of them is going to survive this evaluation.

Let's break it:

'' == ('' || undefined) // return "undefined"
'' == undefined // false

|| return the first true value or the last value.

DEMO

You want this:

'' == undefined  || '' == false

undefined is == only to null, and not to all other "falsy" values:

  • 0
  • "" - empty string
  • NaN
  • false

try '' == '' || '' == undefined

As in almost all programming languages, the expressions at both sides of an operator must evaluate to a valid operand. || is logical OR operator which is used to evaluate a pair of boolean operands.

发布评论

评论列表(0)

  1. 暂无评论