loading...

JavaScript Conditionals

ziizium profile image Habdul Hazeez ・4 min read

FrontEnd Development Zero to Hero (67 Part Series)

1) FrontEnd Development: Zero to Hero 2) What is the Internet 3 ... 65 3) What is the Web 4) Web Browsers 5) Tools for Web Development 6) Introduction to HTML 7) History of HTML 8) The HTML specification 9) HTML Elements and Tags 10) Replaced Element and Void Element 11) Writing Accessible HTML 12) Validating HTML documents 13) HTML Resources and Reference 14) Introduction to CSS 15) History of CSS 16) The CSS Specification 17) CSS Properties 18) CSS Selectors 19) CSS Units 20) CSS Specificity 21) The CSS Cascade 22) CSS Inheritance 23) The CSS Box model 24) CSS Margin Collapse 25) CSS Positioning 26) CSS z-index 27) CSS colors 28) CSS Backgrounds 29) CSS Variables 30) CSS Floats 31) CSS Block Formatting Context 32) CSS Flexbox part 1 33) CSS Flexbox part 2 34) CSS Grid part 1 35) CSS Grid part 2 36) CSS Media Queries 37) CSS Typography 38) CSS Animations and Transitions 39) CSS Naming conventions 40) Writing maintainable CSS 41) CSS References and Resource 42) Introduction to JavaScript 43) History of JavaScript 44) The EcmaScript specification 45) Introduction to programming 46) JavaScript Variables 47) JavaScript Arrays 48) JavaScript Objects 49) JavaScript Numbers 50) JavaScript Conditionals 51) JavaScript Loops 52) JavaScript Functions 53) The Document Object Model 54) Introduction to Ajax 55) JavaScript References and Resource 56) Introduction to Web Design 57) History of web design 58) Site Layouts in CSS 59) Introduction to Responsive web design 60) Introduction to Progressive Enhancement 61) Introduction to User Interface design 62) Introduction to user experience design 63) Introduction to Web accessibility and usability 64) Introduction to Color theory 65) Web design References and resource 66) Series final project 67) Building your career as a developer

Naturally if you are hungry you tend to look for food and when you do find it, you eat. This is the basic analogy of conditional statements in most programming languages, JavaScript included.

The execution path of most programs is not a one way street and when you write code for a program, the program can act differently when a certain condition is met. This condition can be the result of a previous computation or a statement at that very point of execution.

Programming constructs that execute certain code based on conditions are called conditional statements or simply conditionals.

Their structure is similar in most high level programming languages with slight differences.

Let's discuss the theory behind them and we will give code examples.

All screenshots are from Firefox 71.0 and its Developer Tools. One particular feature in Firefox 71.0 that's worthy of mention is the multi-line code editor in the console.


Technically speaking conditional statements execute or skip other statements depending on the value of a specified expression. These statements are the decision points of your code.

Example of an expression is:

var a = 20;

JavaScript conditional statements are:

  • if
  • else/if
  • switch

if

The if statement is the fundamental control statement that allows JavaScript to make decisions or to execute statements conditionally.

This statement has two forms. The first is:

if (expression) {
   // statement;
}

In this form the statement will execute if the expression is evaluated and the resulting value is truthy. If the resulting value is false, the statement will not execute. Lets take an example.

/**
  * The console will log the string
  * "This code will execute"
  */
var a = 2;
if ( a == 2 ) {
  console.log('This code will execute');
}

When executed in the console:

A simple if statement in JavaScript

If the statement is a single statement you can omit the parentheses (the curly brackets) and the code will execute just fine.

A simple if statement in JavaScript

You should note that the expression can be another value that is truthy and not necessarily an equality check.

/**
  * The console will log the string
  * "This code will execute because the variable
  * "a" holds a truthy value which is the number 2
  */
var a = 2;
if ( a ) {
  console.log('This code will execute');
}

On the other hand if the expression is false the statement will not execute.

Then what happens if the code is false? That is the second form of the if statement called if/else statement. The format is

if (expression) {
    // statement
} else { 
   // this will be executed if expression evaluates to false
  statement
}

Lets revisit our last example by adding an else clause.

/**
  * The console will log the string "The expression
  * evaluated to false"
  */
var a = 2;
if ( a == 4 ) {
  console.log('This code will not execute');
} else {
  console.log('The expression evaluated to false');
}

When executed in the console:

An if else statement in JavaScript

Note: you can have more than one statement in the if and else clause.

else/if

The else ifstatement is used when you want to test multiple expressions and execute a piece of code based on the result of the expression.

The else if statement results when repeated if/else statements are used.

Let's look at an example.

/**
  * In this section of code we check for multiple expression
  * before executing a piece of code.
  */
var a = 3;
if ( a == 1 ) {
  console.log('This code will not execute');
} else if (a == 2){
  console.log('The code will not execute');
} else if (a == 4) {
  console.log('The code will not execute');
} else if (a == 3) {
  console.log('The code will execute because the expression evaluates to true');
} else {

  // if all else fails, the code here will execute
  console.log('All else code evaluated to false');
}

When executed in the console:

else if statements in JavaScript

switch

The switch statement is a complicated statement to explain. The basic syntax is:

switch (expression) {
  //statements
}

However, the full syntax of a switch statement is more complex than this. Various locations in the block of code are labeled with the case keyword.

When a switch executes, it computes the value of the expression and then looks for a case label whose expression evaluates to the same value.

The value is placed in front of the case keyword before the colon (:).
After the colon, we write the code that will be executed if the case is a match followed by a break statement.

The break statement causes the interpreter to jump to the end of the switch statement and continue with the statement that follows it.

We can have multiple case label with code and break statement, this is similar to the if else if statement we demonstrated in the last section.

If there is no matching case label, the interpreter looks for a statement labeled default: which is similar to the elseclause after multiple else if statements.

If there is no default: label, the switch statement skips the block of code altogether.

Armed with this knowledge we can rewrite or previous example using a switch statement.

/**
  * In this section of code we check for multiple expression
  * using a switch statement before executing a piece of code.
  */
var a = 3;

switch (a) {
    case 1: // if a == 1
      console.log('This code will not execute');
      break;
    case 2: // if a == 2
      console.log('The code will not execute');
      break;
    case 4: // if a == 4
      console.log('The code will not execute');
      break;
    case 3: // if a == 3
      console.log('The code will execute because the expression evaluates to true');
      break;
    default: // no match found
    // if all else fails, the code here will execute
    console.log('All else code evaluated to false');
}

When executed in the console:

JavaScript switch statement

That's it for now.

Up next, Loops.

FrontEnd Development Zero to Hero (67 Part Series)

1) FrontEnd Development: Zero to Hero 2) What is the Internet 3 ... 65 3) What is the Web 4) Web Browsers 5) Tools for Web Development 6) Introduction to HTML 7) History of HTML 8) The HTML specification 9) HTML Elements and Tags 10) Replaced Element and Void Element 11) Writing Accessible HTML 12) Validating HTML documents 13) HTML Resources and Reference 14) Introduction to CSS 15) History of CSS 16) The CSS Specification 17) CSS Properties 18) CSS Selectors 19) CSS Units 20) CSS Specificity 21) The CSS Cascade 22) CSS Inheritance 23) The CSS Box model 24) CSS Margin Collapse 25) CSS Positioning 26) CSS z-index 27) CSS colors 28) CSS Backgrounds 29) CSS Variables 30) CSS Floats 31) CSS Block Formatting Context 32) CSS Flexbox part 1 33) CSS Flexbox part 2 34) CSS Grid part 1 35) CSS Grid part 2 36) CSS Media Queries 37) CSS Typography 38) CSS Animations and Transitions 39) CSS Naming conventions 40) Writing maintainable CSS 41) CSS References and Resource 42) Introduction to JavaScript 43) History of JavaScript 44) The EcmaScript specification 45) Introduction to programming 46) JavaScript Variables 47) JavaScript Arrays 48) JavaScript Objects 49) JavaScript Numbers 50) JavaScript Conditionals 51) JavaScript Loops 52) JavaScript Functions 53) The Document Object Model 54) Introduction to Ajax 55) JavaScript References and Resource 56) Introduction to Web Design 57) History of web design 58) Site Layouts in CSS 59) Introduction to Responsive web design 60) Introduction to Progressive Enhancement 61) Introduction to User Interface design 62) Introduction to user experience design 63) Introduction to Web accessibility and usability 64) Introduction to Color theory 65) Web design References and resource 66) Series final project 67) Building your career as a developer

Posted on by:

ziizium profile

Habdul Hazeez

@ziizium

I teach and write code with interests in Web Development, Computer Security, and Artificial Intelligence.

Discussion

markdown guide