Photo by Andrew Neel on Unsplash
Frontend: Day 2 - Strings continued, Booleans and == || === in JavaScript
Indexing
To access an individual character, you can use the character's location in the string, called its index. Just put the index of the character inside square brackets (starting with [0] as the first character) immediately after the string.
Ex-1
"Divya"[0];
Returns: "D"
Escaping strings
There are some cases where you might want to create a string that contains more than just numbers and letters. For example, what if you want to use quotes in a string?
Ex-2
"Hey, "please talk to me.""
Uncaught SyntaxError: Unexpected identifier
- If you try to use quotes within a string, you will receive a SyntaxError like the one above.
- Because you need to use quotes to denote the beginning and end of strings, the JavaScript engine misinterprets the meaning of your string by thinking > "Hey, " is the string. Then, it sees the remaining
please talk to me."" and returns a SyntaxError.
- If you want to use quotes inside a string, and have JavaScript not misunderstand your intentions, you’ll need a different way to write quotes. Thankfully,JavaScript has a way to do this using the backslash character( \ ).
Escaping characters
- In JavaScript, you use the backslash to escape other characters.
- Escaping a character tells JavaScript to ignore the character's special meaning and just use the literal value of the character. This is helpful for characters that have special meanings like in our previous example with quotes "…".
- Because quotes are used to signify the beginning and end of a string, you can use the backslash character to escape the quotes in order to access the literal quote character.
Ex-3
"The man whispered, \"please speak to me.\""
Returns: The man whispered, "please speak to me."
This guarantees that the JavaScript engine doesn’t misinterpret the string and result in an error. By using the backslash to escape characters, the JavaScript engine can understand the meaning of your strings.
Special characters
Quotes aren’t the only special characters that need to be escaped, there’s actually quite a few. However, to keep it simple, here’s a list of some common special characters in JavaScript.
Code Character
\\ \ (backslash)
\" '' (double quote)
\' ' (single quote)
\n newline
\t tab
The last two characters listed in the table, newline \n and tab \t, are unique because they add additional whitespace to your Strings. A newline character will add a line break and a tab character will advance your line to the next tab stop.
Ex-4
"Up up\n\tdown down"
Returns:
Up up
down down
Ex-5
"The file located at "C:\\Desktop\My Documents\Roster\names.txt" contains the names on the roster."
Returns:
"The file located at \"C:\\\\Desktop\\My Documents\\Roster\\names.txt\" contains the names on the roster."
Comparing strings
Another way to work with strings is by comparing them. You've seen the comparison operators == and != when you compared numbers for equality. You can also use them with strings!
Ex-6
"No" == "no"
Returns: false
A. Case-sensitive
When you compare strings, case matters. While both string use the same letters (and those letters appear in the same order), the first letter in the first string is a capital N while the first letter in the second string is a lowercase n.
Ex-7
'N' != 'n'
Returns: true
B. Internal Working
- In Javascript, strings are compared character-by-character in alphabetical order. Each character has a specific numeric value, coming from ASCII value of Printable characters. For example, the character 'A' has a value 65, and 'a' has a value 97.
- If you want to know the ASCII value of a particular character, you can try running the code below:
Ex-8
// Pick a string. Your string can have any number of characters.
var my_string = "v";
// Calculate the ASCII value of the first character, i.e. the character at the position 0.
var ASCII_value = my_string.charCodeAt(0);
// Let us print
console.log(ASCII_value);
If you wish to print ASCII values of all the characters in your string, use Loops. Just for reference, here is how you can use a loop to print the ASCII value of all characters in a string.
Ex-9
var my_string = "Divyanshi";
// Iterate using a Loop
for (var i = 0; i < my_string.length; i++) {
console.log(my_string.charCodeAt(i));
}
The ASCII values of [A-Z] fall in the range [65-90], whereas, the ASCII values of [a-z] fall in the range [97-122]. Therefore, when we compare strings, the comparison happens character-by-character for the ASCII values. When checking if a string is "greater than" or "less than" another string, JavaScript compares individual characters using a numerical value. Each character is assigned a numerical value that essentially corresponds to the character's location in an ASCII table: ascii-code.com
Booleans
Whenever you compare data, the result of the comparison will always be a value of true or false.This is important because our third primitive data type Booleans, only include these two values. Just think yes or no, true or false, ones or zeroes. These all values represent the same thing
Ex-10
var studentName = "Jaiesh";
var haveEnrolledInCourse = true;
var haveCompletedTheCourse = false;
A boolean variable is mainly essential in evaluating the outcome of conditionals (comparisons). The result of a comparison is always a boolean variable.
Ex-11
var a = 20;
var b = 30;
// a comparison - we will study this in detail in upcoming lesson
if (a>b) // The outcome of a>b will be a boolean
console.log("Variable `a` has higher value"); // if a>b is true
else
console.log("Variable `b` has higher value"); // if a>b is false
In general cases (regular equality check), a true corresponds to number 1, whereas false represents a number 0.
Null & Undefined
- Null is a data type that has no value.
- Null is a value that means nothing or totally empty.
- Null will be returned if you purposefully assigned the value to nothing
Ex-12 var x=null
- Undefined is a data type that indicates absence of value.
- Undefined actually means does not have a value not even a value of nothing.
- Undefined will be returned to you, if you didn't assign a value to something.
Ex-13
var x;
console.log(x);
What is NaN?
NaN stands for "Not-A-Number" and it's often returned indicating an error with number operations.
Ex-14
// calculating the square root of a negative number will return NaN
Math.sqrt(-10)
// trying to divide a string by 5 will return NaN
"hello"/5
Equality
If you use == and != in situations where the values that you're comparing have different data-types, it can lead to some interesting results.
Ex-15
"1" == 1
Returns: true
Ex-16
0 == false
Returns: true. The == operator is unable to differentiate 0 from false.
Ex-17
' ' == false
Returns: true. Both the operands on either side of the == operator are first converted to zero, before comparison.
All of the above three evaluate to true. The reason for such interesting outcomes is Type Conversion. In the case of regular comparison, the operands on either side of the == operator are first converted to numbers, before comparison. == is also called lose equality because it only checks for values.
Implicit type coercion
JavaScript is known as a loosely typed language.
Basically, this means that when you’re writing JavaScript code, you do not need to specify data types. Instead, when your code is interpreted by the JavaScript engine it will automatically be converted into the "appropriate" data type. This is called implicit type coercion.
Ex-18
"divya" + 5
Returns: "divya5"
JavaScript takes the string "divya" and adds the number 5 to it resulting in the string "divya5". In other programming languages, this code probably would have returned an error, but in JavaScript the number 5 is converted into the string "5" and then is concatenated to the string "divya".
DEFINITION: A strongly typed language is a programming language that is more likely to generate errors if data does not closely match an expected type. Because JavaScript is loosely typed, you don’t need to specify data types; however, this can lead to errors that are hard to diagnose due to implicit type coercion.
When you use the == or != operators, JavaScript first converts each value to the same type (if they’re not already the same type); this is why it's called "type coercion"! This is often not the behavior you want, and it’s actually considered bad practice to use the == and != operators when comparing values for equality.
Strict equality
Instead, in JavaScript it’s better to use strict equality to see if numbers, strings, or booleans, etc. are identical in type and value without doing the type conversion first. To perform a strict comparison, simply add an additional equals sign = to the end of the == and != operators.
Ex-19
"1" === 1
Returns: false
This returns false because the string "1" is not the same type and value as the number 1.
Ex-20
0 === false
Returns: false
This returns false because the number 0 is not the same type and value as the boolean false
Just like strict equality operator, there is also a strict non-equality operator !== that can be used instead of != if you don't want a type-conversion, before comparison.
Ex-21
0 !== true
Returns: true
Ex-22
'1' !== 1
Returns: true