3. Data Types
3.1. Strings
A string may be a series of characters.
A string will represent data that contains text. The name string possibly derived from software
engineers who were reminded of a string of beads.
- You should wrap it in double quotes (""):
"Pull the string, and it will follow wherever you wish."; //string with double quotation
- Or you wrap it in single quotes (' '):
'Pull the string, and it won’t happen anywhere at all.';//string with single quotation
But what if you need to write a single quoted string, or quote a double quoted string? Won’t the string break that?
It will and to tackle that there are choices. You can either use the opposite type of quotes
safely or by using the \ escape method:
"I’m a web designer, not a technician!". // Using single quotes inside a string of double quotes
'"Do. Or do not. There is no try. " – Yoda'; // Using double quote in a single string of quotes
"They call it an \"escape\" character"; // using \ escape character
We can apply string to a variable. Let us use our previous example.
var greeting = "Oh hi, Pisay";
Strings can also be joined together in a process known as concatenation. Variables and literal strings can be joined together by using the (+) plus symbol, concat function, and template literals.
Using (+) plus symbol:
var greeting = "Oh hi, "+ "Pisay"+ "!"; // displays Oh hi, Pisay!
Example:
- <!DOCTYPE html>
- <html>
- <body>
- <h2>Variables of JavaScript</h2>
- <script>
- var message = "Oh hi, ";
- var firstName = "Pisay ";
- var bam = "!";
- var greeting = message + firstName + bam; /* displays Oh hi, Pisay! */
- document.write(greeting);
- </script>
- </body>
- </html>
The example above shows that all the strings are represented by variables, and how the
different values in the three variables are combined using the plus (+) sign. This method could be used
in a system like if you have signed into an app (like your email) and are greeted with your name.
Using concat function
The concat function connects the calling string together, with arguments given and a new
string return.
The concat function joins together the calling string with arguments given, and a new string
is returned. The significant thing is that the string does not change but returns a new one.
Example:
var greetings = "Hello";
document.write (greetings.concat("Pisay")); // Hello Pisay
Using Template literals
Instead of double or single quotes, template literals are enclosed by the backtick (` `) (grave
accent) character. Expressions inserted as part of the string surrounded by a dollar sign and curly
brackets, may be evaluated.
Example:
var name = "Pisay";
var myCondition = "good";
document.write(`Hello ${name}! You're looking ${myCondition} today!`); // returns Hello Pisay! You’re looking good today!