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!

How to conditionally add a member to a JavaScript object?

This article describes how to add a member to a JavaScript object only if a condition is met. We demostrate it in pure JS and also in JQuery.

Pure JavaScript version

In pure javascript, the most compact solution I could come up with is this:

var myObject = {};

if(true) myObject.member1 = 10;
if(false) myObject.member2 = 20;
if(true) myObject.member3 = 30;

In this example only the first and third member will be added. It is quite okay, but looks a bit verbose, especially because all of the assignments are separate statements, and you have to write down the name of the object multiple times. It would be good to have a solution that can handle conditional adding when declaring the object. Let’s look at jQuery…

jQuery version

As you might expect, in jQuery it is a bit more compact. Let’s see the solution:

var myObject = $.extend({}, {
    member1: true  ? 10 : undefined,
    member2: false ? 20 : undefined,
    member3: true  ? 30 : undefined,
});

As you can see, it looks better, and you can assign the members when you are creating the object. However, you have to write undefined in all places, but even considering that, it is a more compact solution.

This code uses the extend function that can add the members of one JavaScript object to another JavaScript object. As you can see we set all the attributes of the second object, but only the ones that have a value that is not undefined will be set.

Change the text of a link via CSS

A typical example of a link that changes it’s text is when you would like to create section on your website and need a link that says Collapse when the section is open and says Expand when the section is closed.

Create a simple closable section

First, let’s create a simple link that will open and close our section with the help of a little JavaScript. The HTML part:

<a class="toggle-button" href="#">Collapse/Expand</a>

<section class="expandable">
    This is an expandable section.
</section>

The JavaScript part:

$(function() {
    $('.toggle-button').on('click', function() {
    	$('.expandable').toggle();
    });
});

Clicking the link can open and close the section. So our program is working fine, but we could improve it a little bit by changing the text of the link depending on the status of our section.

Add text changing functionality via CSS

Let’s add a wrapper around our HTML elements and change the classnames:

<div class="expandable-container">
    <a class="toggle-button" href="#" data-collapsed="Expand" data-expanded="Collapse"></a>
    <section class="expandable-content">
        This is an expandable section.
    </section>
</div>

Our JavaScript will also need to be changed, because we would like to add the expanded class to the parent of the content that we would like to show/hide.

$(function() {
    $('.toggle-button').on('click', function() {
        $(this).parent().toggleClass('expanded');
    });
});

Now comes the most important part. As you can see in our HTML we provided the Expand and Collapse texts is data attributes. We will use CSS to read these attributes and set them as the link’s text.

.expandable-container .toggle-button:after {
    content: attr(data-collapsed);
}
.expandable-container.expanded .toggle-button:after {
    content: attr(data-expanded);
}

.expandable-container .expandable-content {
    display: none;
}

.expandable-container.expanded .expandable-content {
    display: block;
}

The text of the link is set using the :after psedo attribute. The content inserted this way should behave as it would be a normal child of the element, but some browsers have issues interpreting them. In an other article I discussed a possible problem that could come up on certain browsers: Link with pseudo attribute is not clickable on mobile browser (Samsung Galaxy S3)

Array has an extra undefined element in IE 8

I’ve run into this problem when I was writing a new piece of JavaScript code that went through an array and did something on all it’s elements. We needed to support the latest FF, Chrome and IE 8+. In almost all browsers it was working fine. However, in IE 8 my array had an extra undefined element at the end. My array definition looked something like this:

var arr = [1, 2, 3,]

The problem is the trailing comma at the end. IE 8 thinks that the comma means there is an extra element in the array and because it is not specified it becomes undefined.  Then if you go through all the element and try to call some function on them, you will get an error stating that the desired function is not available on that element. To fix this, just remove the trailing comma.

var arr = [1, 2, 3]