Home > Web Front-end > JS Tutorial > Automatic Type Conversion In The Real World

Automatic Type Conversion In The Real World

Lisa Kudrow
Release: 2025-02-24 08:30:11
Original
326 people have browsed it

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.
  • typeofWhile 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

condition:
if (foo) {
}
Copy after login
Copy after login
Copy after login

The second expression is a variable assignment with optional values:
var x = foo || bar;
Copy after login
Copy after login
Copy after login
Copy after login

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

.

fooBut what if they are not simple boolean values ​​- what if undefined is an object, a string, or foo? What if bar and

are different data types? To understand how these expressions will be computed, we need to understand how JavaScript automatically converts between data types.

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

statements. <🎜>

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) {
}
Copy after login
Copy after login
Copy after login

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;
Copy after login
Copy after login
Copy after login
Copy after login

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 {
  // 元素不存在
}
Copy after login
Copy after login

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) {
    ...
  }
}
Copy after login
Copy after login
Logical operators do not return

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) {
}
Copy after login
Copy after login
Copy after login

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;
Copy after login
Copy after login
Copy after login
Copy after login

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 {
  // 元素不存在
}
Copy after login
Copy after login

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) {
    ...
  }
}
Copy after login
Copy after login

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") {
    ...
  }
}
Copy after login

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;
Copy after login
Copy after login
Copy after login
Copy after login

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!

Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template