Casting to string in JavaScript

javascript, string

Solution

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.

Problem

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. I would like to know if there are any differences between them: ``` value.toString() String(value) value + "" ``` DEMO They all produce the same output, but does one of them better than the others? I would say the `+ ""` has an advantage that it saves some characters, but that's not that big advantage, anything else?

Original source