Written by Harald Rudell

Why Use This Page?

This document is a quick reference to JavaScript usage.


JavaScript has six language types and several built-in objects. This brief demonstrates how to determine variable types, convert between types, and the usage of built-in objects. Please enjoy responsibly!

undefined type

typeof undef !== 'undefined' false Check if global variable undef has been defined without throwing exception
(function() {
  var f
  return typeof f
'undefined' The type of an in-scope unassigned variable is undefined

null type

(function(x) {
  return x == null
true Check if an in-scope variable is null or undefined
(function(x) {
  return x === null
false Check if an in-scope variable is null
typeof null 'object' A null variable has an object type, but no constructor property. Object property access on null or undefined values throws exception

boolean type

true values: numbers other than 0 and NaN, non-empty strings, any object.

!!' 5 ' true Convert to boolean using logical not
Boolean(~'5'.indexOf(6)) false Convert indexOf result to evaluate to the proper boolean
Boolean(undefined) false undefined converts to false
Boolean(null) false null converts to false
Boolean(0) false The number 0 converts to false
Boolean(NaN) false Not a number converts to false
Boolean(1) true Other numbers converts to true
Boolean('') false An empty string converts to false
Boolean('0') true Other strings converts to true
Boolean(' ') true
Boolean({}) true Any Object converts to true
Boolean(Object(false)) true
(function() {
  var f = true
  return typeof f === 'boolean'
true Check if a variable has a primitive boolean value
(function() {
  var f = true
  return f != null && typeof f.valueOf() === 'boolean'
true Check if any value is a boolean

number type

There is no integer type.

+' 5 ' 5 Convert to number using plus
~~-3.14 -3 Convert to integer using two tilde. Rounds towards 0.
Number(undefined) NaN undefined converts to NaN
Number(null) 0 null converts to 0
Number(false) 0 false converts to 0
Number(true) 1 true converts to 1
Number(' ') 0 An empty or white space string converts to 0
Number(' 45 ') 45 numeric strings convert allowing for leading and trailing white space
Number('abc') NaN Non-numeric strings convert to NaN
Number({}) NaN Non-Numeric objects convert to NaN
Number(Object(7)) 7 Primitive objects converts to corresponding numbers
(function() {
  var f = 1
  return typeof f === 'number'
true Check if a variable has a primitive number value
(function() {
  var f = 1
  return f != null && typeof f.valueOf() === 'number'
true Check if any value is Number

string type

String(undefined) 'undefined' Convert to string
String(null) 'null'
String(false) 'false'
String(0) '0'
String(NaN) 'NaN'
String({}) '[object Object]' Regular objects become an implementation dependent string
String(Object(true)) 'true' Primitive-based objects converts to primitive string
(function() {
  var f = ''
  return typeof f === 'string'
true Check if a variable has a primitive string value
(function() {
  var f = ''
  return f != null && typeof f.valueOf() === 'string'
true Check if any value is string value

object type

(({})).toString() '[object Object]' How objects are displayed is implementation specific. {} is an empty object. Parenthesis required to distinguish object initializer from block.
typeof Object(false) === 'boolean' false Primitives can become wrapped as objects. This is not useful, but some JavaScript functions do this
typeof Object(false).valueOf() === 'boolean' true Unwrap a primitive object
(function(f) {
  return f && f.constructor && || 'none'
'Array' Get name of an object's constructor
new SyntaxError instanceof Error true Determine if an object extends another object.
(({})).constructor === Object true Determine if a value is an Object object (eg. not an Array)
typeof ({}) === 'object' true Check if a value is of object type.


Except for objects and NaN, strict equality means same type and value. Values of different types are converted to Number before testing

undefined == null true null and undefined tests as being the same value only to each other
false == 0 true Boolean and String are first converted to Number, so for numbers, false equals only 0
true == ' 1 ' true for numbers, true equals only 1, here as a numeric string
false == ' ' true for strings, false equals only an empty or whitespace string (converts to 0)
true == Object(' 1 ') true Boolean are converted to Number, Objects converted to primitive, then Number
NaN == NaN false NaN never equals anything
NaN === NaN false NaN is not identical to anything
'' == '' true Strings are equal if they have the same length and characters
25 == ' 25 ' true Numbers equal strings that can have leading and trailing whitespace
({}) == {} false Objects are equal only if they refer to the same object
undefined === undefined true Except for objects and NaN, strict equality means same type and value

Global Object

encodeUri decodeUri

NaN NaN Not a number property
Infinity Infinity Infitity property
undefined undefined Undefined property
eval('2 + 2') 4 Eval function
parseInt('2.5 trailing garbage') 2 string to integer
parseFloat('2.5 trailing garabage') 2.5 string to float
isNaN(NaN) true
isFinite(NaN) false
encodeURIComponent('%&') '%25%26'
decodeURIComponent('%23') '#'

Object Objects

getPrototypeOf create defineProperty defineProperties seal freeze preventExtensions isSealed isFrozen isExtensible toLocaleString isPrototypeOf propertyIsEnumerable

  a: 1,
  b: 2
['a', 'b'] Get an array of object properties, similar to for(var property in object)
Object.getOwnPropertyNames([ 5 ]) ['0', 'length'] Get object properties including non-enumerable properties, here a length property
  a: 1,
  b: 2
true Check if an object has a property defined ignoring the prototype chain
  1: 2
}, 1)
{ value: 2, writable: true, enumerable: true, configurable: true } Get property descriptor
(function() {
  var obj = {}
  obj.__defineGetter__('x', function() {
    return 7
  return obj.x
7 Getters and setters can execute code on property access
(new function X() {}) 'X' Get the name of an object's constructor
  a: 1,
  b: 2
'{"a":1,"b":2}' Get object state

Function Objects

(function() {})() undefined The value of a function not returning a value is undefined (leading parenthesis required to indicate expression, not statement)
(function(arg) {
  return arg
undefined A function argument not provided has the value undefined
(function(arg) {
  return JSON.stringify(arguments)
'{"0":1}' Inside a function there is a variable arguments containing a value map. arguments is an object, not an Array
(function(arg) {
[1] Convert arguments to Array
(function theName() {
  return || 'anonymous'
'theName' Get the name of the executing function
(function theName() {}).name 'theName' Get the function name of a function value
(function f(x) {

'function f(x) {;}' Get a function's declaration
(function(args) {
  return this
}).apply(5, [])
Object(5) invoke a function with a set this value and an array of arguments
(function(arg) {
  return arg
}).call(5, 1)
1 invoke a function with a set this value and a list of arguments
(function(arg) {
  return this[arg]
  field: 3
}, 'field')()
3 bind creates a function alias where this and arguments can be intercepted, here this is set to an object and arg becomes the string "field"
(function(arg1, arg2) {}).length 2 length is typical number of arguments
typeof (function() {}) === 'function' true Check if a value is a function

Array Objects


typeof [] 'object' Note: Arrays have object type
[ 1, 2 ].toString() '1,2' Get Array state
[ 1 ].concat([ 2 ], [ 3 ]).toString() '1,2,3' Array concatenation, one array level of concat arguemnts is reolved
(function(a) {
  a.push.apply(a, [ 3, 4 ])
  return a
})([ 1, 2 ]).toString()
'1,2,3,4' Append to Array
[ 1, 2, 3 ].join('z') '1z2z3' Array as a string
[ 1, 2, 3 ].pop() 3 Remove last element from array
[ 1 ].push(2) 2 append element to array, returns the appended value
[ 1, 2 ].reverse() [2, 1] Reverse array
[ 1, 2 ].shift() 1 Remove first element from array
[ 5, 6, 7, 8 ].slice(2, 3) [7] Extract sub-array
[ 1 ].slice() [1] Clone array
[ 1, 3, 2 ].sort() [1, 2, 3] Sort array
[ 7, 8, 9 ].splice(1, 2, 4, 5) [8, 9] At index 1, delete 2 items and replace with values 4 and 5, return deleted items
[ 1 ].unshift(3) 2 Insert entry at beginning of array, return new length
[ 2, 2, 3 ].indexOf(2, 1) 1 Search for entry starting at position, -1 means not found
[ 3, 3, 3 ].lastIndexOf(3) 2 Search for last occurrence of value
[ 1, 2 ].every(function(value, index, object) {
  return true
true Iterate through array until false is returned. true if false was never returned
[ 1, 2 ].some(function(value, index, object) {
  return true
true Iterate through array until true is returned. true if true was returned
[ 1, 2 ].forEach(function(value, index, object) {}) undefined Iterate through all array items
[ 1, 2 ].map(function(value, index, object) {
  return 5 - value
[4, 3] Iterate through array return array of return values
[ 1, 2 ].filter(function(value, index, object) {
  return value < 2
[1] Iterate through array return array of values when callback returned true
[ 1, 2 ].reduce(function(reduce, value, index, object) {
  return reduce + value
3 Iterate through array accumulating a value
Array.isArray([ 1 ]) true Test if a value is an Array

String Objects

charCodeAt concat localeCompare toLocaleLowerCase toLocaleUpperCase fromCharCode

'AbC'.charAt(1) 'b'
'A'.concat('b') 'Ab'
'abbc'.indexOf('b') 1
'abbc'.lastIndexOf('b') 2
'abbc'.match(/a/) ['a', index: 0, input: 'abbc']
'abc'.replace('b', 'c') 'acc'
'abbc'.search(/a/) 0
'abbc'.slice(1, 2) 'b'
'abbc'.split('b') ['a', '', 'c']
'abbc'.substring(1, 2) 'b'
'AbC'.toLowerCase() 'abc'
'abbc'.toUpperCase() 'ABBC'
'abbc'.trim() 'abbc'
'abbc'.length 4

Boolean Objects


Number Objects


3 / 2 1.5 There is no integer division
Math.floor(3 / 2) 1 integer division result
3.14.toFixed(1) '3.1' round fraction digits
3.14.toExponential(1) '3.1e+0' round fraction digits

The Math Object

E LN10 LN2 LOG2E LOG10E PI SQRT1_2 SQRT2 acos asin atan atan2 cos sin tan

Math.abs(-1) 1 Absolute value
Math.ceil(-3.14) -3 Round towards positive infinity
Math.exp(1) 2.718281828459045 e powers
Math.floor(-3.14) -4 Round towards negative infinity
Math.max(1, 2, 3) 3 Max value
Math.min(1, 2, 3) 1 Min value
Math.pow(2, 3) 8 Power
Math.random() 0.843700736388945 >= 0, <1, typically 30 significant binary digits (9 decimal digits)
Math.round(-1.5) -1 round
Math.sqrt(9) 3 Square root

Date Object

Date constructor takes year > 99, month 0..11, date 1.., hours, minutes, seconds, ms. Day is Sunday.. 0-6. MakeTime MakeDay MakeDate TimeClip parse toDateString toTimeString toLocaleString toLocaleDateString toLocaleTimeString get/set-/UTC-FullYear/Month/Date/Day/Hours/Minutes/Seconds/Milliseconds toUTCString toJSON

Date() 'Wed Aug 15 2018 13:08:19 GMT+0000 (UTC)' String representation of now 1534338500000 Time value representation of now (unit ms, 1000 * Unix timestamp)
new Date Date(1534338500003) Date object of now, can take time value argument
(new Date).getTime() 1534338500025 Convert Date to time value
(new Date).getTimezoneOffset() 0 Minutes to add to localtime to get utc
new Date(Date.UTC(1970, 0)) Date(0) Create date using UTC time zone
(new Date).toISOString() '2018-08-15T13:08:20.074Z' The only string representation with a known format

RegExp Objects

Regular expressions are used with properties test or exec or string functions search, replace, match and split. alternative: | assertions: ^$\b\B(?=)(?!) atom: .()(?:) non-atom characters: ^$\.*+?()[]{}|, atom quantifiers: *+?{n}{n,}{n,n} character classes: [] [^] escapes: \tnvfr \000 \x00 \u0000 \character \c-controlLetter \d\D 0-9, \s\S white space line terminator, \w\W a-zA-Z0-9_, modifiers: g global, m multiline, i ignore case.

/a/g.exec('baac') ['a', index: 1, input: 'baac'] Look for a. The result is an array with the matched element and two properties
/\b[sS]ales(\W|$)/.test('Sales Director') true look for sales or Sales as a separate word
'@joe and @jim was here'.replace(/(( )@|^@)(\w{1,15})/ig, '$2<@$3>') '<@joe> and <@jim> was here' Finding twitter names but not email addresses

Error Objects

EvalError RangeError ReferenceError SyntaxError TypeError ParseError URIError

SyntaxError('que').toString() 'SyntaxError: que' Specified printout
SyntaxError('que').message 'que' Error can have implementation properties such as stack errno code path
new SyntaxError instanceof Error true Check for Error

The JSON Object

parse(text, reviver) stringify(value, replacer, space)

  a: 1
JSON.parse('{ 'a': 1}') { a: 1 }

Operator Precedence

1. (...) Grouping
function identifier(...) {...} Function expression
memberExpression[...] Bracket property access
memberExpression.identifier Dot property access
new memberExpression(...) new
Left to right
2. new memberExpression new
memberExpression(...) Function call
Left to right
3. ++ Postfix increment
-- Postfix decrement
4. ++ Prefix increment
-- Prefix decrement
+ Unary plus
- Unary negation
! Logical not
~ Bitwise not
Right to left
5. / Division
* Multiplication
% Remainder
Left to right
6. + Addition
+ String concatenation
- Subtraction
Left to right
7. >> Unsigned right shift
<< Left shift
Left to right
8. < Less-than
<= Less-than-or-equal
> Greater-than
>= Greater-than-or-equal
instanceof Instance of
in In
9. !== Strict does-not-euqals
=== Strict equals
!= Does-not-equals
== Equals
10. & Bitwise and
11. ^ Bitwise xor
12. | Bitwise or
13. && Logical and
14. || Logical or
15. ?: Conditional
16. = Assignment
*= Compound multiplication assignment
/= Compound division assignment
%= Compound remainder assignment
+= Compound addition assignment
-= Compound subtraction assignment
<<= Compound left shift assignment
>>= Compound right shift assignment
>>>= Compound unsigned right shift assignment
&= Compound bitwise and assignment
^= Compound bitwise xor assignment
|= Compound bitwise or assignment
17. , Comma

Written by Harald Rudell