Disclosure: Your support helps keep the site running! We earn a referral fee for some of the services we recommend on this page. Learn more

JavaScript is one of the most popular programming languages in the world. Along with HTML and CSS, JavaScript is one of the three foundational technologies that virtually all websites rely on.

While HTML is the language used to assign meaning to each bit of content on a website, and CSS is the language used to format styling and layout of HTML elements, JavaScript adds behavior to a web page.

Introduction to JavaScript

What is JavaScript?

First, let’s clear up any confusion about the name: JavaScript has nothing to do with Java. Now that we know what JavaScript is not, we can talk about what JavaScript is.

If all you want to do with your website is to display some basic text and images, then HTML and CSS are enough to do the job.

However, if you want to do more — such as change styles dynamically, animate menus, create functional buttons, validate data entered into a form, and much more — you’re going to need another tool.

JavaScript is the tool most frequently used to handle these common website behavior tasks.

Getting Started with JavaScript

If you’re ready to get your hands dirty and get down to the task of learning JavaScript, there are two types of resources to check out.

If you prefer to learn-by-doing, consider working your way through an interactive course or two where you will learn JavaScript as you are prompted to create simple scripts in a browser-based interactive course.

When you’re ready to dive deeper and become a true JavaScript developer, online books and tutorials can help you get there.

If you are a complete beginner you will do best to start with some of the free interactive courses. Once you have a basic grasp for how JavaScript works, head into some of the meatier books and tutorials which will help you level-up from beginner status to a competent programmer.

Free Interactive Courses

Codecademy is the premier provider of free programming education. They offer a JavaScript track that may be the most effective way to get started learning JavaScript.

Code School is a premium (paid) education provider.

However, their quick introductory JavaScript course is free, and will give you a 10-minute overview of JavaScript that will get your education headed in the right direction. If you are an absolute beginner, you’ll cover a lot of ground in just a few minutes in this course.

The jQuery Foundation, in cooperation with Code School, has pulled together an introductory interactive jQuery course.

Keep in mind that most everyone, including us, recommends learning some JavaScript before you plunge into jQuery. So after completing the JavaScript track at Codecademy, give this course a try and you’ll gain a sense of what can be done with jQuery.

Online Books and Tutorials

JavaScript For Cats is a free tutorial you can read online, and one intended to get you up and running as a beginning JavaScript programmer.

Written for cats, but also suitable for their human companions, this tutorial won’t turn you into a full-fledged developer, but it covers the basics and will help you develop a solid foundation to build on.

Eloquent JavaScript by Marijn Haverbeke can be read for free online, or you can get an old-fashioned paperback copy.

Developed with backing from web-heavyweights such as Mozilla and Hack Reactor, Eloquent JavaScript is well-respected by experienced programmers.

The Mozilla Developer Network (MDN) offers comprehensive guides for foundational web technologies, including JavaScript.

The content provided by MDN is extremely detailed and is considered adequate to get a disciplined student all the way from beginner status to being a competent front-end developer.

The You Don’t Know JS books series, by Kyle Simpson, is a deep-dive series that aims to help you develop mastery of each topic covered.

This isn’t a “get up and running” series. You should already be relatively competent before beginning it. If you’re ready to move beyond basic JavaScript usage and become a truly competent JavaScript programmer, with this book series you’ll dive right in the deep end.

JavaScript Libraries and Frameworks

JavaScript Libraries and Frameworks

When you first start learning JavaScript you will want to learn and use it in its native format. However, you will quickly find that many of the things routinely accomplished with JavaScript require a great deal of coding.

This is where JavaScript libraries and frameworks come in: they cut down on the amount of code required to accomplish common tasks.

While you certainly can use JavaScript in it’s native format, and you should develop a solid understanding of pure JavaScript before moving on, you can get a lot more out of JavaScript with a lot fewer keystrokes if you learn to use some of the many libraries and frameworks.

According to W3Techs, jQuery, Bootstrap, and Modernizr, are the most popular JavaScript libraries and frameworks.

jQuery is the most popular JavaScript library by a large margin, and is designed to help you write less code.

It’s also one of the easiest JavaScript libraries to get started with since it uses mostly the same syntax as pure JavaScript. Basically, if you can accomplish a task with JavaScript, you can accomplish the same task with a lot less code by learning jQuery.

Bootstrap is much more than just a JavaScript library. It is a complete framework, or suite of tools, for developing responsive websites.

Building a website front-end with Bootstrap will produce solid HTML, CSS, and JavaScript code. Bootstrap provides everything you need to develop the front-end of any type of website.

Modernizr is a small piece of JavaScript code used to detect the features available in a website visitor’s browser, and to tailor the content and styling delivered based on the features detected.

Unlike jQuery and Bootstrap, which are can be used to accomplish just about anything, Modernizr is a niche script used for a very specific purpose: to tailor a website visitors experience based on the features supported by the visitor’s browser.

Some additional JavaScript frameworks being used to develop the most advanced web applications today are Angular.js, Backbone.js, Ember, and React.

If you want to take your JavaScript from simple front-end manipulation to full-fledged custom-app development, a little time spent researching these frameworks will help you identify the best framework for your project, and open your eyes to the power they offer.


Modernizr is a JavaScript library that detects if the browser is HTML5 and CSS3 compliant. This allows it to do just the things that the browser can do. It doesn’t add functionality to your code, but it makes sure that the browser is only sent commands that the browser can execute.

There are many tutorials and books you can find if this is something you think will be using.

Modernizr Tutorials

There aren’t many books on Modernizr, because it is rather specialized. And those that are around have not been well reviewed. You are better off sticking with online tutorials:


We’ve already mentioned jQuery. And once you master JavaScript, you will likely want to look into jQuery, which really makes JavaScript programming easier.

We have a whole article on it, Learn and Master jQuery, which will not only get you started with jQuerry, but includes a tutorial on using jQuery for designers.


Backbone.js is a JavaScript library that was created by Jeremy Ashkenas, who also co-created CoffeeScript, LiveScript, and Underscore.js.

The project is hosted at GitHub and ongoing development is spearheaded by Ashkenas with a community of open-source contributors.

Backbone.js is intended to be used to build single-page JavaScript web applications. The library brings structure to the development of web applications by encouraging complete separation between application logic and the presentation of the application content.

Backbone.js Basics

Backbone.js is a client-side JavaScript library. Its dependencies include the Underscore.js and jQuery libraries, which must be loaded by the browser prior to loading Backbone.js.

The library has a RESTful JSON interface, meaning that it can send and receive data to and from a web server using the lightweight JSON data format.

The library is designed with the Model-View-Presenter (MVP) programming architecture, a popular software design pattern for user interfaces. However, in the Backbone.js ecosystem, the terminology “models, views, and collections” is used.

Models, Views, and Collections

The philosophy behind Backbone.js is that application logic and the presentation of application data should be separated. This separation is maintained in the way that models and views are created and manipulated.

In Backbone.js, a model represents a single table of data along with the functions and logic needed to manipulate the data.

The data is presented using one or more views, which are simply portions of a web application UI that translate the data in the model and adjust the webpage DOM to match.

Views also listen for user input and send that input back to the appropriate model to update the data held in the model.

Backbone.js includes a built-in JSON API. When a model is changed, the change can be communicated back to a web server database over the JSON API.

Since virtually all server-side programming languages can be equipped to send and receive JSON data, virtually any server-side language or application with a JSON API can be used to communicate data to and from a Backbone.js web application and update the application database accordingly.

Related models can be organized and managed by grouping them together into collections, which offer the added benefit of providing a single listening point whereby multiple views can be used to keep one or more views continuously updated.

What is Backbone.js Good For?

While Backbone.js is not as ubiquitous as the most popular JavaScript libraries such as jQuery and Modernizr, the library is among the top fifteen or so of all client-side JavaScript technologies.

In addition, Backbone.js projects may not be as numerous, but projects that do use the library tend to be higher traffic web applications, some of which enjoy a high degree of name recognition.

For example, the Backbone.js website provides a list of known projects built with Backbone.js which includes a veritable who’s-who of well-known internet startups and established digital titans such as:

  • Hulu
  • Quartz
  • Vox
  • WordPress.com
  • Disqus
  • Khan Academy
  • Walmart Mobile
  • Basecamp
  • Airbnb
  • Pandora
  • Code School
  • Trello
  • Stripe
  • And many more.

What sets Backbone.js apart from many other popular JavaScript frameworks — notable, AngularJS — is the relative freedom it offers to developers.

While other leading frameworks may include built-in default features that are a great help (take two-way data binding for instance), Backbone.js does not. This is the key reason Backbone.js is referred to as a library rather than a framework.

Instead, it provides developers with complete freedom to build a web application that conforms to their preferences rather than forcing the developer to accept a variety of pre-made decisions.

On the other hand, this does mean that more foundational groundwork must be laid when building a web application with Backbone.js than with a framework such as AngularJS that includes a pre-build foundational groundwork.

Learning Materials

If you want to learn Backbone.js the first thing you will need to do is to master JavaScript and jQuery.

Since Backbone.js is a JavaScript library built to work alongside jQuery, mastering these two programming languages prior to tackling Backbone.js will save you a lot of time and frustration.

  • Learn and Master jQuery
  • JavaScript and jQuery for Designers.

In addition, you’ll want to get up to speed with Underscore.js, or it’s descendant library, Lodash.

Backbone.js requires that one of these two libraries be loaded prior to loading Backbone.js, so having a degree of familiarity with one or the other will come in handy.

Online Tutorials

If you want to get up and running with Backbone.js as quickly as possible, then tackling a few of the following tutorials is your best bet.

We’ve sorted them in order of complexity. So, if you’re a beginner, start with one of the first resources listed as the latter resources assume quite a bit of prior knowledge.

The Backbone.js GitHub repository also includes an extensive list of additional tutorials, blog posts, and examples of Backbone.js web applications.


If you really want to master Backbone.js, or if you just prefer your education to be printed and bound, consider the following positively-reviewed texts.

Final Thoughts on Backbone.js

Backbone.js is a JavaScript library designed for the development of one-page web applications.

The library is noteworthy in the way that it offers full separation between application data and the views that display that data to application users, as well as the relative freedom — and corresponding responsibilities — it affords to JavaScript developers.

Functional JavaScript

Functional JavaScript

When programmers talk about functional programming, they are generally talking about two different but related things:

  • A programming style that emphasizes the intentional avoidance of side effects as well as hidden inputs and outputs.
  • A set of programming functions — such as curry, map, and filter — derived from lamba calculus.

These concepts are related because the types of functions associated with functional programming enable a greater degree of code abstraction by performing powerful and complex mathematical computations.

What Makes Functional Programming Functional?

Every function takes in one or more inputs and produces one or more outputs. Take this simple function for instance:

function example( a ) {
  var result = a + 1;
  return result;

This simple function takes a single input, a, adds one to that value, and then stores the result in a variable called result. In this case, a is the input and result is the output.

Simple enough, right?

However, what about this slightly more complex function? What are its inputs and outputs?

function example( a ) {
  var result = doSomething( a ) + 1;
  return result;

Well, now suddenly things are more complex. We have a function, doSomething(), nested inside of our function and acting on our variable. If you were to change doSomething() you would also necessarily change the result of example().

In this case, we have what is called a hidden input. Whatever it is that doSomething() actually does in an input into our example() function, there’s no way to tell by looking at our function exactly what it will do.

In addition, we would say that the function doSomething() has side-effects. What this means is that when doSomething() is changed it affects other functions. The entire scope of the function is not contained within the function.

Functional programming is a style of programming that tries to eliminate all side effects as well as hidden inputs and outputs by writing functions that explicitly declare all of their inputs and outputs.

For example, we could rework the function above in the functional style by keeping the functions seperate and declaring doSomething(a) as an input into example(a), like this:

function doSomething( a ){
  var b = a + 1;
  return b;
function example( c ){
  var result = c + 1;
  return result;
var c = example( doSomething(1) );

While this may look more complex at first glance, you can easily look at the line declaring var c and know that there are two functions involved in creating the output, whereas the previous example obscured that information.

If you’re still a bit confused about exactly what functional programming is, What Is Functional Programming? by Kris Jenkins is an excellent technical introduction to this topic that applies to any programming language.

Functional Programming with JavaScript

Is JavaScript a functional programming language? Well, the answer to that question depends on what you mean by functional programming language.

You can write code using a functional programming style with JavaScript. However, plain vanilla JavaScript does not include the sort of powerful mathematical functions most programmers are looking for when they talk about functional programming.

The solution, of course, is to build or include a JavaScript library of functional programming functions. Do that, and JavaScript becomes a great language for writing functional code.

If you’re primarily concerned with learning the functional programming style and less concerned with complex mathematical functions, then the following resources will help you better grasp the functional programming style and how it can be applied to JavaScript:

Functional JavaScript

While JavaScript can be used to program in a functional style, as we mentioned it does lack a library of the sort of functions many functional programmers are looking for.

In 2007, Oliver Steele released Functional — a JavaScript library that introduces the sort of mathematical formulas and functions that functional programmers frequently use.

Rather than force any constraints upon programmers forcing them to write functional code, Functional is basically a set of lambda calculus formulas converted into JavaScript functions.

  • High-order functions included in Functional include map, reduce, and filter.
  • Function-level methods include curry, partial, compose, guard, and until.
  • In addition, Functional includes support for lambda expressions.

Functional is hosted at GitHub and is completely free and open source. However, it hasn’t seen a significant update since 2007. In other words, you can expect some bumps along the way if you try to make use of the old library.

If you want to learn more about Functional JavasScript check out the following resources:

Functional JS

If the idea of using a circa-2007 JavaScript library makes you a little nervous — as it should — why not spin up a more modern alternative?

Functional JS by Lee Crossly was released in late 2013. It is similar to Functional by Oliver Steele in that it is basically a collection of calculus functions rather than constraints to enforce a functional style of programming. However, it includes a much wider range of functions including curry, arity, lambda, map, reduce, select, partition, group, and a whole lot more.

Functional JS is hosted at GitHub, and the official project website offers excellent and thorough library documentation. Although, you should be warned that the documentaiton is written in a style that assumes it is being read by experienced developers.

Final Thoughts on Functional JavaScript

Functional programming is a style of programming developed in support of lambda calculus that encourages the explicit declaration of all inputs and outputs and the avoidance of side effects. A functional programming style can be used when coding with JavaScript.

However, standard JavaScript does not include the sort of powerful mathematical functions that many functional programmers are looking for. JavaScript can be enhanced to better suit a functional programming style by making use of free JavaScript libraries such as Functional by Oliver Steele and Functional JS by Lee Crossley.

JavaScript Style

JavaScript Style

JavaScript is a very forgiving programming language. As a result, the same bit of code written by two different JavaScript programmers will often look quite different.

Conforming to a set of stylistic guidelines ensures that all code looks as though it were written by a single programmer even when multiple programmers are involved. It also makes code easier to read and understand.

In this guide, we’ll provide a set of JavaScript coding guidelines that you can adopt to write cleaner, elegant code, and ensure a consistent programming style is used.

A Guiding Principle

When programming in any language, including JavaScript, emphasize clarity over cleverness.

This means that the goal of the programmer should be to write code in a way that is as readable as possible rather than to use the fewest number of keystrokes.

If there are two ways to do a thing — and in JavaScript, there are often a half-dozen or more ways to do a thing — use the method that offers the most clarity rather than the method that is the most clever.

For example:

// Clever, but potentially confusing
;[ 'foo', 'bar', 'baz', 'qux' ].forEach ( function () {
  // Function code
} );

// Somewhat verbose, but clear
var foobars = [ 'foo', 'bar', 'baz', 'qux' ];
function somethingClever () {
  // Function code
foobars.forEach( somethingClever );


Since we’ll be using comments throughout this guide, let’s address comment styling first.

Programmers should err on the side of providing too many comments rather than too few. Comments are an invaluable way to help other developers understand what’s going on and also help the original developer remember the purpose of each bit of code.

There are three types of comments that can be used in JavaScript:

  • Single line comments.
  • Multi line comments.
  • Inline comments.

Here is how we recommend formatting each type of comment:

  This is a multi-line comment. This type of comment
  should be reserved for file headings and to describe
  the purpose of complex functions.

// This is a single line comment. Use it to provide short notes.

// Try to avoid inline comments as seen below.
var foobars = [ 'foo', 'qux' /* also quux and quuux */ ];

Single and multi-line comments should always be preceded by a blank line. In addition, single line comments should appear above the code they describe, not next to or below it.

Multi line comments can be formatted in many different ways.

 *                                                         *
 *  Some developers like to create large blocks            *
 *  in which to nest multi line comments. It certainly     *
 *  isn't our preference, but the key here is consistency. *
 *  If you're going to use this format, just make sure to  *
 *  use it consistently.                                   *
 *                                                         *

  * Our preference is for simplicity. Multi-line comments
  * typed out simply require less effort and are just as
  * easy to read - and present less of an eyesore if you
  * ask us. We recommend the use of a single forward slash
  * and two asterisks to open a multi-line comment. Then,
  * each line begins with two space indentation, an
  * asterisk, and a space. The comment is closed with a
  * two space indentation, an asterisk, and the closing
  * forward slash.


  But this style of comments is arguably as readable as
  the other styles. And it has the advantage of being
  easy to maintain, regardless of the editor that the
  programmer is using.


Whitespace, Line Breaks, Columns, and Indentation

The proper use of space is the single most important determiner of code readability. Code that is consistently spaced and indented is far easier to read than the alternative.


Let’s start with indentation. While indentation practices vary, the predominant indentation method — and the method we recommend — is to indent with the use of two spaces.

Indentation can be configured in virtually every integrated development environment (IDE) or text editor, so just set indentation to 2 spaces and you should be good to go.


When we talk about columns in programming, what we’re referring to is the number of characters that should appear in a row before adding a line break. For the sake of readability, it is important to add line breaks. In general, the consensus is that 80 characters, or columns, is a good break-point. Others perfect smaller lengths, like 65.

One additional issue that will require illustration is the use of indentation following a line break. When that occurs, the best thing to do is to indent the wrapped content 4 spaces rather than 2 as shown in the example below:

var foo = 'This variable contains a very long ' +
    'string that will break out over multiple ' +
    'lines. For the sake of clarity, the ' +
    'content appearing on new lines should be ' +
    'indented four spaces.',
  bar = 'Indenting in this way makes it easier' +
    ' to visually differentiate between line ' +
    'breaks due to column wrap and line breaks' +
    ' at the end of a statement.';

(Note that we are using shorter line lengths to make them look good on this webpage.)


A few additional best-practice rules for the use of whitespace include:

  • Avoid end-of-line and blank line whitespace. That is, avoid leaving an empty space at the end of a line of code or on an empty line. Turning on “show invisibles” or “draw white space” in most text editors and IDEs will display these characters so that you can spot and eliminate them.
  • Add a space after commas in lists, like this: var foo = [ 'bar', 'baz', 'qux' ];.
  • Add whitespace between parentheses and their contents, like this: function( foo )....
  • Add whitespace between operators and content when concatenating a string, like this: 'Hello ' + 'world!'.
  • Adding a single blank line to separate and group of related bits of code is fine. Adding multiple lines is not recommended.


When naming functions, variables, and other items in JavaScript here are a few rules to observe:

  • Use human readable names that are intuitively meaningful whenever possible.
  • Use plural names for arrays and singular names for other types of variables.
  • Use camelCase to name functions and variables, like this: var longName = '';.
  • Use PascalCase when naming constructors (object classes), like this: function HostingCompany( name, url, rating) {....
  • If you create symbolic constants, name them by using all caps and underscores, like this: var MAX_RATING = 100;.
  • When creating regular expressions, prefix the name with a lower case r, like this for validating email addresses: var rEmail = /[A-Z0-9._%+-][email protected][A-Z0-9.-]+.[A-Z]{2,63};.


Virtually all modern JavaScript implementations include a feature called automatic semicolon insertion (ASI). This feature intuits where semicolons are supposed to appear and adds them automatically.

As a result, some programmers encourage others to never use semicolons with the exception of a few edge cases. Others programmers encourage you to add them as if ASI did not exist.

We’re solidly in the latter camp. We’ve just seen too many concatenated JavaScript files break to think it’s okay to omit them.

The question then becomes, when should semicolons be added? In general, semicolons should be added after every declaration or assignment. For example:

var foo = '';
foo = 1;
foo = function() {
  // Semicolon needed because this function is being assigned to a variable.
alert( foo );
console.log( foo );

Semicolons are not needed after the closing curly brace of a statement or function — unless the function is assigned as the value of a variable as demonstrated in the last bit of code.

However, if you do add semicolons after functions and statements you aren’t going to break anything in doing so.

In addition, semicolons should never be added between the closing paranthesis and opening curly brace in a statement or function like this: function( parameter ); {... or if ( condition ); {....


In JavaScript, either single quotes or double quotes may be used. However, the consensus among most published style guides is in favor of the use of single quotes — a consensus we are happy to go along with.

When you need to use more than one set of quotes, such as when nesting HTML inside of JavaScript, alternate between single and double quotes.

// Do this
var foo = 'bar';

// Not this
var foo = "bar";

// This is ok
var foo = '<div class='trouble'>Some content here.</div>';

// But this is easier and more readable
var foo = '<div class="trouble">Some content here.</div>';


JavaScript is very forgiving in allowing variables to be declared in a wide variety of formats. We recommend using a format that is as readable and clear as possible.

// This is bad because it is hard to read. Don't do this.
var foo = "", bar = [], baz = {}, qux = function () { 
    /* Insert statements here. */ };

//This is bad because it is inconsistent.
var foo = '', 
  bar = [];
var baz = {};
qux = function () { /* Insert statements here. */ };

// This is good because it is consistent and legible.
var foo = '',
  bar = [],
  baz = {},
  qux = function () {
    // Insert statements here.

// This is best.
var foo = '';
var bar = [];
var baz = {};
var qux = function () {
    // Insert statements here.

There are many times when you will want to declare a variable inside of a function or inside of an if…else statement. When that happens, group all of your variables together and declare them first.

Arrays and Objects

Creating complex arrays and objects has the potential to produce highly illegible code. For this reason, proper indentation and the use of line breaks is critical. Let’s review a few examples of good and poor coding practice with regard to the creation of arrays and objects.

// It's okay to declare short, simple arrays on a single line.
var foobars = [ 'foo', 'bar', 'baz', 'qux' ];

// Long arrays should be declared with line breaks.
var emailAddresses = [
  '<a href="mailto:[email protected]">Contact Us</a>',
  '<a href="mailto:[email protected]">Webmaster</a>',
  '<a href="mailto:[email protected]">Sales</a>',
  '<a href="mailto:[email protected]">Support</a>'

// Objects should always be declared with line breaks.
var placeholders = {
  1: 'foo',
  2: 'bar',
  3: 'baz',
  4: 'qux'

Statements and Functions

Properly formatting statements and functions makes them easier to understand and can also help avoid issues when code is concatenated or rendered by a browser. Here is how functions and statements should generally be formatted:

function functionName() {
  // Insert code here.

That basic format should be followed for functions, if statements, for statements, while statements, and so forth. The rules that dictate that style include:

  • Always place the opening bracket on the same line as the function or statement parameters like this: ( parameters ) {.... Adding a line break between the closing parenthesis and opening bracket can cause automatic semicolon insertion (ASI) to break code by adding semicolons improperly.
  • Always break statements and functions onto multiple lines with all function or statement code appearing on the lines between the opening and closing brackets.

Nesting Functions

Nesting functions inside of functions as shown in the next example is perfectly acceptable:

function fooBar( foo ) {
  var bar = function() {
    // Function code here.
  function nestedFunction() {
    // More function code here.
  return nestedFunction( bar );

However, nesting functions inside of statements should only be done when the function is assigned to a variable. This is because the ECMAScript standard does not support nested functions in statements.

While most JavaScript implementations will handle this improper use just fine, implementations that follow ECMAScript more strictly will not process the code correctly.

The following example illustrates the difference:

if ( foo > bar ) {

  // Don't do this
  function fooBar( foo, bar ) {
    foobar = foo + bar;
    return foobar;
  fooBar( foo, bar );

  // Do this instead
  var foobar = function fooBar( foo, bar ) {
    return foo + bar;

When writing if…else statements, make it clear that the entire statement is connected by avoiding the addition of line breaks before each portion of the statement.

// Use the following format.
if ( condition ) {
  // Insert statements here.
} else if ( condition ) {
  // Additional statements here.
} else {
  // Even more statements here.

// Don't do this. It's confusing.
if ( condition ) {
  // Insert statements here.
else if ( condition ) {
  // Additional statements here.
else {
  // Even more statements here.


When comparing two values in JavaScript you have two options. You can check for either strict equality by using === and !== or you can check for abstract equality by using == and !=.

The difference between the two options is that when you check for abstract equality the JavaScript machine will attempt to convert the value types before returning false.

However, when you check for strict equality, the machine will only return true if both the type and value are a match. Here are a few examples of how this can play out in practice:

// A number
var foo = 0;

// A string
var bar = '0';

// Evaluates to 'true'
foo == bar;
foo == false;
bar == false;
foo !== bar;

// Evaluates to 'false'
foo != bar;
foo === bar;
foo === false;
foo === false;

The use of abstract comparisons can lead to confusion about variable types. As a result, we recommend sticking to strict comparisons to avoid the following sort of issue:

// A string
var foo = '123';

// A number
var bar = 123;

// Will return true
foo == bar;

// Will return false
foo === bar;

If you use abstract comparison you may think both values are equal to the number “123” when foo is actually equal to the string “123.”

As a result, you may try to perform mathematical calculations with the string in foo. Strict comparison of the values will clue you into the issue and let you know that you need to convert foo into a number before performing a calculation.

Learn More About JavaScript Style

If you want to learn more about JavaScript style, the following sources will be useful:

Final Thoughts on Style

Using a consistent and thoughtful style when writing JavaScript can make your code easier to read and understand.

In addition, using a consistent style when working on projects that involve multiple developers ensures that all code is present in a consistent manner.

In this guide, we’ve presented a suggested style for writing JavaScript code. Adopt it, modify it to suit your needs, and reap the benefits of cleaner, clearer, more consistent code.



CoffeeScript (CS) is a concise programming language designed by Jeremy Ashkenas that compiles into standard JavaScript that can be executed in any JavaScript environment.

It is an open source language, and ongoing development is completed in collaboration between Ashkenas and an army of nearly 200 contributors.

CS is designed to let developers write code using a simple and concise syntax. Then to compile into JavaScript code that takes advantage of programming best practices and can be readily executed by any JavaScript runtime environment.

History of CoffeeScript

In December of 2009, Jeremy Ashkenas created a new GitHub repository with an initial commit tagged as “initial commit of the mystery language.”

This initial commit was rapidly built upon and the first official release of the language, CS version 0.1.0, came less than 2 weeks later on Christmas Eve of 2009.

The CS compiler was originally written in Ruby. However, version 0.5, released in February of 2010, replaced the compiler with one written in CoffeeScript itself. However, there was still a ways to go before the first stable version of CS, version 1.0.0, which was released on Christmas Eve of 2010, approximately one year after the project sprang to life.

The latest version of CoffeeScript is version 2.3.1 as May 2018.

To keep abreast of the latest development work being done on CS, refer to the CoffeeScript 6.0 GitHub repository.

Jeremy Ashkenas

The designer of CS, Jeremy Ashkenas, is an influential and productive JavaScript developer. In addition to CS, Jeremy has developed the following noteworthy projects:

  • LiveScript: a functional programming language with support for object oriented and imperative programming styles that is an indirect descendant from CoffeeScript. Like CS, it compiles into standard JavaScript.
  • Backbone.js: a flexible JavaScript library designed with single-page web apps in mind that emphasizes the separation of application logic code from the code that defines the presentation of application data.
  • Underscore.js: a JavaScript library with utility functions to address common programming tasks.

Jeremy is also a developer for The New York Times as well as a popular speaker for conferences and you will find many videos of his talks on YouTube, such as:

CoffeeScript Syntax

The CS tagline is “Unfancy JavaScript” and that tagline doubles as an effective description of CS syntax.

One of the primary goals in designing CoffeeScript was to create a language that was easy to write — modeled after languages like Ruby, Python, and Haskell. For this reason, CoffeeScript abandons many of the syntactical rules that apply to JavaScript.

Most notably, curly braces, semicolons, and the use of assignment keywords like var and function are all omitted in CS.

This makes CS extremely concise, but does so at the expense of readability. To get a sense for how this works, consider the following JavaScript function followed by the CS equivalent.

// Function to return the average host rating in JavaScript
var hostRating;
hostRating = function ( totRatingsVal, totRatingsNo ) {
  return totRatingsVal / totRatingsNo;

// The same function in CoffeeScript
hostRating = ( totRatingsVal, totRatingsNo ) ->
  totRatingsVal / totRatingsNo

As you can see, the CS version is cleaner, shorter, and contains fewer language operators. This makes the CS version a bit faster to type, but it also masks what is going on behind the scenes to a certain degree.

Literate CoffeeScript

One interesting variation of CS is called literate CoffeeScript. The compiler will recognize this variation as long as the source code file ends with the extension .litcoffee rather than .coffee.

Literate CS allows developers to write code using markdown syntax. All writing will be ignored by the compiler as commentary while indented code blocks are recognized as program code.

Let’s look at a short example.

## Literate CoffeeScript

[Literate CoffeeScript](http://coffeescript.org/#literate) allows for the use of [markdown](https://daringfireball.net/projects/markdown/syntax#precode) to write CoffeeScript code. All text -- headings, paragraphs, lists, and so forth -- is ignored and treated as commentary by the compiler. 

However, indented code blocks, such as the code block below, are compiled into JavaScript.

  fooBar = ( foo ) -> foo + 1
  doSomething = ( fooBar ) -> alert fooBar
  if fooBar? doSomething

This functionality creates some interesting scenarios where a CoffeeScript file could be written in markdown and rendered on a webpage as a tutorial while simultaneously serving as a functional piece of program source code.

How to Get CoffeeScript

The CS compiler is typically installed and run using Node.js and CS is available as an NPM package. However, the project can also be downloaded or cloned from GitHub.

If you aren’t ready to install CoffeeScript quite yet, you can also give it a spin by heading to CoffeeScript.org and selecting the Try CoffeeScript tab.

This tab contains a browser-based CoffeeScript environment. Simply type CoffeeScript on the left and watch it compile into JavaScript in real time on the right.

CoffeeScript Resources

If you want to learn CS, the first thing to do is to learn JavaScript. It’s best to think of CS as a language designed to make JavaScript developers more productive, enable them to produce fewer errors, and produce JavaScript that adopts best practices.

Since CS compiles to standard JavaScript, debugging CS requires a solid foundation in JavaScript programming. In addition, your CS learning curve will be dramatically reduced if you already know JavaScript since you’ll be able to review the compiler output to understand what the CS code is doing.

With that caveat in mind, the following resources will help competent JavaScript developers get up and running with CS in short order.




CoffeeScript is a programming language with a concise syntax that minimizes the use of the keywords and operators and enables developers to write elegant code quickly.

In addition, after being compiled to standard JavaScript, CS code can be executed in any JavaScript-enabled environment.

JavaScript Summary

JavaScript Summary

JavaScript has a bad rap. But this is due to the fact that it is so useful and so used. Knowing JavaScript is very important. Although you can do much more with other languages, JavaScript remains the most useful language to know.

Hopefully with this introduction, you will be able to get up and running fast — creating interactive websites.

Further Reading

We have more guides, tutorials, and infographics related to coding and development:

  • F# Programming: find out about functional programming in the .NET framework.
  • Erlang Programming Introduction and Resources: an early functional language used for creating parallel code.
  • Swift Introduction and Resources: this is one of the newest C-like languages. The future of programming? Find out here!

What Code Should You Learn?

Confused about what programming language you should learn to code in? Check out our infographic, What Code Should You Learn?

It not only discusses different aspects of the languages, it answers important questions such as, “How much money will I make programming Java for a living?”

Text written by Jon Penland. Compiled and edited by Frank Moraes.

Need a great web host?
Save time and money with these top-rated web hosting deals.
Best for small businesses
Best for small businesses
Save 80%
Best hosting for new sites
Best hosting for new sites
Save 74%
Best WordPress hosting
Best WordPress hosting
Save 80%

Browse Web Hosting Provider Reviews