Detailed explanation of mandatory and implicit conversion of types in JavaScript

Detailed explanation of mandatory and implicit conversion of types in JavaScript

1. Implicit conversion

What is the result of executing the following statement?

A. undefined == null
B. isNaN("100")
C. parseInt("1a") === 1
D. [ ] instanceof Array

Answer:

A. undefined == null is true; undefined === null is false

B. When NaN or a value that can be converted to NaN is passed in, isNaN returns true. "100" will be converted to Number–>100 first, which is not NaN, so it returns false.

C. parseInt("1a") will only parse the part that is preceded by a number, that is, only "1" will be parsed, and parseInt("1a1") === 1 is also true

D. [ ] is an empty array, return true

Conversion in double equals

After warming up, let's look at a piece of code:

if ([]) {
  console.log(true);
}

The result is true.

In fact, [] is false, because when comparing equal signs, if one side is a Boolean value, the data on both sides will be converted to Number first.
Right now:

Number([]); // 0
Number(false); // 0

Therefore [] is false.

However, when making an if statement, the data will be converted to Boolean type.

Right now:

Boolean([]); // true

So it can output true.

Summarize some techniques for double equal sign judgment:

  1. If there is NaN before and after the double equal sign, false is always returned;
  2. If there are Boolean values ​​(including 0 and 1) before and after the double equal sign, they are all converted to numbers before comparison (false is 0, true is 1);
  3. If there are strings before and after the double equal signs, there are three cases:
    1. If the other end is an object, the object is converted using toString or ValueOf;
    2. The other end is a number, a string to a number;
    3. The other end is a string, which is compared directly;
    4. All others return false.
  4. If one end is a number and the other end is a string such as '3', refer to the third item. The other end is an object, and the toString or ValueOf result of the object is used for comparison, otherwise false is returned;
  5. null and undefined are not type-converted, but they are equal;

Boolean Type Conversion

var test = new Boolean();
console.log(test);

var test = new Boolean(0);
console.log(test.valueOf());

var test = new Boolean(null);
console.log(test.valueOf());

var test = new Boolean("");
console.log(test.valueOf());

var test = new Boolean(NaN);
console.log(test.valueOf());

The answer is:

false false false false false

Here’s how it works:

  1. When called as a constructor (with operator new), Boolean() will convert its argument into a Boolean value and return a Boolean object containing that value. Note that the returned object is a Boolean object, which can be accessed through toString or valueOf.
  2. If called as a function (without operator new), Boolean() will simply convert its argument to a primitive Boolean value and return that value - a forced type conversion;
  3. If the value parameter is omitted, or is set to 0, -0, null, "", false, undefined, or NaN, the object is set to false. Otherwise set to true (even if the value parameter is the string "false").

"+" and "-"

console.log(1 + "2" + "2");
console.log(1 + +"2" + "2");
console.log("A" - "B" + "2");
console.log("A" - "B" + 2);

What is the output?

The result is: 122 32 NaN2 NaN

Analysis:

  1. Adding a number and a string will convert the number into a string, so the result is string concatenation. The first sentence outputs "122";
  2. +"2", the unary operator + here converts the string into a number, so 1+ +"2" = 1+2 = 3, and then merges with the following string, so the second sentence outputs "32";
  3. The minus sign will convert both sides of the minus sign into numbers first, and the results of Number("A") and Number("B") are NaN. In the subtraction operation, as long as one side is NaN, the result is NaN. Therefore, the third sentence is the concatenation of NaN and "2", and the result is NaN2 (mentioned in point 4.1, if one side of the double equal sign is NaN, the result is false);
  4. According to the analysis of the previous sentence, the result of "A"-"B" is NaN, and when added to the number 2, the result is still NaN

2. Forced type conversion

For the code var a = 10.42; to extract the integer part of a, which of the following codes are correct?

A. parseInt( a );
B. Math.floor( a );
C. Math.ceil( a );
D. a.split('.')[0];

Answer: AB

Many people will choose ABC at a glance.

Analysis:

A. parseInt converts to an integer, the default is decimal, and the result is 10;

B. floor is rounded down, the result is 10 - floor means floor, rounding down, to help memory;

C. ceil is rounded up, and the result is 11;

D. The split operand must be a regular expression or a string, otherwise TypeError is raised.

new String with ' '

Which of the following are true?

A. 'foo' == new function(){ return String('foo'); };
B. 'foo' == new function(){ return new String('foo'); };
C. [] == 0
D. ![]
E: !0

Answer:

A: Let me explain in detail below;

B: Let me explain in detail.
C: The result of Number([]) is 0, so option C is correct;
D: The object is always equal to true, but why is the result of judging an empty object == true or === true always false?

According to our summary of the double equal sign, when one side of the double equal sign is a Boolean value, both sides will be converted to the Number type. Therefore, when the console tests empty object == true or === true, it is actually executing empty object == 1 or === 1, so it returns false. Therefore, if you want to verify that the object is always equal to true, you should use !{} and !!{} !{}; // false; !!{}; // true

E: Since Boolean(0) == false, !0 = true, which is correct.

Let's talk about option AB. Due to the use of the new keyword and the call of the function constructor, the result is unexpected.

First of all, we need to know that when a constructor is called with new, if a reference object (array, object, function, etc.) is returned internally, the anonymous object created by new will be overwritten.

If a primitive type is returned (when there is no explicit return, undefined is actually returned), then the anonymous object created by new is returned.

It seems that

In option A, the constructor returns a string, so the final constructor returns an anonymous object created by new, which is an empty object.

In option B, a string object is returned inside the constructor, so the final constructor returns this object.

Summarize

This is the end of this article about mandatory and implicit type conversions in JavaScript. For more information about mandatory and implicit type conversions in JavaScript, please search previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript data visualization: ECharts map making
  • Super detailed basic JavaScript syntax rules
  • JavaScript implements changing the color of a web page through a slider
  • Detailed explanation of the differences between var, let and const in JavaScript es6
  • Detailed explanation of the this pointing problem in JavaScript
  • JavaScript function call, apply and bind method case study
  • Detailed explanation of the use of Arguments object in JavaScript
  • JavaScript CollectGarbage Function Example
  • Detailed explanation of BOM and DOM in JavaScript
  • JavaScript setTimeout and setTimeinterval use cases explained
  • JavaScript timer to achieve limited time flash sale function
  • JavaScript to implement limited time flash sale function
  • JavaScript Objects (details)

<<:  Detailed explanation of viewing and setting SQL Mode in MySQL

>>:  How to install openssh from source code in centos 7

Recommend

How to quickly deploy an Elasticsearch cluster using docker

This article will use Docker containers (orchestr...

About installing python3.8 image in docker

Docker Hub official website 1. Search for Python ...

Docker container custom hosts network access operation

Adding the extra_hosts keyword in docker-compose....

CSS3 achieves various border effects

Translucent border Result: Implementation code: &...

Detailed explanation of the process of using docker to build minio and java sdk

Table of contents 1minio is simple 2 Docker build...

Summarize the User-Agent of popular browsers

1. Basic knowledge: Http Header User-Agent User A...

JavaScript Objects (details)

Table of contents JavaScript Objects 1. Definitio...

Detailed explanation of common Docker commands

1. Help Command 1. View the current Docker versio...

React gets input value and submits 2 methods examples

Method 1: Use the target event attribute of the E...

Tutorial on installing GreasyFork js script on mobile phone

Table of contents Preface 1. Iceraven Browser (Fi...

Details of Linux file descriptors, file pointers, and inodes

Table of contents Linux--File descriptor, file po...

RGB color table collection

RGB color table color English name RGB 16 colors ...

One line of code solves various IE compatibility issues (IE6-IE10)

x-ua-compatible is used to specify the model for ...

Some notes on mysql self-join deduplication

Let me briefly explain the functional scenario: T...