Data Types and Conditionals
JavaScript offers many different data types. We have already covered numbers and strings to an extent, but there are many others!
Strings
Depending on what kind of work you are doing, you might end up working more with pieces of text rather than numbers. A string is a piece of text, and is a fundamental building block of the language.
HTML provides structure and meaning to text, CSS allows us to precisely style it, and JavaScript offers many features for manipulating strings. These include creating custom welcome messages and prompts, showing the right text labels when needed, sorting terms into the desired order, and much more.
Strings are a fundamental data type in JavaScript. They are used to represent text and are wrapped in either single quotes, double quotes, or backticks:
let greeting = "Hello World!";
let greeting2 = 'I am learning JavaScript!';
let greeting3 = `with Per Scholas!`;
Strings declared using single quotes and strings declared using double quotes are the same, and which you use is down to personal preference — although it is good practice to choose one style and use it consistently in your code.
One reason you may have to use single or double quotes is if you need to include a quote of that same type in the string. For example:
let greeting = "I'm learning JavaScript!"; // contains a single quote, so we use double quotes
let greeting2 = 'The learner said, "This is complicated!"'; // contains a double quote, so we use single quotes
let greeting3 = `The learner said, "I'm learning JavaScript!"`; // contains both, so we use backticks
Strings declared using backticks are also called “template literals.” They are a more recent feature of JavaScript and offer a few additional features, which we will cover shortly.
String Methods
Certain data types in JavaScript have built-in methods. These are functions that are built into the data type and are available to use on instances of that data type.
For example, the String
data type has a built-in method called toUpperCase()
that converts all the letters in the string to uppercase.
let myString = "Hello, world!";
console.log(myString.toUpperCase()); // "HELLO, WORLD!"
There are many other methods available for the String
data type. To begin exploring them, go through points 8 through 12 of the freeCodeCamp JavaScript String Handbook :
- Case Manipulation Methods
- Trimming whitespace
- String searching
- Substring extraction
- Modifying strings
Practicing with String Methods
Now that you have gone through the points listed above, you should have a good understanding of how strings can be manipulated in JavaScript. Try a few of the following exercises:
Currently, this given string has a trailing space at the end after the exclamation mark. To solve this, you need to remove the trailing space from the string using a predefined method.
let greeting = "Hello World! ";
console.log(greeting);
Seeing the example below, You want to make sure the word loves
is present in the string.
let sentence = "freeCodeCamp loves The Odin Project!";
Seeing the example below You want to know the index of the last occurrence of the word The
in the string.
let sentence = "freeCodeCamp loves The Odin Project! The Odin Project is great!"
Template Literals
Strings defined using backticks are called template literals. They are a new way to define strings in JavaScript. They allow you to embed expressions within the string. This is done by wrapping the expression in ${}
.
For example, the following code:
let name = "John";
let age = 25;
let greeting = `Hello, my name is ${name} and I am ${age} years old.`;
will result in the greeting
variable containing the string “Hello, my name is John and I am 25 years old.”
Comparison Operators
You know that JavaScript has a variety of data types, including strings, numbers and booleans (true
or false
). You can use comparison operators to compare these data types and make decisions based on the results.
The following comparison operators are available in JavaScript:
Operator | Description | Example |
---|---|---|
== | Equal (value comparison) | x == y |
!= | Not equal | x != y |
> | Greater than | x > y |
< | Less than | x < y |
>= | Greater than or equal to | x >= y |
<= | Less than or equal to | x <= y |
To use a comparison in a variable assignment, you can use the ==
operator. For example:
let x = 5;
let y = 5;
let result = x == y;
console.log(x == y); // true
Strict Equality
JavaScript also has the ability to compare types and values using the strict equality operator ===
. This operator checks if the two values are equal and of the same type. For example:
let x = 5;
let y = "5";
let result = x === y;
console.log(result); // false
In this example, the result
variable will contain false
because x
is a number and y
is a string. But if you use the ==
operator, the result will be true
because JavaScript will convert the string to a number and compare the values.
This operator is called the strict equality operator because it checks for both value and type equality. It is often recommended to use the ===
operator to avoid unexpected results when comparing values.
There is also a strict inequality operator !==
that checks if the two values are not equal and of the same type.
There are a lot of ways to use the strict equality operator, and it’s important to understand how it works.
Read this article on JavaScript.info to learn more about the strict equality operator.
Conditional Statements
In any programming language, you need to compare values to make decisions. For example, if the weather is sunny, you will go out, otherwise you will stay at home. Another example would be to see if a user has enough points to level up in a game.
The if-else
conditional statement is used to make decisions in JavaScript. It is often used with comparison operators to compare values and make decisions based on the results.
An example of an if statement is:
let x = 5;
if (x > 3) {
console.log("x is greater than 3");
} else {
console.log("x is less than or equal to 3");
}
In this example, the x
variable is compared to the number 3
using the >
operator. If x
is greater than 3
, the first block of code will be executed. Otherwise, the second block of code will be executed.
Critical Thinking
What will be the output of the following code?
let x = 5;
let y = "5";
if (x === y) {
console.log("x is equal to y");
} else {
console.log("x is not equal to y");
}
Else If
In the last example, you had two choices: if
or else
. But what if you want to have more than two choices?
You can use the else if
statement to add more conditions to our code. The else if
statement allows us to check multiple conditions and execute a block of code when the first condition is true. If the first condition is false, it will check the next condition and so on. If none of the conditions are true, the else
block will be executed.
Here is an example of the else if statement:
let x = 5;
if (x > 10) {
console.log("x is greater than 10");
} else if (x > 5) {
console.log("x is greater than 5");
} else {
console.log("x is less than or equal to 5");
}
In this example, the x
variable is compared to the number 10
using the >
operator. If x
is greater than 10
, the first block of code will be executed. Otherwise, the else if
statement will check the next condition. If x
is greater than 5
, the second block of code will be executed. Otherwise, the else
block will be executed.
Critical Thinking
What will be the output of the following code?
let x = 5;
if (x > 10) {
console.log("Red");
} else if (x > 5) {
console.log("Blue");
} else {
console.log("Green");
}
Logical Operators
More complex conditional statements might include multiple conditions. That is why logical operators are used to combine multiple conditions. The logical operators are &&
, ||
and !
which are used to represent and
, or
and not
respectively.
The logical operator ||
is used to combine two boolean conditions. It returns true
if at least one of the conditions is true
. Otherwise, it returns false
:
let a = 5;
let b = 10;
let c = 15;
if (a > b || a > c) {
console.log("At least one of the conditions is true");
} else {
console.log("Both of the conditions are false");
}
The logical operator &&
is used to combine two boolean conditions. It returns true
only if both of the conditions are true
. Otherwise, it returns false
:
let a = 5;
let b = 10;
let c = 15;
if (a < b && a < c) {
console.log("Both of the conditions are true");
} else {
console.log("At least one of the conditions is false");
}
The logical operator !
is used to negate a boolean condition. It returns true
if the condition is false
. Otherwise, it returns false
:
let a = 5;
let b = 10;
if (!(a > b)) {
console.log("The condition is false");
} else {
console.log("The condition is true");
}
In the above example, the extra pair of parentheses is used to make the code more readable. It is not necessary to use them.
Critical Thinking
You are tasked with writing an if
statement that checks for the following conditions in a web app to display Welcome!
to the user:
The user must either have a premium account (isPremium
) or have been a member for more than a year (membershipDuration
> 12 months).
The user must not be currently blocked from the service (!isBlocked
).
Which if statement correctly checks these conditions?
if (isPremium && membershipDuration > 12 && !isBlocked) {
console.log("Welcome!");
}
if (isPremium || (membershipDuration > 12 && !isBlocked)) {
console.log("Welcome!");
}
if ((isPremium || membershipDuration > 12) && !isBlocked) {
console.log("Welcome!");
}
if (!isPremium || membershipDuration <= 12 || isBlocked) {
console.log("Welcome!");
}
Switch Statements
The switch
statement is used to perform different actions based on different conditions. It is similar to the if-else
statement, but is more readable and easier to understand when there are multiple conditions to check. The switch
statement is used to select one of many code blocks to be executed.
The switch
statement evaluates an expression and compares it with the values of each case. If there is a match, the associated block of code is executed. If there is no match, the default block of code is executed.
let day = "Monday";
switch (day) {
case "Monday":
console.log("Today is Monday");
break;
case "Tuesday":
console.log("Today is Tuesday");
break;
case "Wednesday":
console.log("Today is Wednesday");
break;
case "Thursday":
console.log("Today is Thursday");
break;
case "Friday":
console.log("Today is Friday");
break;
case "Saturday":
console.log("Today is Saturday");
break;
case "Sunday":
console.log("Today is Sunday");
break;
default:
console.log("Invalid day");
}
In the above example, the value of the day
variable is compared with the values of each case. If there is a match, the associated block of code is executed. If there is no match, the default block of code is executed.
break
is used to stop the execution of the code block. Ifbreak
is not used, the code will continue to execute the next block of code.
Critical Thinking
Given the JavaScript code snippet below, which modifies the activity
variable based on the day of the week, what will be the value of the activity
variable if the value of the day
variable is “Tuesday”?
let day = "Tuesday";
let activity;
switch (day) {
case "Monday":
activity = "Go to the gym";
break;
case "Tuesday":
activity = "Attend coding meetup";
break;
case "Wednesday":
activity = "Watch a movie";
break;
case "Thursday":
activity = "Visit a museum";
break;
case "Friday":
activity = "Dinner with friends";
break;
case "Saturday":
activity = "Hiking in the mountains";
break;
case "Sunday":
activity = "Rest at home";
break;
default:
activity = "Undefined day";
}
Ternary Operator
Another way to compare conditional statements would be the ternary operator. The ternary operator is a shorthand way of writing an if-else
statement. It is used to evaluate a condition and return a value based on the result of the condition. The syntax of the ternary operator is as follows:
let result = condition ? valueIfTrue : valueIfFalse;
In the above example, if the condition is true, the value of result
will be valueIfTrue
. Otherwise, the value of result
will be valueIfFalse
.
Ternary operators are often used to assign a value to a variable based on a condition. They are also used to return a value based on a condition.
Critical Thinking
What is the value of the result
variable if the value of the condition
variable is true?
let condition = true;
let result = condition ? "option 1" : "option 2";