DEV Community

Cover image for Blocks, if-statements, switch (Lesson 2 with Hassan)
Hanna
Hanna

Posted on • Updated on

Blocks, if-statements, switch (Lesson 2 with Hassan)

GOOD TO REMEMBER!

{} curly brackets
[] square brackets
() parentesis / brackets
: colon
; semicolon
" quotes / double quotes
' quotes / single quotes
` back ticks

BLOCK

We use it to group expressions with each other
Curly brackets ({}) are used for the block.
It is used with:

  • if
  • while
  • for
  • functions

IF-STATEMENTS

-if to specify a block of code to be executed, if a specified condition is true;
-else if to specify a new condition to test, if the first condition is false
-else to specify a block of code to be executed, if the same condition is false;

Example 1:

if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Enter fullscreen mode Exit fullscreen mode




Example 2:


const condition = true

if(condition) {
console.log("sant")
} else {
console.log("falskt")
}

Enter fullscreen mode Exit fullscreen mode



or

Conditional (Ternary) Operator

const condition = true
condition ? console.log("sant") : console.log("falskt")
Enter fullscreen mode Exit fullscreen mode




Switch statement

To select one of many code blocks to be executed.

How it works:

  • The switch expression is evaluated once.
  • The value of the expression 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 code block is executed.

Example 3:

switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Enter fullscreen mode Exit fullscreen mode




Math.ceil() vs Math.round()

The Math.ceil() function always rounds a number up to the next largest integer.

  • Math.ceil(null) returns integer 0 and does not give a NaN error

The round() method rounds a number to the nearest integer.

Top comments (0)