String(x) and x.toString()

There are some important differences between String(x)and x.toString()in JavaScript.

String(x)- Type Conversion Function

String()​​ is a function that converts any value to a string:

String(123)           // "123"
String(true)          // "true"
String(null)          // "null"
String(undefined)     // "undefined"
String({})            // "[object Object]"
String([1, 2, 3])     // "1,2,3"

x.toString()- Object Method

toString()​​ is a method that objects call on themselves:

(123).toString()      // "123"
true.toString()       // "true"
[1, 2, 3].toString() // "1,2,3"

Key Differences

1. ​Handling nulland undefined

// String() works fine
String(null)          // "null"
String(undefined)     // "undefined"

// toString() throws errors
null.toString()       // TypeError: Cannot read properties of null
undefined.toString()  // TypeError: Cannot read properties of undefined

2. ​Primitive Values

// Both work for primitives
String(42)            // "42"
(42).toString()       // "42"

// But need careful syntax for numbers
42.toString()         // SyntaxError - dot is part of decimal
(42).toString()       // "42" - correct
42..toString()        // "42" - also works (weird but valid)

3. ​Custom Objects

class Person {
    constructor(name) {
        this.name = name;
    }
    
    toString() {
        return `Person: ${this.name}`;
    }
}

const john = new Person('John');

String(john)          // "Person: John" - uses toString() if available
john.toString()       // "Person: John"

When to Use Which?

Use String(x)when:​

  • Value might be nullor undefined

  • You want safe, predictable conversion

  • Working with unknown/variable types

function safeToString(value) {
    return String(value); // Always works
}

Use x.toString()when:​

  • You know the value is not null/undefined

  • You want to use custom toString()methods

  • Working with specific object types

// Safe pattern with optional chaining
value?.toString()     // Returns undefined instead of throwing error

Advanced Differences

Radix Parameter (Number to String)​

// Only toString() supports radix
(10).toString(2)      // "1010" - binary
(255).toString(16)    // "ff" - hexadecimal

String(10)            // "10" - no radix support

Symbol Conversion

const sym = Symbol('test');

String(sym)           // "Symbol(test)" - works
sym.toString()        // "Symbol(test)" - also works

// But template literals
`${sym}`              // TypeError: Cannot convert a Symbol value to a string

Summary Table

Feature

String(x)

x.toString()

null/undefined

✅ Works

❌ Throws error

Primitive values

✅ Works

✅ Works (careful syntax)

Custom objects

Uses object's toString()

Uses object's toString()

Radix parameter

❌ No support

✅ For numbers

Safety

✅ Very safe

❌ Less safe

Best Practice

Prefer String(x)for general use​ - it's safer and more predictable. Use x.toString()when you specifically need its features (like radix) or are certain about the value type.

// Good for most cases
const str = String(someVariable);

// When you need specific functionality
const binary = number.toString(2);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值