"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > string vs String

string vs String

Published on 2024-11-08
Browse:672

string vs String

string

Lowercase string is a primitive data type in JavaScript.

Strings created with this type are not objects, but JavaScript automatically wraps them with a String object (this is called "boxing").

let imAString = "hello";
console.log(typeof imAString); // "string"

String

Uppercase String is a constructor function that creates String objects, an object wrapper around a string primitive.

When you use the String constructor with new, you get a String object rather than a primitive string

String objects are not necessary unless you need to use them as objects explicitly.

let imAStringObject = new String("hello");
console.log(typeof imAStringObject); // "object"

Differences

string String
type primitive Object
Memory lightweight and stored by value heavyweight, stored as object
methods get converted to String object temporarily has access to String methods like .charAt()
Comparing Values by values by reference

When to use string/String?

Use string (primitive) in almost all cases. It is more efficient, simpler, and JavaScript automatically provides methods when needed.

Use String (object) only when you specifically need an object with additional properties or when you want to use instanceof checks, though this is rare in practice.


That's it! Thank you for reading this far. Till next time!

Release Statement This article is reproduced at: https://dev.to/theteabagcoder/string-vs-string-24p?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3