Javascript Refresher Cheat Sheet

JavaScript Cheat Sheet

This is not meant to be a comprehensive reference. Rather, it’s meant as a refresher for me to refer to when I’ve not written any JS for a few months and need to remember all the quirks and gotchas. For folks looking for more coherent information about Javascript, I highly recommend any and all of the books linked to the at the bottom of this page. If you want a free, tutorial-style introduction to Javascript, then Eloquent Javascript is a nice place to start.

Basic Syntax & Grammar

Statements

  • C-like, except braces create new blocks but not new scopes. This is counter-intuitive; just remember that function definitions create scope, but braces do not.
  • "var" keyword creates a local variable
  • switch, while, for, and do have optional label prefix (for break)
  • False values: false, null, undefined, '', 0, NaN
  • "for" statement has C-style "for (init; cond; incr)" syntax and "for VAR in LIST" syntax

Expressions

  • == is a coercing comparison, i.e. "5" == 5
  • Type & value equality is checked via === and !==
  • delete is an operator and forms an expression (that generally returns true, even if the property doesn’t exist, or its argument is a built-in like an integer)
  • typeof(X); returns "number", "string", "boolean", "undefined", "function", "object"
  • typeof(array) or null is object

Numbers

  • Numbers are all 64-bit floats; use Math.floor() to get an integer
  • NaN, Infinity are defined but are not reserved, so can be overwritten
  • You can use parseInt() to convert string to number. BE CAREFUL: if the numeric string starts with a ‘0’, JS will interpret as octal, and will stop processing the string at the first ‘8’ or ‘9’. So parseInt('08')=>0 and parseInt('012383')==parseInt('0123'). So, always include the radix: parseInt('08',10).
  • Alternatively, use the Number() constructor. (However, this accepts floats.)

Strings

  • All strings are 16-bit unicode and immutable
  • Use strings like "u0041" to address unicode code points
  • Strings and arrays have .length property
  • Methods:
    • charAt, charCodeAt, fromCharCode, toLowerCase, toUpperCase
    • concat, slice, split(separator, limit), substring, indexOf, lastIndexOf
    • match(regexp) – can return array of all matches
    • search(regexp) – like indexOf on a regexp
    • replace

Date

  • stored as milliseconds since UNIX epoch
  • parse(str) – browser dependent, but typically supported formats are: MM/DD/YYYY; Monthname Date, YYYY; and unix timestamp
  • Date() returns current time
  • UTC(month,day,h,m,s,ms) – creates Date from given values; month and day are zero-indexed
  • Date() also accepts same args as UTC(), but interprets as local time
  • browsers tend to replace out-of-range values (e.g. Jan 32) with something useful

RegExp

  • Perl-style syntax: var myRE = /pattern/flags
  • flags: g=global, i=case insensitive, m=multi-line matching
  • (Since I don’t plan on using REs very much, I’m omitting quite a bit of info)

Functions

  • Function definitions can be either expressions or statements
  • In a function expression, the function name is optional and is used for recursion within the statement block; it does not leak to the outer scope. For the function to be referenced, it should be assigned to a name.
  • A function statement is roughly equivalent to a function expression, except that the function definition is compiled and the function name gets defined before execution of the rest of the code in the scope. So function outer() { inner.blah = 12; function inner() {}; } is valid.
  • Functions are first-class objects whose __proto__ is Function.prototype, and can have methods.
  • Functions always return a value; defaults to "undefined"
  • Two automatic variables in local scope: this and arguments
  • A function nested within another has access to outer context, except for the "this" special variable. (See This, below.)
  • All user-defined functions get a .prototype attribute, which then has a .constructor property referring back to the function. This is for using the function as a constructor. (See Objects, below)
  • Grammar quirk: You cannot use a bare function expression as the first thing in a statement because JS will interpret it as a function statement. Instead, wrap the entire function expression in parentheses.

Arguments

  • The "arguments" special variable is not really an array, but rather an array-like object (an Arguments object) with a .length property, and a .callee property
  • The argument list in the function declaration is matched against provided arguments at invocation; mismatches are not an exception, and unsatisfied parameters are merely "undefined" in the local scope
  • For varargs, iterate through the "arguments" array, which contains all arguments passed in
  • Weird: arguments array elements and local variables from named function parameters are aliases. Assigning to an element of the arguments array will change the value of the local named variable!
  • The .callee refers to the current function, and is useful for recursing in anonymous functions.

This

  • The value of the special variable "this" in a function’s scope depends on how the method was called (aka the "invocation mechanism")
  • These rules are easy to remember but they are kind of fucked up.
  • Method: When function is stored as a property on some object and is invoked in an expression containing a refinement (. or []), "this" is bound to the object. This is tricky: there is no such thing as a bound method; the interpreter binds "this" based on whether or not the expression contains a refinement!
  • Function: When a function is not the property of object, "this" is bound to global object, NOT the enclosing scope’s "this". By convention, people assign "that = this" in the enclosing scope for nested functions.
  • Apply: called as a method of the function; caller specifies the value of "this" as the first argument, and passes the function arguments as a single list (for .apply()) or as additional arguments (for .call()). If the value of the "this" parameter is not an object, then "this" inside the function is the global object.
  • Constructor (see under Objects, below)

Objects

Literals

  • Object literals are created like dicts in Python with { name:value }; nesting is permitted
  • Property name can be empty string
  • Quotes around name are optional if it’s a legal JS identifier
  • Property retrieval is either via [] or . (if valid JS identifier)
  • Non-existent properties return undefined
  • Attribute lookup with a default value: myobject["prop"] || "default value"

Prototypes

  • All objects have an internal [[Prototype]] object from which it inherits properties. This is not the same as its .prototype attribute! ([[Prototype]] can usually be accessed via __proto__.)
  • Any function can serve as a constructor, by calling it via "new func(…)"
  • "delete" removes properties from an object, but does not affect the prototype
  • Object literals inherit from Object.prototype. Chasing the chain of [[Prototype]] all the way up will lead to Object.prototype. Object.prototype.__proto__ is null.
  • use hasOwnProperty() to determine if attribute is on the instance or inherited
  • The "for/in" statement loops over all properties (including functions and inherited ones) in random order
  • Useful read: http://joost.zeekat.nl/constructors-considered-mildly-confusing.html
  • The "OBJ instanceof CTOR" operator checks that CTOR.prototype is in the chain of OBJ.__proto__. It is possible to get counterintuitive behavior by assigning to CTOR.prototype after instantiating some objects.

Constructors

  • When function is invoked with "new", the new object is created with a [[Prototype]] equal to the function’s .prototype member.
  • This is not the same thing as the function’s [[Prototype]] (which is Function.prototype).
  • this in the function scope will be bound to the new object.
  • If the function does not return an object of some sort, then the new object is returned (i.e. equivalent to "return this;")
  • By convention, constructor functions names start with a capital letter

Idioms

  • JS is a very function-oriented language, because functions are basically blocks.
  • Closures are used a lot.
  • All members, etc. are public. A pattern for creating private members is to create a factory function that creates methods, etc. in local scope and then returns a constructed object. There are several different ways to do this but the overall pattern is to hide private variables in the closure.

Arrays

  • Like a python list: heterogenous
  • Derives from Array.prototype instead of Object.prototype
  • Converts array subscripts into strings that become properties to look up.
  • The .length property
    • NOT NECESSARILY THE ACTUAL LENGTH – the largest integer property name in the array, plus one.
    • If you set an integer attribute that is >= current length (and less than 32bit maxint), then length of array is updated to be the subscript+1. #wtf
    • Not a limit: add more elements, and .length grows
    • Not a read-only attribute: set it larger, and array fills with undefineds; set it smaller, and it drops elements off the end
    • Adding non-integral properties to an array does not affect its length!
  • delete operator can remove elements from the middle of the array; remaining elements do not shift down
    • use .splice() methods
  • The (for in) statement will iterate over all the properties of the array, but produces them out of order; use for (;;) statement instead
  • typeof() on an array instance will actually return "object"
  • “Javascript: The Good Parts” recommends that testing for arrays is most robustly done by calling .toString() on the prototype of the value and checking for the string ‘[object Array]’. #wtf
  • built-in array methods:
    • concat(item,…) – if item is an array, then extends(), otherwise appends()
    • slice() – the right way to pop from the middle of the array
    • splice() – slice() and insert items
    • join(separator) – makes string
    • pop, push
    • shift/unshift – pops/pushes from the front
    • sort(cmpfcn) – in-place sort but stringifies the values; DO NOT USE ON NUMERICAL ARRAYS
    • reverse – reverse in-place

Style Notes

  • JS will automatically insert semicolons. This WTF feature has a few ramifications on style:
    • If you have to break up a line, do it after a comma or binary operator
    • Don’t separate the return keyword and the value to be returned by a newline.
    • If you return an object literal, put opening brace on the same line as the return.
  • Avoid using block comments /* */ because the "*/" characters can appear in a regexp and inadvertently terminate your comment.
  • JS allows variables to be declared after they are used. Don’t do this.

Gotchas

  • typeof(null) and typeof(array) are both "object"
  • A big pile of words are reserved even though they are not used in the language. The most annoying ones are probably: debugger, default, export, native, package
  • The plus operator will coerce and concat. So "5"+3 => "53", while "5"-3 => 2.
  • Some operations return null on error or missing, others return undefined. Double-check the actual error values for particular operations.
  • Bitwise operations convert floats into 32-bit ints, perform the bitwise ops, and then convert back into Number. Don’t even bother with these.

Resources

Pages & Projects

For someone new to the Javascript ecosystem, the plethora of cleverly-named toolkits can be overwhelming. Some of the most common/well known ones are described below, along with what they do.

One thought on “Javascript Refresher Cheat Sheet

  1. michaelveloz says:

    Thanks for taking the time to publish this. I’m coming back to JS after having been in C# and Python for a couple years.. needed something to get my brain re-seeded :)

Leave a reply to michaelveloz Cancel reply