JavaScript

Conditionals

WebDevLee 2021. 10. 9. 23:29

이 글은 자바스크립트의 Conditionals(조건문)에 관한 개념 및 문법을 정리하기위해 작성하였습니다.



 

< Conditional >

To check a specific condition(s) and perform a task based on the condition(s)

We can make decisions based on circumstances.

 

 


< The if keyword >

if (condition) {
	// code block or block statement
}

 

  • Condition evaluates to true, block runs.
  • Condition evaluates to false, block won't run.

 

ex)

if (true) {
	console.log('This message will be printed!');
}

 

 


< If...Else Statements >

if (condition) {
	// code block-1
} else {
	// code block-2
}

 

  • Condition evaluates to true, 'code block-1' runs.
  • Condition evaluates to false, 'code block-2' runs.

 

ex)

if (false) {
	console.log('The code in this block will not run');
} else {
	console.log('But the code in this block will run');
}

 

 


< Comparison Operators >

To compare values.

All comparison statements evaluate to either true or false.

 

  • Less than : <
  • Greater than : >
  • Less than or equal to : <=
  • Greater than or equal to : >=
  • Is equal to : ===
  • Is not equal to : !==

 

 


< Logical Operator >

To add more sophisticated logic to conditionals.

 

  • and && : checks if both provided expressions are truthy.
  • or || : checks if either provided expressions are truthy.
  • not ! : switches the truthiness and falsiness of a value.

 

ex)

let mood = 'sleepy';
let tirednessLevel = 6;

if (mood === 'sleepy' && tirednessLevel > 8) {
  console.log('time to sleep');
} else {
  console.log('not bed time yet');
}

 

 


< Truthy and Falsy >

To evaluate non-boolean data types, like string or numbers, inside a condition.

 

  • Truthy : non falsy
  • Falsy :
  1.  0
  2.  '  '  or  "  "
  3.  Null
  4.  undefined
  5.  NaN (Not a Number)

 

ex)

let defaultName;
if (username) {
	defaultName = username;
} else {
	defaultName = 'Stranger';
}

// Short Version
let defaultName = username || 'Stranger';

 

 


< Ternary Operator >

To simplify on if...else statement.

 

condition ? codeblock-1 : codeblock-2

 

  • Condition evaluates to true, 'code block-1' runs.
  • Condition evaluates to false, 'code block-2' won't run.

 

ex)

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

// Ternary Operator
isNightTime ? console.log('Turn off the lights') : console.log('Turn on the lights');

 

 


< Else If Statements >

To add more conditions. So, it allows for more than two possible outcomes!

 

if (condition) {
	code block-1;
} else if (condition) {
	code block-2;
} ... 
  ...
} else {
	code block-3;
}

 

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

 

ex)

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 switch keyword >

An else if 's another version. It's easier to read and write!

 

switch (expression) {
	case value1 :
    	// code block-1
        break;
	case value2 :
    	// code block-2
        break;
        
        //...
        //...
        
    	default :
    	// code block
        break;
}

 

  • If the expression matches the specified value, that case's code block will run.
  • The break keyword tells the computer to exit the block and not execute any more code.
    Note : Without break keywords, every subsequent case will run regardless of wheter or not it matches!
  • If none of the cases are true, then the code in the default statement will run.

 

ex)

let athleteFinalPosition = 'first place';

switch (athleteFinalPosition) {
  case 'first place' :
    console.log('You get the gold medal!');
    break;
  case 'second place' :
    console.log('You get the silver medal!');
    break;
  case 'third place' :
    console.log('You get the bronze medal!');
    break;
  default :
    console.log('No medal awarded.');
    break;
}