Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

switch case block scope

let number  = 2;

switch (number) {
    case 1: 
        let message = "first number";
        console.log(message)
        break;
    case 2:
        let message = "second number";
        console.log(message)
        break;
  case 3:
        let message = "third number";
        console.log(message)
        break;
    default
        let message = "second number";
        console.log(message)
        break;
}

//This throws a syntax error: identifier "message" 
//has already been declared

//Here is a way to fix this issue:

let number  = 2;

switch (number) {
    case 1: { // braces make the case statement a block
        let message = "number" + number; // this remains in this block
        console.log(message)
        break;
    }
    case 2: {
        let message =  "number" + number; // this is a valid syntax
        console.log(message)
        break;
    }
    case 3: {
        let message = "number" + number; 
        console.log(message)
        break;
    }
    default
        let message =  "number" + number;
        console.log(message)
        break;
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: multi level route static file not found issue in express 
Javascript :: threee.js camera to point 
Javascript :: sharepoint javascript get last added item 
Javascript :: how to stop re rendering in react hooks 
Javascript :: listen to keyboard close event in js 
Javascript :: javascript filter in place algorithm 
Javascript :: remove null from object lodash 
Javascript :: minus converter 
Javascript :: Print Files with React 
Javascript :: error number:-1,state:0,class:20 
Javascript :: Implementing basic set operations set object javascript 
Javascript :: replace html encodings node.js 
Javascript :: tokenize javascript 
Javascript :: redux cannot read properties state) = state.useSelector 
Javascript :: gsap cdn not working 
Javascript :: _document getInitialProps req is undefined 
Javascript :: javascript to typescript converter tool 
Javascript :: how to render req.session.name to ejs 
Javascript :: array loop 
Javascript :: infinite loop MenuItem MUI fixed onClick event 
Javascript :: random color javascript 
Javascript :: compare strings to multiple strings javascript 
Javascript :: prevent form submit twice jquery 
Javascript :: _.isEqual Underscore Example 
Javascript :: Backbone Initialize vs Render 
Javascript :: pro side nav react rtl 
Javascript :: moment format time 
Javascript :: firebase database TIMESTAMP 
Javascript :: javascript object duplicate keys 
Javascript :: function Using onpause and onplay Method to Start and Stop Animationto replace source file path to jpg image 
ADD CONTENT
Topic
Content
Source link
Name
4+2 =