Conditionals in JavaScript
7.1 Conditionals in JavaScript
JavaScript lets our code respond differently based on user inputs, values or situations
Suppose we get to vote at 18
So if our age is 18 or above we are eligible else we are not
Basic Syntax system of Conditionals
For example we want to build an Age Checker
Conditionals Statements can also be combined with Logical Operators
For example we want to build a Grade Assigner from obtained marks
Switch Statement - It is used when we have many exact matches to check
For example we want to build a day in the week finder
Suppose we get to vote at 18
So if our age is 18 or above we are eligible else we are not
Basic Syntax system of Conditionals
conditionals.js
1if (condition) {
2 // runs if condition is true
3} else if (anotherCondition) {
4 // runs if anotherCondition is true
5} else {
6 // runs if nothing else is true
7}
For example we want to build an Age Checker
age.js
1let age = 20
2if (age < 13) {
3 console.log("Child")
4} else if (age < 18) {
5 console.log("Teenager")
6} else {
7 console.log("Adult")
8}
Conditionals Statements can also be combined with Logical Operators
For example we want to build a Grade Assigner from obtained marks
marks.js
1let marks = 75
2if (marks >= 90 && marks <= 100) {
3 console.log("Grade: A+")
4} else if (marks >= 75 && marks < 90) {
5 console.log("Grade: A")
6} else if (marks >= 60 && marks < 75) {
7 console.log("Grade: B")
8} else {
9 console.log("Grade: C or below")
10}
Switch Statement - It is used when we have many exact matches to check
For example we want to build a day in the week finder
dayOfWeek.js
1let day = 3
2switch (day) {
3 case 1: console.log("Monday") break
4 case 2: console.log("Tuesday") break
5 case 3: console.log("Wednesday") break
6 case 4: console.log("Thursday") break
7 case 5: console.log("Friday") break
8 case 6: console.log("Saturday") break
9 case 7: console.log("Sunday") break
10 default: console.log("Invalid day")
11}