Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
The arithmetic operators -, *, /, and % all attempt to convert their arguments to numbers before being evaluated. The arithmetic + overrides both numeric addition and string concatenation.
Addition is left associative
Null does not cause a failure in arithmetic operations but is implicitly converted to 0
An undefined variable will be converted to a special floating point value NaN (not a number)
Unfortunately, even testing NaN values is extremely difficult. There are two reasons for this.
- JavaScript follows the troublesome requirement of the IEEE floating-point standard that NaN is not equal to itself
let x = NaN;
x === NaN; //false
Copy the code
Also, the standard library function isNaN is not very reliable because it comes with its own implicit coercion that converts its parameters to numbers before testing them (a more accurate name for the isNaN function might be coercesToNaN). If you already know that a value is a number, you can use the isNaN function to test if it is a NaN.
isNaN(NaN); //true
Copy the code
But other values that are definitely not NaN, but are cast to NaN, are indistinguishable using the isNaN method.
Console. log(isNaN(" Andy Lau ")); // true console.log(isNaN(undefined)); // true console.log(isNaN({})); // true console.log(isNaN({name: "r"})); // trueCopy the code
The last type of cast is sometimes called truthiness
Most JavaScript values are truth, that is, can be implicitly converted to true, and truth operations do not implicitly call any cast methods
There are seven false values in JavaScript: false, 0, -0, “, NaN, null, and undefined
All other values are true.
Because numbers and strings can be false, it is not perfectly safe to use the truth operation to check whether function arguments or object attributes are defined.
Objects can also be cast to their original values. The most common use is to convert to a string
console.log("the Math object" + Math); //the Math object[object Math]
console.log("the JSON object" + JSON); //the JSON object[object JSON]
Copy the code
An object is converted to a string by implicitly calling its own toString method.
console.log(Math.toString());
console.log(JSON.toString());
Copy the code
conclusion
- Type errors can be hidden by implicit casts.
- Whether the overloaded operator + performs addition or string concatenation depends on its argument type.
- An object is cast to a number using the Valueof method and to a string using the toString method.
- Objects with a Valueof method should implement the toString method, which returns a string representation of the number produced by the Valueof method.
- To test whether a value is undefined, use Typeof or compare with undefined instead of using a truth operation.