[2022.10.10(Mon)] JavaScript #4 - if/else Statements

Jun's Coding Journey·2022년 10월 10일
0

[Learn] JavaScript

목록 보기
5/9

In this post, I want to talk about the importance of using if/else statments. We need to remember that computers do things differently than that of humans. Although computers possess powerful task-achieving capabilities, they can only do things in a 100% logical manner. As such, in order for computers to be useful, we need to tell them to do things differently within various situations. This is where the if/else statement is very helpful.

While writing code for a program, developers often times need to make decisions for various situations. In such cases, developers use conditional statements that gives the program to make certain decisions based on various situations. The if/else statement can also be called a 'control structure' where developers are able to take control over the ways in which the code functions.

During the use of 'if/else statements', we use boolean to decide whether the statement will be executed or not.

// if/else statement structure
if () {    // if statement 1 is true
} else if {   // if statement 1 if false and statement 2 is true
} else { // If all the previous condition fails
}
// Ex) driving age
const age = 18;
if (age >= 18) {
  console.log('Sarah can start driving');
} else {
  const yearsLeft = 18 - age;
  console.log(`Sarah is too young. Wait another ${yearsLeft} years :)`);
}
// Ex) find the century
const birthYear = 2012;
let centure;
if (birthYear <= 2000) {
  centure = 20;
} else {
  century = 20;
}
console.log(century);

Conditional (Ternary) Operator

Besides the if/else statement and the switch statement, there is also the conditonal (ternary) operator. this is known as 'ternary' because there is a three part process in creating a conditional code. The functionality is similar with both if/else statement and the switch statement. The only difference is that the conditional operator is much simpler and shorter to write. We can literally fit all the code within a single variable.

const example = age > 18 ? console.log('1st Condition') : ('2nd Condtion');

We can even write this code using template literals.

console.log(`I like to drink ${age >= 18 ? 'wine' : 'water'}`);

However, this does not mean that we can ignore the if/else statement or the switch statement. Different methods are used for different situtations. So it is good to remember all 3 ways of creating conditional codes 😀.

profile
Greatness From Small Beginnings

0개의 댓글