Interesting JavaScript implicit type conversions

Source: Internet
Author: User
Tags arithmetic operators

The data type of JavaScript is very weak (otherwise it will not be called a weakly typed language)! When using arithmetic operators, the data types on either side of the operator can be arbitrary, for example, a string can be added to a number. It is possible to perform operations between different data types because the JavaScript engine silently casts them implicitly type before the operation, as follows: the addition of numeric types and Boolean types.

true // 4

The result is a numeric type! If it is in the C or Java environment, the above operation will definitely cause error due to inconsistent data types on both sides of the operator! However, in JavaScript, there are only a few cases where the error type can cause an error, such as calling a non-function, or reading a null or undefined property , as follows:

// Error:not a function NULL // Error:cannot Read Property ' x ' of NULL

In most cases, JavaScript does not go wrong, but it automatically makes the appropriate type conversions. For example-, *,/, and% arithmetic operators will convert the operand to a number, but the "+" number is a little different, in some cases, it is the arithmetic plus, in some cases, is the string connection symbol, the concrete to see its operand , as follows:

// 5 // "Hello World"

But what happens if the string and the number are added together? JavaScript automatically converts numbers into characters, regardless of whether the number is before or before the string , as follows:

// "All" // "All"

String and number addition result is string, string and number add result is string, string and number add result is string , important thing say three times!!!!!!

In addition, it should be noted that the "+" operation direction is from left to right, as follows:
// " the"

This is equivalent to the following:

// " the"

In contrast, the following results are not the same:

// "123"

However, implicit type conversions sometimes hide some errors, for example, null is converted to 0,undefined and is converted to Nan . It is important to note that Nan and Nan are unequal (this is determined by the precision of the floating-point numbers), as follows:

var x =//  false

Although , JavaScript provides isnan to detect whether a value is Nan, but this is also less precise because, before invoking the isNaN function, there is an implicit conversion process, which converts values that are not nan to Nan. , as follows:

// true // true // true // true

The above code, we use isNaN to test, found the string, undefined, even the object, the results are returned true!!! But, we can not say that they are Nan, right? In a word, the conclusion is: isNaN Detection nan is not reliable!!!

var a =//  truevar b = "foo"//  falsevar C =//  falsevar d =//  falsevar e = {valueOf: ' foo '//  false

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

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

Ok,nan detection method is so simple, we continue to discuss the object of the implicit conversion!

The most common way to convert an object to a primitive value is to convert it to a string, as follows:

// "The Math object: [Object Math]" // "The JSON object: [Object JSON]"

The object converted to a string is called by his tosting function, and you can call it manually to detect it:

// "[Object Math]" // "[Object JSON]"

Similarly, the object can be converted to a number, he is through the valueof function, of course, you can also customize this valueof function, as follows:

function return // "JS" function return // 6

If an object has both the ValueOf method and the ToString method, then the ValueOf method will always be called First, as follows:

var obj = {    function() {        return "[Object MyObject]";    },     function () {        return ;    }; // "Object:17"

However, in most cases, this is not what we want, generally, as much as possible to make valueof and ToString represent the same value (although the type can be different).  

The last type of coercion, which we often call "truth operations," such as, if, | |, &&amp, is that their operands are not necessarily boolean-like amounts. JavaScript converts values of non-Boolean types to Boolean by simple conversion rules. Most of the values are converted to true, and only a few are false, and they are :false, 0, -0, "", NaN, null, Undefined , because there are numbers and strings, and the value of the object is false, it is not very safe to judge whether a function's arguments are passed in directly with the truth conversion. For example, there is a function that can have a default worth of optional parameters, as follows:
function Point (x, y) {if (!  x) {    = +;} if (! y) {    = +;}     return {x:x, y:y};}

This function ignores any true value for false parameters, including 0,-0;

// {x:320, y:240}

A more accurate way to detect undefined is to operate with typeof:

function Point (x, y) {if (typeof x = = = "undefined") {    = +;} if (typeof y = = = "undefined") {    = +;}     return {x:x, y:y};}

This notation can be divided into 0 and undefined:

// {x:320, y:240} // {x:0, y:0}

Another method is to use parameters to compare with undefined , as follows:

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

Summarize:

1. Type errors may be hidden by type conversions. 2. "+" can represent both a string connection and an arithmetic addition, depending on its operand, if one is a string, then the string is concatenated. 3. The object converts itself into a number by means of the valueof method, and converts itself into a string by the ToString method. 4. An object with the ValueOf method should define a corresponding tostring method that returns the string form of an equal number. 5. When testing some undefined variables, you should use typeof or compare with undefined, rather than using the true truth operation directly.

Interesting JavaScript implicit type conversions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.