ES6 – String Primitive Datatype

ES6 – String Primitive Datatype

JavaScript can store data as form of string datatype. strings are a sequence of letters, numbers or special characters. Single or Double quotes are used to store string datatypes.

JavaScript String Datatype:

In JavaScript string almost anything can be put between quotes, this will make a string value out of it. However there are few cases that makes it difficult to use few characters for strings.

Newline in JavaScript String:

Adding newline to JavaScript string is one of the cases that makes some people pull their hair to figure it out. However, its straight forward and easy to add by using \ (backslash).

Backslash in JavaScript or almost any programming language has a special meaning. Whenever a backslash is used within quotes for strings datatype it indicates that the character after it has a special meaning. That is also called escaping characters. When an n character occurs after a backslash it’s interpreted as a newline. similarly a t after backslash means a tab character.


    

let str1 = “Hi there…” // Literal Syntax
let str2 = String(‘Hi there…’) // Function Syntax

 

let str3 = “Hi there… \n How is the day going?”
console.log(str3)
// Hi there…
// How is the day going?

Quotes in JavaScript String:

This is another scenario it makes it difficult to add quotes within a JavaScript sting datatype. This process is quite straight forward actually by determining which quotes to include within string.

If we need to have single quotes within string then we need to wrap the single quotes with double quotes for that string.


    

let str1 = “Hi there ‘John Doe’, Lets learn JS today.”
console.log(str1)
// Hi there ‘John Doe’, Lets learn JS today.

 

let str2 = ‘Hi there “John Doe”, Lets learn JS today.’
console.log(str2)
// Hi there “John Doe”, Lets learn JS today.

Concatenating JavaScript Strings:

The word concatenating in programing is generally referred as combining two or more strings into a single string. In cases where JavaScript string datatypes are retrieved from database or used somewhere else within the program concatenating is used to combined those strings into a single string.

In JavaScript the + (plus) sign is used to concatenate strings together.


    

let str1 = “Hi ” + “there ” + “…”
console.log(str1)
// Hi there…

 

let str2 = “Hi”
let str3 = “there”
let str4 = str2 + str3
console.log(str4)
// Hi there

Also to concatenate JavaScript strings in ES6 often Template Literals are used. Template Literals not only concatenate string but more powerful to run JavaScript expression within a string.