JavaScript Notes and Examples

JS at-a-glance

You can try most of this right in the repl (in your browser’s JS console).

Basics

Literals:

Types: Use the typeof operator to find the type of something (ex., number, string, boolean, object) — reported as a string.

There’s no ints and floats — they’re all just numbers. And there’s no separate character type — they’re all just strings.

Incidentally,

Note: In general, JS will automatically use type coercion with wild abandon in an effort to accept anything you throw at it.

Operators: JS supports the usual unary, binary, and ternary operators. This includes ++, --, and the ones like +=, -=, *=, etc. Some notes:

false, 0, "" (empty string), NaN, null, and undefined are all falsey. Everything else is truthy. (For more, see this sitepoint article.)

The logical and conditional operators short-circuit, as expected.

Consider: foo || bar || baz || moo and foo && bar && baz && moo

You might think of the || operator as “hopeful”. It’s always looking to return a truthy value to you; it keeps checking each one, hoping to find a truthy one. It’s an optimist. :)

The && operator is never happy though. It’s always looking for a falsey value to return to you. Alas, nothing’s ever good enough for &&. It keeps expecting one of them to be falsey so it can return that. It’s a pessimist! ;)

Although not always strictly required, always end statements with a semicolon.

let and const give you variables and constants (collectively, “bindings”) with lexical scope that work as you’d expect. (The old var gets you either global or function scope.) const means that you can’t change to which object the name refers, but you can mutate the object (if the object is mutable).

The collection of all current bindings is called “the environment”.

Control flow

Strings

Arrays

Objects

todo {}

Functions

If you leave out the return, or have only a bare return, the function returns undefined.

Just as you might expect, you can define functions lexically-scoped inside of other functions.

JS doesn’t check function arity. If you pass too many args, extras get ignored. If you pass too few, the ones you omit are assigned undefined.

Arrow functions go like:

Numbers and Math

Number.isNaN()
Math.max()
Math.min()