Strings in JavaScript

 Strings in JavaScript





The string is one of JavaScript’s primitive data types.

Strings in JavaScript are 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.

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:

> Hello

var 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 a Wrapper Object

JavaScript has a new keyword that 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

As str2 is an object, we cannot directly check its equality with str1. To check for the equality of str1 and str2, we need to use a String wrapper object’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 notice, we called valueOf() on the str1 and we assigned it a primitive value.

Can you identify from where we get the valueOf() function, despite it being 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 have all the available functions of the String wrapper object.


 

Comments