How to use the switch statement in JavaScript with logical expressions?

The switch statement in JavaScript is usually used as a way of performing different operations depending on the value of an expression. In the usual case, you specify it in the following way:

var number = 1;

switch (number) {
    case 1:
        console.log("One");
        break;
    case 2:
        console.log("Two");
        break;
    case 3:
        console.log("Three");
        break;
    default:
        console.log("Something else");
}

You can see that you provide the expression in parenthesis after the switch keyword and then the different values after the case keyword.

By only seeing this structure, it might not be obvious how to convert the following code to use a switch statement:

var number = 16;

if (number >= 1 && number <= 5) {
    console.log('Between 1 and 5.');
} else if(number >= 6 && number <= 10) {
    console.log('Between 6 and 10.');
} else if (number >= 11 && number <= 15) {
    console.log('Between 11 and 15.');
} else {
    console.log('Some other number.');
}

The situation is not easy because you are doing different things based on number ranges and not based on single values. One option would be to add a bunch of cases to the switch like this:

var number = 16;

switch (number) {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        console.log('Between 1 and 5.');
        break;
    case 6:
    case 7:
    case 8:
    case 9:
    case 10:
        console.log('Between 6 and 10.');
        break;
    case 11:
    case 12:
    case 13:
    case 14:
    case 15:
        console.log('Between 11 and 15.');
        break;
    default:
        console.log('Some other number.');
}

This can result in a very long code if there are larger numbers at play. Luckily, we have a nice trick which can be used to simplify this:

var number = 55;

switch (true) {
    case number >= 1 && number <= 5:
        console.log('Between 1 and 5.');
        break;
    case number >= 6 && number <= 10:
        console.log('Between 6 and 10.');
        break;
    case number >= 11 && number <= 15:
        console.log('Between 11 and 15.');
        break;
    default:
        console.log('Some other number.');
}

As you can see, we are putting true into the switch parenthesis so a case will match if it evaluates to true. So it is doing the same as the if statement. Some people better like this syntax, some people not. It’s your choice which one you use, although the use of if is more widespread.

Variable in JavaScript has value without specifying it

In JavaScript for certain variable names, a quite confusing situation can happen due to the various scopes present in the language. Let’s start off with some examples where we see the expected outcome and reach some interesting points from there. We have placed all the example code at the root of a JS file (so it is not inside any block).

var firstName = 'John';
var lastName;
console.log(firstName);
console.log(lastName);

The output of this is not surprisingly the following.

John
undefined

The first one contains a string we have specified and the second one prints undefined as we have not specified any value.

What if I declare a variable called “name”, but don’t assign a value to it?

var name;
console.log(name);

Surprisingly, it will contain an empty string. We’ll see why at the end, but until that let’s see another example.

What happens if I assign “John Doe” to the variable, and rerun my program?

var name = 'John doe';
console.log(name);

It will, of course, print “John Doe”. Nothing surprising. But what if I update the code to the following and refresh the page?

var name;
console.log(name);

This is what we see after the refresh:

John Doe

Wow! Our variable has the value we have previously set, although it’s not even in our code anymore.

Explanation

The first surprising outcome happened because the window object has a property called “name”, which contained an empty string. This is what is returned because we were using the “name” variable from the global scope. So what is the window object exactly?

The window object is supported by all browsers. It represents the browser’s window. All global JavaScript objects, functions, and variables automatically become members of the window object. Global variables are properties of the window object.

So, even before one line of our code executed, the “name” global variable already had an empty string as value. That is what we got back.

The other weird outcome is also because of the window object’s “name” property. This property is persisted between page refreshes and it is only cleared when the browser window is closed. This is why it still contained the value we have removed.

The conclusion we can draw here is that besides the JavaScript keywords (e.g. delete, var) that you cannot use for variable names, there are some other names that should not be used because of their unexpected side effects.

Of course, using global variables is not a good idea 99% of the time. But this won’t stop anyone from using them. They are especially common for practice code when we just quickly trying out something, and this is a good opportunity for beginners to have some headaches due to the above issue. So guys, be careful with your variable naming!