阿里云主机折上折
  • 微信号
Current Site:Index > Type checking and conversion

Type checking and conversion

Author:Chuan Chen 阅读数:52895人阅读 分类: JavaScript

Type Checking

JavaScript is a dynamically typed language where variable types are determined at runtime. Type checking is an essential means to ensure code robustness. The typeof operator is the most basic way to perform type checking:

typeof 42 // "number"
typeof "text" // "string"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (historical legacy)
typeof {} // "object"
typeof [] // "object"
typeof function(){} // "function"

The instanceof operator checks whether the constructor's prototype property appears in the object's prototype chain:

[] instanceof Array // true
new Date() instanceof Date // true
"text" instanceof String // false (primitive types are not objects)

Object.prototype.toString.call() provides more precise identification of built-in types:

Object.prototype.toString.call([]) // "[object Array]"
Object.prototype.toString.call(new Date()) // "[object Date]"
Object.prototype.toString.call(null) // "[object Null]"

Type Conversion

Type conversion in JavaScript can be explicit or implicit. Explicit conversion is achieved by calling built-in functions:

Number("123") // 123
String(123) // "123"
Boolean(0) // false

Implicit conversion occurs during operator operations or comparisons:

"5" + 2 // "52" (string concatenation)
"5" - 2 // 3 (numeric operation)
"5" == 5 // true (loose equality)
"5" === 5 // false (strict equality)

Numeric Conversion

parseInt and parseFloat are specifically for converting strings to numbers:

parseInt("10px") // 10 (ignores non-numeric suffixes)
parseFloat("12.5em") // 12.5
parseInt("010") // 10 (ES5+ no longer interprets as octal)

Number() conversion is stricter:

Number("123abc") // NaN
Number("") // 0
Number(null) // 0
Number(undefined) // NaN

Boolean Conversion

All values have explicit truthiness in boolean contexts:

Boolean("") // false
Boolean(0) // false
Boolean(null) // false
Boolean(undefined) // false
Boolean(NaN) // false
Boolean([]) // true (all objects are truthy)
Boolean({}) // true

Object-to-Primitive Conversion

Object-to-primitive conversion involves the valueOf() and toString() methods:

let obj = {
  valueOf() { return 1 },
  toString() { return "2" }
};
obj + 1 // 2 (prefers valueOf)
String(obj) // "2" (prefers toString)

Arrays exhibit special conversion behavior:

[] + [] // "" (empty string)
[] + {} // "[object Object]"
{} + [] // 0 (parsed as a code block)

Strict Type Checking

Modern JavaScript recommends using strict equality (===) and strict inequality (!==):

0 == false // true
0 === false // false
null == undefined // true
null === undefined // false

Object.is() provides more precise comparisons:

Object.is(0, -0) // false
Object.is(NaN, NaN) // true

Type Guards

TypeScript's type guards narrow the scope of variable types:

function isString(test: any): test is string {
  return typeof test === "string";
}

function example(foo: any) {
  if (isString(foo)) {
    console.log(foo.length); // Here, foo is recognized as a string
  }
}

Safe Conversion Patterns

Defensive programming suggests using safe conversion patterns:

// Safely convert to number
function toNumber(val) {
  const num = Number(val);
  return isNaN(num) ? 0 : num;
}

// Safely convert to integer
function toInteger(val) {
  return Math.trunc(toNumber(val));
}

JSON Serialization and Parsing

JSON methods involve type conversion:

JSON.stringify({a: undefined, b: function(){}, c: Symbol(""), d: BigInt(1)})
// "{}" (ignores undefined, functions, Symbols, and BigInt)

JSON.parse('{"a":1,"b":"text"}') // {a:1, b:"text"}

Type Conversion Pitfalls

Common type conversion pitfalls to be aware of:

+"123" // 123 (unary plus conversion)
+"" // 0
+"abc" // NaN

!!"false" // true (non-empty strings are truthy)
!!0 // false

[] == ![] // true (confusing conversion)

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:代码缩进与格式

下一篇:条件语句规范

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.