Câu hỏi phỏng vấn Javascript
Câu hỏi

Explain equality in JavaScript

Câu trả lời

Equality in JavaScript is determined by two sets of operators: the abstract equality operator (==) and the strict equality operator (===). These operators are used to compare two values and determine if they are equal.

Abstract Equality Operator (==)

The abstract equality operator, also known as the loose equality operator, compares two values for equality after performing type coercion if necessary. When using ==, JavaScript attempts to convert the values to a common type before making the comparison. This can sometimes lead to unexpected results because different types can be considered equal. For example, the string '5' and the number 5 are considered equal when compared with == because JavaScript coerces the string to a number before the comparison[1][2][3][5][8][9][12][13].

Strict Equality Operator (===)

The strict equality operator, on the other hand, does not perform type coercion. It compares both the value and the type of the two operands. If the operands are of different types, the comparison will immediately return false. For example, '5' === 5 will return false because the operands are of different types: one is a string, and the other is a number[1][2][3][5][6][7][11][12].

Special Cases

There are some special cases to consider when dealing with equality in JavaScript:

  • NaN is not equal to anything, including itself. To check if a value is NaN, you should use the Number.isNaN() function instead of equality operators[7][8][12].
  • +0 and -0 are considered equal under both the abstract and strict equality operators[7][11][12].
  • null and undefined are equal when compared with ==, but not when compared with ===[8][12].

Best Practices

Due to the potential for confusion and errors with type coercion, it is generally rec...

entry

entry

Gợi ý câu hỏi phỏng vấn

senior

What are the actual uses of ES6 WeakMap?

middle

What is the preferred syntax for defining enums in JavaScript?

middle

Could you explain the difference between ES5 and ES6

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào