search
HomeWeb Front-endJS TutorialWhat is implicit type conversion? Introduction to js implicit type conversion

This article brings you what is implicit type conversion? The introduction to js implicit type conversion has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

JavaScript's data types are very weak. When using arithmetic operators, the data types on both sides of the operator can be arbitrary. For example, a string can be added to a number. The reason why operations can be performed between different data types is because the JavaScript engine will quietly perform implicit type conversion on them before the operation. The following is the addition of numeric types and Boolean types:

3 + true; 
// 结果:4

The result is a numeric value! If it is in a C or Java environment, the above operation will cause an error because the data types on both sides of the operator are inconsistent. However, in JavaScript, only in a few cases, the wrong type will cause an error, such as calling a non-function, or reading When taking null or undefined attributes, it is as follows:

"hello"(1); 
//结果: error: not a function
null.x; 
// 结果:error: cannot read property 'x' of null

In most cases, JavaScript will not make an error, but will automatically perform the corresponding type conversion. For example, arithmetic operators such as -, *, /, and % will convert the operands into numbers, but the " " sign is a little different. In some cases, it is an arithmetic plus sign, and in other cases, it is a string concatenation. Symbol, the specific details depend on its operands, as follows:

2 + 3; 
//结果: 5
"hello" + " world"; 
// 结果:"hello world"

However, if strings and numbers are added, JavaScript will automatically convert the numbers into characters, regardless of whether the numbers or strings come first. As follows:

"2" + 3; 
// 结果:"23"
2 + "3";
 //结果: "23"

The result of adding a string and a number is a string!

It should be noted that the operation direction of " " is from left to right, as follows:

1 + 2 + "3"; 
// "33"

This is equivalent to the following:

(1 + 2) + "3"; 
// "33"

Compare Next, the following results are different:

1 + "2" + 3; 
// "123"

However, implicit type conversion sometimes hides some errors, for example, null will be converted to 0, and undefined will be converted to NaN. It should be noted that NaN and NaN are not equal (this is due to the precision of floating point numbers), as follows:

var x = NaN;
x === NaN; // false

Although JavaScript provides isNaN to detect whether a value is NaN, however, This is not very accurate, because before calling the isNaN function, there is an implicit conversion process, which will convert values ​​that are not NaN to NaN, as follows:

isNaN("foo"); // true
isNaN(undefined); // true
isNaN({}); // true
isNaN({ valueOf: "foo" }); // true

The above code , after we used isNaN to test, we found that strings, undefined, and even objects all returned true! ! ! But they are not NaN.

In short: isNaN detection of NaN is not reliable! ! !

There is a reliable and accurate way to detect NaN.

We all know that only NaN is not equal to itself. You can use the inequality sign (!==) to determine whether a number is equal to itself. Therefore, NaN can be detected, as follows:

var a = NaN;
a !== a; // true
var b = "foo";
b !== b; // false
var c = undefined;
c !== c; // false
var d = {};
d !== d; // false
var e = { valueOf: "foo" };
e !== e; // false

We can also define this mode as a function, as follows:

function isReallyNaN(x) {
    return x !== x;
}

Implicit conversion of objects

Objects can be converted into primitive values , the most common method is to convert it into a string, as follows:

"the Math object: " + Math; // "the Math object: [object Math]"
"the JSON object: " + JSON; // "the JSON object: [object JSON]"

The object is converted into a string by calling its toSting function. You can call it manually to check:

Math.toString(); // "[object Math]"
JSON.toString(); // "[object JSON]"

Similarly, objects can also be converted into numbers through the value Of function. Of course, you can also customize the value Of function, as follows:

"J" + { toString: function() { return "S"; } }; // "JS"
2 * { valueOf: function() { return 3; } }; // 6

If an object also exists valueOf method and toString method, then the value Of method will always be called first, as follows:

var obj = {
    toString: function() {
        return "[object MyObject]";
    },
    valueOf: function() {
        return 17;
    }
};
"object: " + obj; // "object: 17"

Generally, try to make the values ​​represented by value Of and toString the same (although the types can be different).

The last type of forced type conversion is often called "truth operation", such as if, ||, &&, their operands are not necessarily Boolean. JavaScript will convert some non-Boolean values ​​into Boolean values ​​through simple conversion rules. Most values ​​will be converted to true, only a few are false, they are : false, 0, -0, "", NaN, null, undefined, because there are numbers, strings and objects The value is false, so it is not very safe to directly use true value conversion to determine whether the parameters of a function are passed in. For example, there is a function that can have optional parameters with default values, as follows:

function point(x, y) {
if (!x) {
    x = 320;
}
if (!y) {
    y = 240;
}
    return { x: x, y: y };
}

This function will ignore any parameters whose true value is false, including 0, -0;

point(0, 0); // { x: 320, y: 240 }

A more accurate way to detect undefined is to use the typeof operation:

function point(x, y) {
if (typeof x === "undefined") {
    x = 320;
}
if (typeof y === "undefined") {
    y = 240;
}
    return { x: x, y: y };
}

This way of writing can distinguish between 0 and undefined:

point(); // { x: 320, y: 240 }
point(0, 0); // { x: 0, y: 0 }

Another method is to use parameters to compare with undefined. As follows:

if (x === undefined) { ... }

Summary:

1. Type errors may be hidden by type conversion.

2. " " can represent both string concatenation and arithmetic addition, depending on its operands. If one of the operands is a string, then it is string concatenation.

3. The object converts itself into a number through the value Of method, and converts itself into a string through the toString method.

4. Objects with value Of methods should define a corresponding toString method to return equal numbers in string form.

5. When detecting some undefined variables, type Of or comparison with undefined should be used instead of true value operation directly.

Related recommendations:

JS implicit type conversion summary

How to use implicit conversion? Summarize the usage of implicit conversion examples

A brief introduction to implicit type conversion of JavaScript data types_javascript skills

The above is the detailed content of What is implicit type conversion? Introduction to js implicit type conversion. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool