JavaScript Strings in Detail

July 27, 2019


String is one of the JavaScript’s primitive data type.
Strings in JavaScript is a sequential arrangement of Unicode characters enclosed inside “ ” or ‘ ’. Both are valid ways to define a string.
In JavaScript, a valid string can be:
console.log("Hello Developers");
console.log('Hello Developers');
console.log('Hello \n Developers');
All the above statements will log valid strings in the console.

Do you know?

JS primitive data types like stringnumber and boolean are having their corresponding wrapper objects which also can be used to define their corresponding values.

More ways to create a String Literal

We can also create a string using their wrapper objects like:
var str1 = "Hello";
console.log(str1);Output:
> Hellovar str2 = String("Hello");
console.log(str2);Output:
> Hello
At this point, (str1 === str2) will evaluate to true.
Not only this, we can provide a non string value to the String wrapper object and the value will be converted to String.
String(20) will create a string “20” even though we pass a number to it.

Using the new keyword with wrapper object

JavaScript has a new keyword which we can use against a wrapper object to create Strings,
var str1 = String(“Hi”);  // returns string
var str2 = new String(“Hi”);  // returns an object
Using the new keyword works differently and returns an object instead.
The values of str1 and str2 will be

Notice the object we get instead of getting a string for str2
If we try to compare the variables str1 and str2 we will get
(str1 === str2) // returns false

Getting values from String Objects

Since, str2 is an object and we cannot directly check its equality with str1. To check for the equality of str1 and str2, we need to use a String wrapper objects’s function named valueOf().
str1 === str2.valueOf() // returns true

One more interesting thing to know

var str1 = "Hi";
console.log(str1); // logs "Hi"
console.log(str1.valueOf()); // logs "Hi"
Did you noticed, we called valueOf() on the str1 which we assigned a primitive value.
Can you identify from where we get the valueOf() function although it was a primitive value assigned to str1?


Reason

For statements of assigning primitive values to a variable like
var str1 = "Hi";
JavaScript will internally create the variable using
String("Hi")
As a result, we are having all the available functions of the String wrapper object.

You Might Also Like

0 comments

Follow by Email