1
0

More than 1 year has passed since last update.

String()とtoString()の違い

Last updated at Posted at 2023-01-02

はじめに

値をString型に変換する、String()とtoString()の違いを把握していなかったので調べた。
結論としては、String()にnullやundefinedを指定すると、"null"、"undefined"が文字列として返ってくる。これを期待値としない場合は、toString()を使うほうがいい。

String()とtoString()の違い

toString()で2ヶ所エラーが出たケースがあった。
TODOとしている箇所は、利用するケースがあるのか含め後日調べて埋める予定。

型\処理 String() toString()
Boolean console.log(String(true));
// "true"
console.log(true.toString());
// "true"
null console.log(String(null));
//"null"
console.log((null).toString());
// ❌Cannot read properties of null (reading 'toString')
undefined console.log(String(undefined));
// "undefined"
console.log((undefined).toString());
// ❌Cannot read properties of undefined (reading 'toString')
Number console.log(String(100));
// "100"
console.log((100).toString());
// "100"
BigInt TODO TODO
String console.log(String("string"));
// "string"
console.log(("string").toString());
// "string"
Symbol TODO TODO
Object TODO TODO

String()

コンストラクターではなく関数として呼び出されたときは型変換を行う

new String("text");と書いたときは、コンストラクタを生成しているが、String("text");new なしで書いた場合、型変換を行う。

String()とtoString()の違いで示した通り、nullやundefinedを指定すると、"null"、"undefined"が文字列として返ってくる。

toString()

返り値は、呼び出したオブジェクトを表す文字列
String()とtoString()の違いで示した通り、nullやundefinedを指定すると、
Cannot read properties of null (reading 'toString')などのエラーが返ってくる。

参考文献

おわりに

値をString型に変換する、String()とtoString()の違いを調べた、ちょっとした違いかもしれないが、知っておいた方がいい情報だと思った。

1
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0