Always break those case blocks!

This is a simple tip, that I thought I would clarify after spending some time scratching my head over a stupid, stupid mistake!

When you are using a switch statement make sure you are either returning or breaking at the end of a case statement. If you do not, your switch statement will run the expected case block AND the default block.

Below are a couple of GISTs showing what I mean.

The top GIST demonstrates how to do it, and the bottom shows you hoe to not do it. The main difference is that the second case block does not have a break. This means both the function ‘doSomethingElse()’ and ‘doDefault()’ will be executed. Not what we are after.

 

A basic jQuery plugin

jQuery is an extremely popular Javascript library that simplifies cross-browser Javascript into an easy to use API. As of May 2014, 50.1% of the top 1 million websites use jQuery in one for or another to help enhance their websites. For the same month 66.8% of the top 100,000 website and 78.5% of the top 10,000 websites use jQuery. Those stats can be found here. The popularity of the jQuery library means that as a developer you will likely encounter and work with jQuery.

You can develop with jQuery the same as if it were any bit of Javascript: write your code in an external .js file and include it onto your webpage. However, jQuery allows you to create plugins that extend jQuery and therefore can be reused through out a number of websites. jQuery plugins should be modular; it does one thing and one thing only. Similar to how a class in any programming language or CSS should only do one thing, creating reusable code.

To give you a head start with developing jQuery plugins below is a small template that you can use to build your jQuery plugin around.

The above is a compilation of these two tutorials provided on the jQuery website:

Relevant links: