Casting to string in JavaScript

前端 未结 8 1724
轻奢々
轻奢々 2020-12-04 07:59

I found three ways to cast a variable to String in JavaScript.
I searched for those three options in the jQuery source code, and they are all in use

8条回答
  •  渐次进展
    2020-12-04 08:37

    They do behave differently when the value is null.

    • null.toString() throws an error - Cannot call method 'toString' of null
    • String(null) returns - "null"
    • null + "" also returns - "null"

    Very similar behaviour happens if value is undefined (see jbabey's answer).

    Other than that, there is a negligible performance difference, which, unless you're using them in huge loops, isn't worth worrying about.

提交回复
热议问题