📒
SDV503
  • SDV503
  • Command Prompt
    • Windows Command Prompt
    • Mac OS Terminal
  • GIT & GITHub
    • GitHub
    • Git
      • Git Workflow
        • Forking Workflow
  • README
    • How to write a readme.md file?
    • Write a better README.me
    • Generate a README for GitHub Repo Quickly
  • Code-comments
    • Clean Comments
    • Writing Comments in a Good way
  • Pair Coding
    • What is Pair Coding?
    • Pair Programming Experience
  • Programming?
    • What is Programming?
    • What Is A Programming Paradigm?
    • JavaScript Programming Paradigms
  • Number Systems
    • Decimal and Binary numbers
  • JavaSCript
    • Introduction To JavaScript
      • The JavaScript Engine
  • JS Call Stack
    • JavaScript call stack
    • JavaScript & Memory
      • Memory Leaks in JavaScript
    • Execution Context and Execution Stack in Javascript
      • Javascript Execution Context and Hoisting
  • JavaScript Variables
    • Introduction to JS Data Types
    • Primitive and Non-Primitive
    • Operator precedence and associativity
      • JS Operators Part One
      • JS Operators Part Two
      • JS Operators Part Three
    • Clean Code for JS Variables
  • JavaScript Scopes
    • Scope (Chain) Visualized
  • Javascript  — this keyword
  • JavaScript Data Types
    • More JavaScript Data Types
  • JavaScript Expressions and Statements
  • if/else, switch and ternary operator
    • If/Else statement
  • Switch Statement
  • Ternary Operator
  • JavaScript Loops
    • Loops in JavaScript
      • Trouble With Loops
  • Objects
    • JavaScript Objects
      • Prototypal Inheritance Visualized
      • JavaScript Number Object
      • JavaScript String Object
  • Functions
    • JavaScript Function Part One
    • JavaScript Function Part Two
    • Immediately Invoked Function Expressions ~ IIFE
    • JS => Arrow Functions
    • JavaScript Callback
    • Hoisting in JavaScript
      • Hoisting Visualized
    • Recursion Functions
    • Curry and Function Composition
  • JavaScript Features
    • JSpread Operator
    • JavaScript Built-in Functions & Objects
  • Data Structures&Algorithms
    • JavaScript’s Data Types
    • Data Structures in JavaScript
      • Introduction to Big O Notation
      • Big O Notation in Javascript
      • Linked Lists
        • Linked Lists — 2
      • Hash Tables
      • Stack & Queue
  • TLDR
    • Single quotes (‘ ’) and double quotes (“ ”) in JavaScript
  • ES6
    • Generators and Iterators
    • Javascript Classes
    • JavaScript closures
    • JavaScript Promises & Async/Await
      • Event Loop Visualized
  • C#
    • What does C#? (C Sharp)
    • C# vs JavaScript
    • What Is The Difference Between C#, .NET, ASP.NET, Microsoft.NET, and Visual Studio?
    • What is the .NET Framework?
    • Methods and Properties of Console Class in C#
    • Datatypes in C#
    • C# Code Comments
    • The if statement
    • The switch statement
    • Loops
    • Comparison operators
    • Addition assignment operators
    • The String Interpolation Operator
    • Arrays
    • Lists
    • Dictionaries
Powered by GitBook
On this page
  • Defining Switch Statements
  • Putting Default Between Cases
  • Multi-Criteria Case
  • Chained Expressions
  • Block-Scope Variable in Switch Statements
  • Conclusion

Was this helpful?

Switch Statement

The switch statement lets us run a statement based on the return value of an expression. It’s the same as having a series of if statements.

In this article, we’ll look at how to use switch statements.

Defining Switch Statements

switch statements are composed of a switch block with case statements for each case.

For example, we can define it as follows:

const person = 'Joe';
switch (person) {
  case 'Jane':
    console.log('Hi Jane');
    break;
  case 'John':
    console.log('Hi John');
    break;
  case 'Joe':
    console.log('Hi Joe');
    break;
  case 'Mary':
    console.log('Hi Mary');
    break;
  default:
    console.log('Hi');
    break;
}

A switch block consists of the switch keyword, which tells us that we’re creating a switch block.

After that, we have the expression that we want to compare in parentheses. In our example, we want to compare person against the values in the case expressions below.

Then we have the case clauses, which we compare the values after to person.

case 'Jane' compares 'Jane' to person for equality, case 'John' compares 'John' to person for equality, and so on.

In each case clause, we have a break; line so that the rest of the code doesn’t get executed once a match is found.

The code above should log 'Hi Joe' because we set person to 'Joe'.

The default clause executes person doesn’t match any of the values listed in the case expressions above. This means it’ll run if person isn’t 'Jane;, 'John', 'Joe', or 'Mary'.

Therefore, the switch statement above is the same as:

if (person === 'Jane') {
  console.log('Hi Jane');
} else if (person === 'John') {
  console.log('Hi John');
} else if (person === 'Joe') {
  console.log('Hi Joe');
} else if (person === 'Mary') {
  console.log('Hi Mary');
} else {
  console.log('Hi');
}

The case and default clauses are optional, but if we don’t define any of them, then the switch statement wouldn’t be very useful.

Putting Default Between Cases

We can put the default clause between cases and the switch statement still works the same way.

So:

const person = 'Joe';
switch (person) {
  case 'Jane':
    console.log('Hi Jane');
    break;
  case 'John':
    console.log('Hi John');
    break;
  default:
    console.log('Hi');
    break;
  case 'Joe':
    console.log('Hi Joe');
    break;
  case 'Mary':
    console.log('Hi Mary');
    break;
}

gets the same result as we have in the original example.

Multi-Criteria Case

We can have case clauses that are compared to multiple values for equality.

For example, if we have:

const foo = 1;
switch (foo) {
  case 1:
  case 2:
  case 3:
  case 4:
    console.log('I like this number');
    break;
  case -1:
  case -2:
    console.log('I love this number');
    break;
  default:
    console.log('I don\'t like this number.');
}

Then we get 'I like this number' since foo is 1, which is one of the values in the first case clause.

If we set foo to -1, then we get 'I love this number'.

Chained Expressions

A useful use case for omitting the break statement is to run a series of expressions.

For example, if we have:

const foo = 1;
let output = '';
switch (foo) {
  case 0:
    output += 'So ';
  case 1:
    output += 'How ';
    output += 'Old ';
  case 2:
    output += 'Are ';
  case 3:
    output += 'You';
  case 4:
    output += '?';
    console.log(output);
    break;
  case 5:
    output += '!';
    console.log(output);
    break;
  default:
    console.log('Please pick a number from 0 to 5!');
}

Then we get the following values depending on what value we set foo to:

  • foo is 0 — 'So How Old Are You?'

  • foo is 1— 'How Old Are You?'

  • foo is 2— 'Are You?'

  • foo is 3— 'You?'

  • foo is 4— '?'

  • foo is 5— '!'

  • foo is anything else — ‘Please pick a number from 0 to 5!’

Block-Scope Variable in Switch Statements

We can only have one let or const expression with the same name. Otherwise, we’ll get an error.

For example, if we have:

const person = 'Joe';
switch (person) {
  case 'Jane':
    let name = 'Jane';
    break;
  case 'John':
    let name = 'John';
    break;
  case 'Joe':
    let name = 'Joe';
    break;
  case 'Mary':
    let name = 'Mary';
    break;
  default:
    let name = '';
    break;
}

We’ll get ‘name is already declared.’ The case clauses aren’t a block if it isn’t enclosed in braces, but the switch block is a block.

We can fix this by making the case and default clauses blocks as follows:

const person = 'Joe';
switch (person) {
  case 'Jane': {
    let name = 'Jane';
    console.log(name);
    break;
  }
  case 'John': {
    let name = 'John';
    console.log(name);
    break;
  }
  case 'Joe': {
    let name = 'Joe';
    console.log(name);
    break;
  }
  case 'Mary': {
    let name = 'Mary';
    console.log(name);
    break;
  }
  default: {
    console.log('No name');
    break;
  }
}

Once we enclose it, then we can have let and const declarations with the same name.

Conclusion

The switch statement is a block that we can use to check against different values and do different things according to the value of the expression.

It’s the same as a series of if...else statements with conditions of comparing equality of a value in each.

We can also have multiple case expressions in one case clause to check multiple expressions.

The default clause is for doing something in case that nothing in the case clauses match.

If we want to declare block-scoped variables with let and const with the same name in case and default clauses, we can convert them to blocks by enclosing them with braces.

PreviousIf/Else statementNextTernary Operator

Last updated 5 years ago

Was this helpful?