What is the difference between == and === in JavaScript? [duplicate]

耗尽温柔 提交于 2020-12-29 14:11:56

问题


Possible Duplicate:
Javascript === vs == : Does it matter which “equal” operator I use?
When would JavaScript == make more sense than ===?

What is the difference between below methods in comparing a string with undefined value.

 var x; 
 if(x==undefined) 
 { 
  alert(x); 
 }

and

if(x===undefined)
{ 
  alert(x); 
}

Why should i prefer second method in this case.. Please let me know advantages..


回答1:


  • == attempts to convert the values to the same type before testing if they're the same. "5" == 5
  • === does not do this; it requires objects to be of the same type to be equal. "5" !== 5

In this case, the result is:

  • x == undefined will be true if x is undefined or null.
  • x === undefined will only be true if x is undefined.

You should prefer the first method if you'd like undefined and null to be treated equivalently. One common use of this is optional function arguments.

function greet(name, greeting) {
    if (name == undefined) name = 'World';
    if (greeting == undefined) greeting = 'Hello';
    alert(greeting + ' ' + name);
}

greet(); // alerts "Hello World"
greet("Bob"); // alerts "Hello Bob"
greet(null, "Goodbye"); // alerts "Goodbye World"



回答2:


suppose we have x=5,

== is equal to

x==8 is false x==5 is true

=== is exactly equal to (value and type)

x===5 is true x==="5" is false

Hope you understand this concept




回答3:


== is just comparing the two values, and if they are of different types, type conversion is done

=== compares the values and well as their types - so no type conversion will be done here.




回答4:


=== checks for the same type as well. You'll understand with a few examples:

(1 == '1') //Returns true

Since == doesn't bother with types, that returns true. However, if you want strict type checking, you'd use === because that returns true only if the it's of the same type, and is the same value.

(1 === '1') //Returns false
(1 === 1) //Returns true
  • Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding
    positions.
  • Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything,
    including NaN. Positive and negative zeros are equal to one another.
  • Two Boolean operands are strictly equal if both are true or both are false.
  • Two objects are strictly equal if they refer to the same Object.
  • Null and Undefined types are == (but not ===).

Reference



来源:https://stackoverflow.com/questions/8132353/what-is-the-difference-between-and-in-javascript

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