A selection of JavaScript snippets for your quick perusal when you are dashing between billion-dollar ideas.
blahA plain word refers to a variable in the current environment.
"blah"A quoted word is a string, a value containing piece of text.
12A number value.
trueBoolean (yes/no) value. true for yes, false for no.
a + bBinary operator applied to two values. + to add, - to subtract, * to multiply, / to divide.
(a + b) * cParenthesis for explicit grouping.
a < b: Comparison operators ==, != (not equal), <, >, <= (less or equal), >=.
a = bAssignment, set variable a to value b. Not to be confused with == comparison. a += b is a shorthand for a = a + b, also for -= etc.
a && bLogical operators — && for AND, || for OR.
-aUnary (one-operand) operator. - to negate (make negative)
!aUnary (one-operand) operator. ! for boolean negation.
!!aUsing two ! operators to work out if something is Truthey.
a[b]Subscript, fetch the field named by b from value a.
a.xShorthand for a["x"].
a(b)Function call. Call the function value a with b as argument. Zero or more argument expressions can be given, separated by spaces. a(1, 2, 3, 4)
a.x(b)Method call. Call the function found in field x of value a, and pass a as the this argument.
[1, 2, 3, 4]Array value with zero or more elements.
{a: 1, b: 2}Object value with zero or more name: value field definitions.
function(arg1, arg2) {
/* ... body ... */
}Function value. Zero or more argument names. Any statements may appear in body.
a;Any expression, followed by a semicolon, is a statement.
var a = b;Variable definition. The variable with name a is defined and given value b. Value is optional. var a; sets a to undefined.
function foo(arg1, arg2) {
// code
}Function definition. Defines variable foo to have a function value. Zero or more arguments, any statements may appear in body.
if (a) {
// code if expression true
} else {
// code if expression false
}Conditional statement. If value a is true, the first statement, otherwise the else statement executes. Else part may be left off.
if (a) {
// code
} else if (b) {
// code
} else {
// code
}Chaining conditional expressions.
while (a) {
// code to execute in the loop
}A while loop. The loop body statement will be executed as long as a produces a true value.
for (var a = 0; a < 10; a++) {
// code
}Example for-loop statement. var a = 1 initializes the loop, a < 10 checks whether it has ended yet, and a++ moves to the next step by incrementing the counter a.
return a;Only valid inside a function or after a control flow struction like if. Returns value a as the result of the function call.
documentAn object-orientated representation of the HTML that was read by the browser.
var greeting = document.getElementById("hello")Search for an element with the id of hello in the document and assign to the variable greeting (can be named anything.
var divs = document.getElementsByTagName("div")Search for all div tags within the document using the html tag.