Over a million developers have joined DZone.

A quick overview of JavaScript

DZone's Guide to

A quick overview of JavaScript

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

tags: dev, javascript, jsguide

A quick overview of JavaScript

This post gives an overview of JavaScript that is as short as possible, but explains every major feature.

1. Preliminaries

You should start a JavaScript command line so that you can try out the examples.


    // a single-line comment (at the end of a line)
    A multi-line comment (anywhere)
Various statements:
    console.log("hello"); // print something
    var myvar = 7; // declare a variable

2. Values

In JavaScript, you work with the following values:
  • Booleans: true or false
  • Numbers: 1, 1.0 (same number, there is no distinction between integers and floating point numbers)
  • Strings: "abc", 'abc'
  • Functions:
        function twice(x) {
            return 2 * x;
        console.log(twice(4)); // 8
  • Objects: Objects store data in properties. Each property has a name and a value.
        var obj = {
            propName1: 123,
            propName2: "abc"
        obj.propName1 = 456;
        obj["propName1"] = 456; // same as previous statement
    Don’t mistake JavaScript objects for simple maps (dictionaries)! They can be used as maps from strings to values, but they are also real objects. Object literals are one of JavaScripts standout features: They allow you to directly create objects – no classes necessary. That is true object-orientation: You can start with concrete objects and introduce abstractions later, as needed. The abstraction for an object factory is a class in most mainstream languages, in JavaScript it is the constructor function (see below).
  • Arrays:
        var arr = [true, "abc", 123];
        console.log(arr[1]); // abc
        console.log(arr.length); // 3
  • undefined (see below)
  • null (see below)
Note: Both functions and arrays are also objects. For example, they can have properties:
    function foo() {}
    foo.bar = 123;

Primitives versus objects

Booleans, numbers, and strings are primitive types (if undefined and null are considered as having their own types then those types are primitive, too). You test for primitive types via typeof:
    > typeof 123
    > typeof true
    > typeof {}
All other types are object types. You test whether a value is an instance of a given type via instanceof:
    > 123 instanceof Object
    > {} instanceof Object
Note that, apart from typeof and instanceof, the difference between primitives and objects is practically unnoticeable in JavaScript.

Not having a value

JavaScript assigns undefined to variables that don’t have a value yet:
    > var x;
    > typeof x === "undefined"
    > typeof undeclaredVariable === "undefined"
Programmers should prefer null for this purpose:
    function someFunction(x) {
        // test for null:
        if (x === null) {
            // ...
Because both undefined and null are interpreted as false by an if statement, you can check for either value as follows:
    function hasAValue(x) {
        if (x) {
            // x is neither undefined nor null
            return "YES";
        } else {
            return "NO";
Beware: All of the following values are interpreted as false. If you check for a value via hasAValue() then, for example, 0 is not considered a value.
  • undefined
  • null
  • false
  • 0
  • ""
All other values are interpreted a true:
    > hasAValue(undefined)
    > hasAValue(null)
    > hasAValue(0)
    > hasAValue("")
    > hasAValue({})
    > hasAValue([])

3. Operators

Comparison operators:
    myvar === "abc"
    myvar !== "def"
    myvar >= 0
    myvar < 0
Boolean operators:
    0 <= a && a < arr.length // and
    a === "foo" || a === "bar"

4. Conditionals

    if (myvar === 3) {
        // then
    } else {
        // else
    switch (fruit) {
        case "banana":
            // ...
        case "apple":
            // ...
            // ...

5. Loops

    for (var i=0; i < arr.length; i++) {
    // Same as above:
    var i = 0;
    while (i < arr.length) {
    do {
        // ...
    } while(condition);
In all loops:
  • break leaves the loop.
  • continue starts a new loop iteration.

6. Functions and variable declarations

A variable always exists within the complete function, even if it is declared inside a block: JavaScript performs hoisting – any var declaration is always moved to the beginning of a function. The following is code where hoisting is performed (internally).
    function foo(x) {
        if (x > 100) {
            var tmp = x - 100;
Due to internal hoisting, the above code is equivalent to
    function foo(x) {
        var tmp;
        if (x > 100) {
            tmp = x - 100;

7. Array methods

Arrays have many methods. Especially the iteration methods are very useful, because you can avoid the for loop.
    [3, 4, 5].forEach(function (elem) {

8. Simple objects

The following is a simple object.
    var jane = {
        name: "Jane",
        // a method:
        sayHello: function () {
            return this.name + " says 'hello'"
    console.log(jane.sayHello()); // Jane says 'hello'
A method is a property whose value is a function. For example, sayHello() in the code above.

Main pitfall: every function has its own this

Problem: If a method m hands a function f to another method or function then f cannot access m’s this, because it has its own this. And that is unfortunate, because with JavaScript’s asynchronous programming style (on either the web or Node.js), one frequently uses callbacks. Example:
    function beep(callback) {
    var counter = {
        count: 0,
        beepAndInc: function () {
            var that = this;
            beep(function () {
                // the function shadows counter’s "this"
                // => must use "that"
Array iteration methods have a second parameter that allows you to specify a value that is to be used for this:
    var jane2 = {
        name: "Jane",
        logHello: function (friends) {
            friends.forEach(function (friend) {
                console.log(this.name + " says hello to " + friend)
            }, this);

9. Constructors

The closest equivalent to classes that JavaScript has are constructor functions, normal functions that are invoked via new:
    // The constructor sets up an instance
    function Person(name) {
        this.name = name;
    // The prototype property of the constructor holds an object whose
    // properties are shared between all instances (usually methods)
    Person.prototype.sayHello = function () {
        return this.name + " says 'hello'"
    var jane = new Person("Jane");
Extending a constructor is non-trivial. You can either do it yourself or use an API. Note that you don’t need extension (“subclassing”) as often in JavaScript, because you can add arbitrary properties to an instance.

10. Where to go from here

The 2ality blog has many posts on JavaScript (including ones on iterating over arrays, exception handling, primitives versus objects, etc.). The posts you should read next are: The Mozilla Development Network (MDN) has much good material on JavaScript. Especially recommended: More resources can be found on my page with JavaScript links.

Source: http://www.2ality.com/2011/10/javascript-overview.html

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}