cyber-s / blog

tipsや質問などをここにknowledgeとして残します。
0 stars 0 forks source link

🤓 e-Learning Journey - JavaScript #655

Open limincs opened 4 years ago

limincs commented 4 years ago

Conditions

If...Else Statements automates solutions to yes-or-no questions, also known as binary decisions.

Comparison Operators (>, <, <=,>=,===,!==)

Comparison operators <, >, <=, >=, ===, and !== can compare two values. Example:

10 < 12 
// Evaluates to true

Logical Operators (&&, ||, !)

When using the && operator, both conditions must evaluate to true for the entire condition to evaluate to true and execute. 

When using the || operator, only one of the conditions must evaluate to true for the overall statement to evaluate to true.

The ! not operator reverses the value of a boolean. The ! operator will either take a true value and pass back false, or false to true.

Truthy and Falsy

Falsy values includes:

let numberOfApples = 0;
if (numberOfApples) {
   console.log('Let us eat apples!');
} else {
   console.log('No apples left!');
}
// Output: No apples left!

Ternary Operator

The ternary operator is a shorthand to simplify concise if...else statements. Example:

let isNightTime = true;
if (isNightTime) {
  console.log('Turn on the lights!');
} else {
  console.log('Turn off the lights!');
}

We can use a ternary operator to perform the same functionality:

isNightTime ? console.log('Turn on the lights!') : console.log('Turn off the lights!'); 

Else If Statements

let stopLight = 'yellow';
if (stopLight === 'red') {
  console.log('Stop!');
} else if (stopLight === 'yellow') {
  console.log('Slow down.');
} else if (stopLight === 'green') {
  console.log('Go!');
} else {
  console.log('Caution, unknown!');
}

The else if statement always comes after the if statement and before the else statement.

Note: if/else statements are read from top to bottom, so the first condition that evaluates to true from the top to bottom is the one that gets executed.

The switch keyword

switch statement provides an alternative syntax that is easier to read and write.

let groceryItem = 'papaya';
switch (groceryItem) {
  case 'tomato':
    console.log('Tomatoes are $0.49');
    break;
  case 'lime':
    console.log('Limes are $1.49');
    break;
  case 'papaya':
    console.log('Papayas are $1.29');
    break;
  default:
    console.log('Invalid item');
    break;
}
// Output: Papayas are $1.29

The break keyword stops the remaining cases from being checked and executed.

Note: Without the break keyword at the end of each case, the program would execute the code for all matching cases and the default as well. This behaviour is different from if/else statements which execute only one block of code.

At the end of each switch statement, there is a default statement. If none of the cases are true, then the code in the default statement will run.

justcallmehide commented 4 years ago

👏