Automatic Type Conversion In The Real World
Core points
- JavaScript's automatic type conversion is both an advantage and a disadvantage in different situations. As a core function, it converts data to an expected type when an operator or statement expects a specific data type.
- According to the conversion result, JavaScript values are called "true values" or "false values". There are six false values:
false
,undefined
,null
,0
,""
,NaN
(empty string) and (non-number). All other values are considered true. - How type conversions affect the evaluation must be carefully considered to avoid pitfalls. For example, when defining default values for optional parameters, the truth of known data must be ensured to prevent failure.
-
typeof
While explicit testing using is always safe, using automatic type conversion is beneficial for file size considerations, as smaller files load faster and use less bandwidth. However, understanding how programming languages handle type conversions is crucial to avoid unexpected results.
There are some expressions that are common in JavaScript, but some programming purists will tell you that they are never a good idea. What these expressions have in common is that they rely on automatic type conversion—the core functionality of JavaScript, which is both an advantage and a disadvantage depending on the situation and your point of view.
So, in this article, I want to pay special attention to these two expressions and consider in which cases they are good ideas and which are not good ideas.
if()
The first expression is a simple
if (foo) { }
The second expression is a variable assignment with optional values:
var x = foo || bar;
foo
If the bar
and foo
in both examples are booleans, the expression is simple: if foo
is true, the first condition passes; if foo
is true, then The second expression assigns x
to bar
, otherwise assigns x
to
foo
But what if they are not simple boolean values - what if undefined
is an object, a string, or foo
? What if bar
and
Automatic type conversion
if()
JavaScript is a "loosely typed" language, which means that whenever an operator or statement expects a specific data type, JavaScript automatically converts data to that type. The while()
statement in the first example expects a boolean value, so anything defined in the parentheses will be converted to a boolean value. The same is true for the do...while()
and
According to the results of such conversions (i.e. true or false), JavaScript values are often referred to as "true" or "false values". The easiest way to understand it is: unless the value is known to be a false value, the value is the true value; in fact, there are only six false values:
false
(Of course!)undefined
null
0
(number zero)""
(empty string)NaN
(non-number)
Notable exceptions are "0" (string zero) and all types of objects - they are true values - this includes all native constructors, which means new Boolean(false)
calculation results True! (A little confusing, but in practice you never need to create native values like that.)
Note: Comparing two false values does not always produce the results you might expect, such as (null != false
), even if both are false values. There are some rather complex algorithms that determine how equality assessments work, and discussing them is beyond the scope of this article. But if you are interested in details, you can check out the abstract equality comparison algorithm in ECMAScript 5.1.
Conditional shortcut
The if()
example I showed you at the beginning converts its expression to a boolean value, since the object is always evaluated to true and null
is evaluated to false, so we can use such a condition to test the DOM element's Existence:
if (foo) { }
This always works reliably when processing DOM elements, because the DOM specification requires that elements that do not exist return null
.
However, other situations are not so clear, such as this example:
var x = foo || bar;
Such conditions are often used to indicate "If the foo parameter is defined" , but there are several situations that can cause failure - i.e., foo
is a false value. So, for example, if it is a Boolean value false
or an empty string, the conditional code is not executed even if foo
is already defined.
What we want is this:
var element = document.getElementById("whatever"); if (element) { // 元素存在 } else { // 元素不存在 }
The data type of the undefined parameters (and other variables) is "undefined
". Therefore, we can use the typeof
comparator to test the data type of the parameter, and then if foo
is fully defined, the condition will always pass. Of course, the if()
expression is still calculating the boolean value, but the boolean value it computes is the typeof
result of the expression.
Assignment shortcut
The second example I showed you at the beginning uses a logical operator to determine which of the two values should be assigned to the variable:
function doStuff(foo) { if (foo) { ... } }
Boolean values, but they do still expect Boolean values, so the conversion and calculations will happen internally. If is evaluated to true, the value of is returned, otherwise the value of foo
is returned. This is very useful. foo
This expression is usually seen in event handlers and is used to define event parameters based on supported models:
if (foo) { }
Therefore, e
is calculated as a Boolean value, which is true (event object) if the event parameter model is supported, otherwise a false value (undefined
); if it is true, return e
, otherwise return window.event
.
Expressions of the same type are also often used to assign event attributes, finding supported attributes by evaluating each possibility:
var x = foo || bar;
Therefore, each of these references is evaluated in turn (from left to right) and the first calculation is true will be returned. The first case handles the standard model, the second case is for Internet Explorer, and the third case is for Internet Explorer, when an event may be triggered on a window object (without the srcElement
property).
However, this expression is also prone to failure, without knowing the truth of the data. For example, another common use case is to define default values for optional parameters, but this is not good:
var element = document.getElementById("whatever"); if (element) { // 元素存在 } else { // 元素不存在 }
Now, if you are sure foo
is always or undefined
, and if the empty string should be treated as undefined
, the expression is safe. But if it is not, it needs to be redefined as more precise content, for example:
function doStuff(foo) { if (foo) { ... } }
By testing the type against "string" we can handle a variety of cases - foo
undefined cases, and cases where it is wrongly defined as non-string values. In this case we also allow empty strings as valid input, but if we want to exclude empty strings, we have to add a second condition:
function doStuff(foo) { if (typeof foo != "undefined") { ... } }
There are some other surprisingly subtle situations that can cause problems. For example, we might have a date function that creates a unix timestamp unless the input timestamp is optionally defined:
var x = foo || bar;
If the input is 0, it will fail - because zero is a false value, but it is also a valid timestamp.
General Principles
The general lesson learned from all of this is simple – think about how type conversions will affect the evaluation and be careful not to fall into the traps we encounter. With proper attention and attention, you can still utilize automatic type conversion to shorten conditions and logical expressions where appropriate.
But this does raise the question - if we know that using typeof
is always safe, while relying on automatic type conversion is sometimes not safe - then why not always is clear? Of course, if the reason for preferring a shorter grammar is simply because it types faster, then this is a lazy and sloppy reason.
But the truth is that JavaScript is usually run over a public network, in which case file size is important. Smaller files load faster and use less bandwidth, and small syntax shortcuts can indeed accumulate.
Using shorter expressions is not an optimization itself, it is just a programming style, which makes full use of language features.
(The FAQ section in the original text is omitted here because the content of this part is weakly related to the topic of the article and is longer, so it is not suitable for retaining in pseudo-original works.)
The above is the detailed content of Automatic Type Conversion In The Real World. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...
