Codepath

Basic JavaScript

Overview

"JavaScript® (often shortened to JS) is a lightweight, interpreted, object-oriented language with first-class functions, most known as the scripting language for Web pages, but used in many non-browser environments as well such as node.js or Apache CouchDB. It is a prototype-based, multi-paradigm scripting language that is dynamic, and supports object-oriented, imperative, and functional programming styles." -Mozilla Developer Network

This guide outlines a practical introduction to understanding JavaScript and a collection of industry-tested resources to further educate yourself deeper on concepts. From this point on the Mozilla Developer Network will be referred to as "MDN".

Basics

Syntax by Example

You ready? No? That's okay. Context is often the best way to start, so lets jump in with an example:

// White Space (including tabs) have little meaning
// beyond readability except within quotes

let workHours               // Declare variable with let, defaults to undefined
let playTime = false        // Initialize with a boolean primitive value
let myPersona = {           // Object literal creation, just key-values
    name: "Sudo",
    skills: [               // an Array literal assigned to an object property
        "JavaScript",
        "hacking",
        "nomad"
    ],
    awesomeness: 9
}

let updateWorkedHours = (hoursWorked) => {      // "Fat-arrow" anonymous function
    // Function closure scope nests like for/if/while loops
    // workHours is accessible since it's nested in the same closure
    if (workHours === undefined) {              
        workHours = 0
    }
    let newHours = workHours + hoursWorked      // local-scope variable
    return newHours                             // Return values
}

console.log(newHours)                           // throws an exception
                                                // newHours doesn't exist in this scope
console.log(updateWorkedHours(12))              // Logs "12" to stdout
console.log(updateWorkedHours(7))               // Logs "19" to stdout

function timeToPlay (decision) {                // A named function
    playTime = decision
    return playTime
}

// I'm ready to play after 19 hours
console.log(timeToPlay(true))                   // Logs "true" to stdout
console.log(playTime)                           // Logs "true" to stdout

// My awesomeness has now increased!
myPersona.awesomeness = 11                      // Access/set object properties

// I'm giving myself a new title...
myPersona.title = "Mr. Awesome"                 // Create and set "title" on myPersona

Phew. Now that you have some exposure, you can read through the MDN Guide for Grammar to get some depth of the keywords and topics shown in the example. For reference, the example showed the following topics: dynamic-typing, type literals, variable & function declaration, simple expression, and scope.

Loops, Expressions, & Conditionals

For the most part loops, expressions, and conditionals remain similar to other languages. See the MDN references (loops & expressions) for a full overview.

Truthy and Falsy Values

In JavaScript sometimes values that seem like they should evaluate one way actually evaluate another.

Values that evaluate to false

0;
'';         // an empty string
NaN;        // JavaScript's "not-a-number" primitive
null;
undefined;  // be careful -- undefined can be redefined!

Values that evaluate to true

'0';        // because it's a string
'a string';
[];         // an empty array
{};         // an empty object
1;          // any non-zero number

Any other values missed here will evaluate to true.

Iteratives

for...in statement

for (variable in object) {
  statements
}

For every property in an object what is the key. An in-depth available in the MDN reference.

for...of statement

Available in ECMAScript 6

for (variable of object) {
  statements
}

For every property of an iterable object, such as an Array, Map, or Set, what is the value. An in-depth available in the MDN reference.

Loops by Example

Lets step through the iterable skills Array embedded in our myPersona Object to demonstrate the difference between for...in and for...of:

let skills = [               // an Array literal
    "JavaScript",
    "hacking",
    "nomad",
]

console.log('\nfor loop:')  // a standard for-loop
for (let i = 0; i < skills.length; i++) {
    console.log(skills[i])  // Logs "JavaScript", "hacking", "nomad" to stdout
}

skills.greeting = "Hello"   // a non-iterable (not part of the Array) property

console.log('\nfor in loop:')
for (let k in skills) {     // k set to the property names in the object
   console.log(k)           // Logs "0", "1", "2", "greeting" to stdout
}

console.log('\nfor of loop:')
for (let v of skills) {     // v set to values of the properties in the iterable object
   console.log(v)           // Logs "JavaScript", "hacking", "nomad" to stdout
                            // Excludes the non-iterable property 'greeting'
}

If you try to use the complete myPersona Object from our previous example you'd get an error with for...of because a base object doesn't have the necessary Symbol.iterator implementation.

Data Structures & Types

As you'll see in the reference provided by MDN, there are a number of primitive types (Boolean, null, undefined, Number, String, and Symbol) and the all encompassing Object data type. For an in-depth take a moment to read the above reference. In this section, however, we will go a bit into Objects.

An Object is the base to create all other non-Primitive data structures (e.g., Arrays, Dates, Maps, Sets, and Functions (that's right, a Function is an Object)). Understanding Objects and how to effectively manipulate them will be quintissential to becoming a skilled JavaScript developer. We'll go into that further when we talk about Inheritance and Prototypes.

Objects by Example

You've probably heard of and even used JSON, JavaScript Object Notation, a universal data structure derived from the JavaScript Object for light-weight data transmission in the form of a key-value store by other languages. Here's a JSON refresher using my digital persona and then as an Object:

JSON

{
    "name": "Sudo",
    "skills": [
        "JavaScript",
        "hacking",
        "nomad"
    ],
    "awesomeness": 9,
    "alternatePersona": {
        "title": "Mr. Awesome"
    }
}

Pretty simple yeah? Now look at an Object:

Object

let myPersona =
{
    // Comments supported
    // No quotes necessary for keys
    name: "Sudo",
    skills: [
        "JavaScript",
        "hacking",
        "nomad"
    ],
    awesomeness: 9,
    alternatePersona: {
        title: "Mr. Awesome"
    },
    // Supports non-primitives beside Object/Array
    weaknesses: new Error('No weaknesses!'),
    // Object method shorthand
    upAwesomeness(levelup) {
        // "this" keyword refers to myPersona
        this.awesomeness += levelup
    },
    keys() {
        // lists myPersona's enumerable keys
        return Object.keys(this)
    }
}

console.log(myPersona.keys())
// ["name", "skills", "awesomeness", "alternatePersona", "weaknesses", "upAwesomeness", "keys"]
myPersona.upAwesomeness(2)
console.log(myPersona.awesomeness) // "11"

As you can see above an Object in JavaScript has the ability to perform actions through function properties (or methods), whereas methods or functions are unsupported in JSON.

Now that you have the general idea, time to learn more about Functions.

Function

There are three concepts to understand about JavaScript functions:

  • Functions inherit from Object
  • Functions have scope
  • Functions can be nested to create a closure

In this case, reviewing MDN's function guide (or EloquentJS) will give the best overview. You've already seen a few examples of these concepts now it's time to dive a bit deeper.

Operators

The last topic to cover in this practical primer are JavaScript operators. For reference, here's the complete list of JavaScript operators on MDN.

A common pitfall with equality operators in JavaScript is understanding why you should only use "strict" equality operator: === & !==. MDN has a great in-depth guide on equality with comparison charts, but here's a quick summary:

  • === - strict equality that also compares operand types
  • == - loose equality that coerces operands to the same type before checking

One minor caveat involves checking Number.NaN, where both of the following are false: NaN == NaN and NaN === NaN. For checking NaN, use [Object.is(a, b)]mdn-objectis instead.

Continued Learning

Now that you've read the quick primer, some great resources for tutorial-style learning of different aspects of JavaScript:

References & Guides

Tools

  • JSFiddle - Collaborate and a playground for code segments
  • ESLint - Enforce excellent code style or JSON

Keep Up to Date

Fork me on GitHub