상세 컨텐츠

본문 제목

[JavaScript] 형변환 시 String() 과 toString()의 차이점

JavaScript

by spring92 2021. 8. 18. 19:23

본문

숫자를 문자열로 형변환 시 사용하는 String()과 toString()의 차이점

// 숫자를 형변환
const number = 10
String(number) // 10
number.toString() // 10
number.toString(2) // 1010, 괄호 안에 2~36사이의 정수가 들어가며 해당 진법으로 바꿔준다. 예시는 2진법. 

// 객체를 형변환
const obj = { name: "charlie" }
String(obj) // [object Object]
obj.toString() // [object Object]

// 배열을 형변환
const arr = [1, 2, 3, 4]
String(arr) // 1,2,3,4
arr.toString() // 1,2,3,4

// null을 형변환
const nl = null
String(nl) // null
nl.toString() // TypeError: Cannot read property 'toString' of null

// undefined를 형변환
const udf = undefined
String(udf) // undefined
udf.toString() // TypeError: Cannot read property 'toString' of undefined

String이나 toString이나 같은 기능을 하는 것으로 보이며,

차이점이 있다면 toString은 객체의 메서드를 호출하는 거라 null과 undefined에서는 사용하지 못하는 것 같다.

관련글 더보기