[javascript] Casting to string in JavaScript

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?

This question is related to javascript jquery string

The answer is


There are differences, but they are probably not relevant to your question. For example, the toString prototype does not exist on undefined variables, but you can cast undefined to a string using the other two methods:

?var foo;

?var myString1 = String(foo); // "undefined" as a string

var myString2 = foo + ''; // "undefined" as a string

var myString3 = foo.toString(); // throws an exception

http://jsfiddle.net/f8YwA/


On this page you can test the performance of each method yourself :)

http://jsperf.com/cast-to-string/2

here, on all machines and browsers, ' "" + str ' is the fastest one, (String)str is the slowest


They behave the same but toString also provides a way to convert a number binary, octal, or hexadecimal strings:

Example:

var a = (50274).toString(16)  // "c462"
var b = (76).toString(8)      // "114"
var c = (7623).toString(36)   // "5vr"
var d = (100).toString(2)     // "1100100"

Real world example: I've got a log function that can be called with an arbitrary number of parameters: log("foo is {} and bar is {}", param1, param2). If a DEBUG flag is set to true, the brackets get replaced by the given parameters and the string is passed to console.log(msg). Parameters can and will be Strings, Numbers and whatever may be returned by JSON / AJAX calls, maybe even null.

  • arguments[i].toString() is not an option, because of possible null values (see Connell Watkins answer)
  • JSLint will complain about arguments[i] + "". This may or may not influence a decision on what to use. Some folks strictly adhere to JSLint.
  • In some browsers, concatenating empty strings is a little faster than using string function or string constructor (see JSPerf test in Sammys S. answer). In Opera 12 and Firefox 19, concatenating empty strings is rediculously faster (95% in Firefox 19) - or at least JSPerf says so.

In addition to all the above, one should note that, for a defined value v:

  • String(v) calls v.toString()
  • '' + v calls v.valueOf() prior to any other type cast

So we could do something like:

var mixin = {
  valueOf:  function () { return false },
  toString: function () { return 'true' }
};
mixin === false;  // false
mixin == false;    // true
'' + mixin;       // "false"
String(mixin)     // "true"

Tested in FF 34.0 and Node 0.10


According to this JSPerf test, they differ in speed. But unless you're going to use them in huge amounts, any of them should perform fine.

For completeness: As asawyer already mentioned, you can also use the .toString() method.


if you are ok with null, undefined, NaN, 0, and false all casting to '' then (s ? s+'' : '') is faster.

see http://jsperf.com/cast-to-string/8

note - there are significant differences across browsers at this time.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript