Interviewer: What’s the difference between == and ===? Children: === requires the same data type, == will perform implicit type conversion… Interviewer: JavaScript:(a== 1&&a == 2&&a ==3) can print true? Children’s shoes:?????

Let’s look at the difference between == and ===, and the solution to the above problem.

The data type

In JavaScript, the data types are: undefined, NULL, Boolean, String, Number, Object, Symbol.

Object is called a reference data type, and the other six are called basic data types. Symbol is a string-like data type that represents unique values.

Implicit type conversion

Do a small experiment to find the result of comparing different types of values with the == operator

Type (x) Type (y) The results of
undefined null true
String Number toNumber(x) == y
Boolean Any data type toNumber(x) == y
Object Any data type toPrimitive(x) == y
Symbol Any data type false

The toNumber() and toPrimitive() methods are internal, so look at the valuation

The toNumber() method, better understood, is converted toNumber, similar to the Number() method.

type The results of
undefined NAN
null 0
Boolean Any data type
String Number

ToPrimitive () method

type The results of
Object Returns the original value if the result of the valueOf method on the object is the original value; If the object’s toString method returns the original value, this value is returned; All other cases return an error

For example, the toPrimitive() method

let test = {
  value: 0,
  valueOf () {
    console.log('in valueOf fun')
    return this.value
  },
  toString () {
    console.log('in toString fun')
    return this.value
  }
}

console.log('test == 0 ? ', test == 0)
Copy the code

Console output:

Back to the interview question

JavaScript:(a== 1&&a == 2&&a ==3) can print true?

let a = {
  value: 0,
  valueOf () {
    return ++this.value
  }
}
Copy the code

Don’t be afraid of implicit casting in your interview

This article was originally published at: github.com/yingye/Blog…

Welcome to pay attention to my Blog, like please click star, subscribe please click watch ~