DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • JavaScript Type Conversion and Coercion
  • Adding Two Hours in DataWeave: Mule 4
  • What's New in Mule 4.4 - With Example
  • From Zero to Meme Hero: How I Built an AI-Powered Meme Generator in React

Trending

  • A Guide to Container Runtimes
  • Segmentation Violation and How Rust Helps Overcome It
  • Building Scalable and Resilient Data Pipelines With Apache Airflow
  • Enhancing Avro With Semantic Metadata Using Logical Types
  1. DZone
  2. Coding
  3. JavaScript
  4. Converting a Value to String in JavaScript

Converting a Value to String in JavaScript

By 
Axel Rauschmayer user avatar
Axel Rauschmayer
·
Mar. 30, 12 · Interview
Likes (2)
Comment
Save
Tweet
Share
31.3K Views

Join the DZone community and get the full member experience.

Join For Free

In JavaScript, there are three main ways in which any value can be converted to a string. This blog post explains each way, along with its advantages and disadvantages.

Three approaches for converting to string

The three approaches for converting to string are:

  1. value.toString()
  2. "" + value
  3. String(value)

The problem with approach #1 is that it doesn’t work if the value is null or undefined. That leaves us with approaches #2 and #3, which are basically equivalent.

  • ""+value: The plus operator is fine for converting a value when it is surrounded by non-empty strings. As a way for converting a value to string, I find it less descriptive of one’s intentions. But that is a matter of taste, some people prefer this approach to String(value).
  • String(value): This approach is nicely explicit: Apply the function String() to value. The only problem is that this function call will confuse some people, especially those coming from Java, because String is also a constructor. However, function and constructor produce completely different results:
        > String("abc") === new String("abc")
        false
    
        > typeof String("abc")
        'string'
        > String("abc") instanceof String
        false
    
        > typeof new String("abc")
        'object'
        > new String("abc") instanceof String
        true
    

    The function produces, as promised, a string (a primitive [1]). The constructor produces an instance of the type String (an object). The latter is hardly ever useful in JavaScript, which is why you can usually forget about String as a constructor and concentrate on its role as converting to string.

A minor difference between ""+value and String(value)

Until now you have heard that + and String() convert their “argument” to string. But how do they actually do that? It turns out that they do it in slightly different ways, but usually arrive at the same result.

Converting primitives to string

Both approaches use the internal ToString() operation to convert primitives to string. “Internal” means: a function specified by the ECMAScript 5.1 (§9.8) that isn’t accessible to the language itself. The following table explains how ToString() operates on primitives.

 

ArgumentResult
undefined"undefined"
null"null"
boolean valueeither "true" or "false"
number valuethe number as a string, e.g. "1.765"
string valueno conversion necessary

Converting objects to string

Both approaches first convert an object to a primitive, before converting that primitive to string. However, + uses the internal ToNumber() operator (except for dates [2]), while String() uses ToString().
  • ToNumber(): To convert an object obj to a primitive, invoke obj.valueOf(). If the result is primitive, return that result. Otherwise, invoke obj.toString(). If the result is primitive, return that result. Otherwise, throw a TypeError.
  • ToString(): Works the same, but invokes obj.toString() before obj.valueOf().
With the following object, you can observe the difference:
    var obj = {
        valueOf: function () {
            console.log("valueOf");
            return {}; // not a primitive, keep going
        },
        toString: function () {
            console.log("toString");
            return {}; // not a primitive, keep going
        }
    };  

Interaction:

    > "" + obj
    valueOf
    toString
    TypeError: Cannot convert object to primitive value

    > String(obj)
    toString
    valueOf
    TypeError: Cannot convert object to primitive value

Most objects use the default implementation of valueOf() which returns this for objects. Hence, that method will always be skipped by ToNumber().

    > var x = {}
    > x.valueOf() === x
    true

Instances of Boolean, Number, and String wrap primitives and valueOf returns the wrapped primitive. But that still means that the final result will be the same as for toString(), even though it will have been produced in a different manner.

    > var n = new Number(756)
    > n.valueOf() === n
    false
    > n.valueOf() === 756
    true

Conclusion

Which of the three approaches for converting to string should you choose? value.toString() can be OK, if you are sure that value will never be null or undefined. Otherwise, ""+value and String(value) are mostly equivalent. Which one people prefer is a matter of taste. I find String(value) more explicit.

Related posts

  1. JavaScript values: not everything is an object [primitives versus objects]
  2. What is {} + {} in JavaScript? [explains how the + operator works]
  3. String concatenation in JavaScript [how to best concatenate many strings]
Strings Data Types JavaScript

Published at DZone with permission of Axel Rauschmayer, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • JavaScript Type Conversion and Coercion
  • Adding Two Hours in DataWeave: Mule 4
  • What's New in Mule 4.4 - With Example
  • From Zero to Meme Hero: How I Built an AI-Powered Meme Generator in React

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: