JavaScript CheatSheet
General
- Glossary: MDN Glossary
- JavaScript guides: MDN JavaScript/Guide
- JavaScript reference: MDN JavaScript/Reference
- JavaScript statements and declarations: MDN JavaScript/Reference/Statements
- JavaScript expressions and operators: MDN JavaScript/Reference/Operators
- JavaScript standard built-in objects: MDN JavaScript/Reference/Global_Objects
- Web APIs: MDN Web/API
Run JS Code
Run JS Code in the Browser with Chrome Dev Tools
Fn+F12 | Cmd+Optn+J (Mac) Ctrl+Shift+J (Win) | Rt-click page > Inspect > Console
Run JS code in the CLI with Node.js
Open Command Line Interface (CLI) > node > enter your JS code.
Close node: Ctrl+D | .exit
Close node: Ctrl+D | .exit
Run JS file from the CLI with Node.js
Open CLI in the file's directory > node filename (.js extension assumed)Syntax
Style Guides: Google | AirBnB
Whitespace: Spaces, tabs, and newline characters.
JS ignores extra spaces. Space characters and indentation are used to make the code more readable. Indent 2 spaces (or soft tabs). Don't use hard tabs.
Comments:
Semicolons: Put semicolons at the end of each statement. This includes variable declarations/assignments, function expressions, function call statements, ternary statements, event listener methods, etc.
Blocks (e.g., functions, if statements, for and while loops, classes) contain one or more statements surrounded by curly braces. Use semicolons after the statements inside the blocks but not after the closing curly brace.
Trailing commas: You can have commas at the end of the last item in arrays, object literals, and function arguments (since ES2017). Style guides recommend using training commas on objects/arrays when there is a line break between the final item and the closing brace/bracket. Note: JSON does not allow trailing commas.
Code Blocks: Blocks are a sequence of statements that execute together. Includes functions, loops, if statements, etc. They are enclosed in curly braces { } not followed by a semicolon. Curly braces are optional for single statement code blocks, but should still be used except in short one line if statements.
Double vs single quotes: You can use either. Style guides recommend single quotes for string literals.
Whitespace: Spaces, tabs, and newline characters.
JS ignores extra spaces. Space characters and indentation are used to make the code more readable. Indent 2 spaces (or soft tabs). Don't use hard tabs.
Comments:
// single line
/* multiple lines */
behave like whitespace and are discarded during script execution.Semicolons: Put semicolons at the end of each statement. This includes variable declarations/assignments, function expressions, function call statements, ternary statements, event listener methods, etc.
Blocks (e.g., functions, if statements, for and while loops, classes) contain one or more statements surrounded by curly braces. Use semicolons after the statements inside the blocks but not after the closing curly brace.
Trailing commas: You can have commas at the end of the last item in arrays, object literals, and function arguments (since ES2017). Style guides recommend using training commas on objects/arrays when there is a line break between the final item and the closing brace/bracket. Note: JSON does not allow trailing commas.
Code Blocks: Blocks are a sequence of statements that execute together. Includes functions, loops, if statements, etc. They are enclosed in curly braces { } not followed by a semicolon. Curly braces are optional for single statement code blocks, but should still be used except in short one line if statements.
Double vs single quotes: You can use either. Style guides recommend single quotes for string literals.
Semicolon automatic insertion, line length:
- The source text of JS script gets scanned from left to right and converted into a sequence of input elements (tokens, control characters, line terminators, comments, or whitespace).
- Semicolon automatic insertion: JS will automatically insert a semicolon at the end of a line if it can't parse the code without a semicolon. This makes using semicolons technically optional. However, Both Google and AirBnB's style guides require them, and there is a minor (probably insignificant) hit to performance to have JS automatically insert it.
- Line length: Google recommends a maximum line length of 80 characters. AirBnB recommends 100.
Reserved Keywords
await, break, case, catch, class, const, continue, debugger, default, delete, do, else, enum, export, extends, false, finally, for, function, if, implements, import, in, instanceof, interface, let, new, null, package, private, protected, public, return, super, switch, static, this, throw, try, true, typeof, var, void, while, with, yield
Data Types
JS has 8 data types: MDN JavaScript/Data_structures
There are 7 primitive data types. Primitives are not objects and are immutable (cannot be changed).
Primitives: Sting, Number, BigInt (ES2020), Boolean, Null, Undefined, Symbol (ES2015).
The 8th data type is objects. Objects include Objects (the Object prototype), Functions, Arrays, Date, RegExp, Promises, etc. Even string, number, and boolean primitives can be created as objects using the String, Number, Boolean constructors.
There are 7 primitive data types. Primitives are not objects and are immutable (cannot be changed).
Primitives: Sting, Number, BigInt (ES2020), Boolean, Null, Undefined, Symbol (ES2015).
The 8th data type is objects. Objects include Objects (the Object prototype), Functions, Arrays, Date, RegExp, Promises, etc. Even string, number, and boolean primitives can be created as objects using the String, Number, Boolean constructors.
More details
- Primitives:
- Most of the time, a primitive value is represented directly at the lowest level of the language implementation. So they are fast and efficient.
- Primitives are immutable. When a variable is assigned to a primitive value, it can be reassigned to a new primitive, but the original value is not changed. Rather it is no longer attached to anything and gets garbage collected.
let str = 'Hello';str = 'hi'; // "hi" is a new string assigned to str. The "Hello" string primitive gets garbage collected.
- Primitives have no methods or properties directly. Instead:
- JavaScript determines the value's data type. The value can then access methods on the associated prototype. String primitives can access String.prototype methods. Number primitives can access Number.prototype methods, Boolean primitives can access Boolean.prototype methods.
- When a method from the prototype is called on a primitive value, JavaScript temporarily auto-boxes the value into a wrapper object, then calls the method from the prototype on it.
- Example:
"hello".toUpperCase()
- "hello" has quotes around it so JavaScript parses it as a string data type.
- JavaScript auto-boxes the value into a wrapper object and gives it access to properties and methods from String.prototype.
- The String.prototype.toUpperCase method is called on the temporary object, and returns the string primitive
- Functions are regular objects with the additional capability of being callable.
- JS does not distinguish between integer and floating point numbers. All numbers are represented as floating point numbers.
- Null and undefined are special values. Variables are assigned a value of undefined until they are initialized. Null is used to assign a variable to nothing. let name; name; // undefined. let name = null; name; // null.
- BigInt: Is the newest primitive as of ES2020. It provides a way to represent whole numbers larger than 2**53 - 1, which is the largest number JavaScript can reliably represent with the Number primitive.
- JS is referred to as a loosely typed and dynamic language. This means variables are not directly associated with a data type. Variable x can be assigned to a string then reassigned to a number or object.
typeof operator
typeof operand;
//Returns a string indicating the type of the evaluated operand.Possible return vals: 'string', 'number', 'boolean', 'symbol', 'undefined', 'object', 'function'.
Examples
Undefined examples:
Boolean examples:
Number examples:
String examples:
Function examples:
Functions are objects, but the datatype operator returns 'function'.
Object examples:
Null example:
Null is a JS data type, but the datatype operator returns 'object' for null values.
typeof undefined;
// Returns 'undefined'.typeof x;
// If variable x is not defined, returns 'undefined'.let y; typeof y;
// If no value was assigned to the variable, its type is 'undefined'.Boolean examples:
typeof true;
// Returns 'boolean'.const bool = false; typeof bool;
// Evaluates the variable value. Returns 'boolean'.typeof 5 > 4;
// Expression evaluates to true. Returns 'boolean'.Number examples:
typeof 7;
// Returns 'number'.const num = -5; typeof num;
// Evaluates the variable value. Returns 'number'.typeof (3 + 4);
// Expression evaluates to 7. Returns 'number'.typeof NaN;
// NaN is a symbolic value representing non-number within the Number data type. Returns 'number'. Same for infinity and -infinity.String examples:
typeof 'hello';
// Returns 'string'.const str = 'world'; typeof str;
// Evaluates the variable value. Returns 'string'.typeof '';
// Empty strings are still strings. Returns 'string'.typeof '7';
// Numbers or booleans in quotes are strings. Returns 'string'.Function examples:
Functions are objects, but the datatype operator returns 'function'.
typeof function() {}
// Returns 'function'.const fn = (x) => x * 2; typeof fn;
// Evaluates the variable value. Returns 'function'.const fn = (x) => x * 2; typeof fn(5);
// Returns 'number', the datatype of the function's return value.typeof toString;
// ToString is a built-in function. Returns 'function'.typeof (5).toString;
// Returns 'string', the datatype of the function's return value.typeof class SomeClass {};
// Returns 'function'. Classes/prototypes are constructor functions .typeof String;
// Returns 'function'. Built-in constructor functions like String, Number, Boolean, Object, Array, Function, Date, etc. are datatype 'function'.Object examples:
typeof { name: 'Joey', age: 24 };
// Returns 'object'.typeof new String('hello');
// Returns 'object'. Strings, numbers, and booleans created as objects are datatype 'object'.typeof new Date();
// Returns 'object'. Dates do not have their own datatype.typeof ['apple', 'orange', 'kiwi'];
// Returns 'object'. Arrays are a kind of object.Array.isArray(['apple', 'orange', 'kiwi']);
// Returns true. This function tests if arg is an array.typeof Math;
// Returns 'object'. Math and JSON globals are not constructor functions.Null example:
Null is a JS data type, but the datatype operator returns 'object' for null values.
typeof null;
// Returns 'object'.Global Object
In JavaScript, a global object is an object that always exists in the global scope.
- Browsers: global object is window and accessible anywhere in your JS scripts.
- Node.js: global object is global and accessible within each module.
Global object properties:
- The standard built-in global objects and functions.
- Web APIs (for browsers) and Node modules (for Node.js nodejs.org/api).
- User defined global variables defined with var (but not let/const) and functions.
Three ways to access global object properties:
window.propName
(browsers) |global.propName
(Node) //Use the global object name.
this.propName
//Keyword this represents the current object.propName
//The global object name is implicit. Leaving it out is the preferred method.
Examples
Date is a standard built-in global object. As such, it becomes a property of the global object.
The Date() function returns the current date and time as a string.
There are three ways to call the global Date() function:
User-defined global variables and functions:
The Date() function returns the current date and time as a string.
There are three ways to call the global Date() function:
window.Date()
for browser,global.Date()
for Node //Using the global object name.this.Date()
//Using the this keyword.Date()
//The preferred method is to leave out the global object name since it is implied.
User-defined global variables and functions:
var greeting = 'Hello';
//Adds variable greeting to the global object.greeting;
//Looks up the variable on the global object and returns 'Hello'.function sayHi() { console.log('Hi'); }
//Adds the function to the global object.sayHi();
//Calls the global sayHi function from the global object. Logs 'Hi' and returns undefined.const sayYo = () => console.log('Yo');
//Function is not added to the global object because it is declared with const.Built-in Objects
Ref: MDN Global_Objects.- Core JS has standard built-in objects in the global scope. They provide properties and methods to work with specific constructs like strings, numbers, arrays, etc.
- Some global objects are regular objects (e.g., Math, JSON).
- Most global objects are constructor functions (JS functions are a type of object).
- All functions have a prototype property. The prototype is an object.
- Instance methods are defined on the prototype and called by chaining to the object.
Examples
Global objects that are standard objects:
typeof Math;
//Returns 'object'. The Math global object is a standard object.Math.PI
returns 3.1416 Math.round(3.9)
returns 4. It has built-in properties and methods that can be called on it.This is similar to the static properties and methods of the global objects that are functions.
Global objects that are functions:
typeof Date
, typeof String
, typeof Array
, typeof Object
etc. all return 'function'.Static properties/methods: They have static properties and methods called on the function:
Number.isInteger(3.1416)
is a static method of the Number global object that determines if the passed in number is an integer. In this case it returns false. Constructor: Call the constructor function with the new keyword to instantiate an object. The argument value passed in becomes the value of the new object.
const date = new Date('2025-12-31');
//creates a new date object.Prototype: All functions can be constructor functions, so functions automatically create a prototype property (e.g.,
Date.prototype
)typeof Date.prototype
//returns 'object'. The prototype is itself an object.All objects have a prototype they are based on.
Object.getPrototypeOf(date)
returns Date.prototype. date.__proto__
will also return the prototype value, although __proto__ is non-standard. Instance methods: are methods that are called by an instance of a prototype/class. They are defined directly on the prototype object.
const date = new Date('2025-12-31')
//Creates a date object.date.toDateString()
//Calling this instance method returns something like 'Tue Dec 30 2025'date.toTimeString()
//Returns something like '16:00:00 GMT-0800 (Pacific Standard Time)'.Object global object
- Object is the prototype of all global objects. It is at the top of the prototype chain.
- All regular objects inherit properties (including methods) from Object.prototype, although they may be shadowed (i.e., overridden).
Example
Object.getPrototypeOf(Date.prototype)
//Returns Object.prototype.new Date() instanceof Object;
//Returns trueObject.getOwnPropertyNames(Object.prototype); //Returns array of own property names. Includes toString.
Object.getOwnPropertyNames(Date.prototype); //Returns array of own property names. Also includes toString, so Date.prototype's toString method shadows (i.e., overrides) Object.prototype's toString method.
toString.call()
toString.call('Hello');
// "[object String]"Examples
toString.call(7);
// "[object Number]"toString.call(true);
// "[object Boolean]"toString.call("Hello".match(/z/));
// "[object Null]". There is no z in "Hello"toString.call(Symbol('x'));
// "[object Symbol]"toString.call({name: 'Joey', age: 22});
// "[object Object]"toString.call([1,2,3]);
// "[object Array]"toString.call(function double(x) { return x * 2 })
// "[object Function]"toString.call(/[aeiou]/);
// "[object RegExp]"Primitive Data Types as Objects:
Primitive data types can be objects if created with a constructor function. ToString.call() returns the same class whether they are primitives or objects:
Be careful with undefined:
If it has been declared but not initialized it will return undefined:
typeof will return "undefined" both if the variable has not been declared, and if it has been declared but not initialized.
toString.call(new String('Hello'));
// "[object String]"toString.call(new Number(7));
// "[object Number]"Be careful with undefined:
If x has not been declared you will get an error.
toString.call(x);
// Uncaught ReferenceError: x is not definedIf it has been declared but not initialized it will return undefined:
let x;
toString.call(x);
// "[object Undefined]"typeof will return "undefined" both if the variable has not been declared, and if it has been declared but not initialized.
typeof x;
// "undefined" let x;
typeof x;
// "undefined"For use in a conditional:
typeof x === 'undefined';
// true.Literals and Variables
Literals
Literals are fixed values, not variables, that you literally provide in your script.
Types of JS Literals:
Number literals: Integer literals: -1, 0, 1. Floating point literals (decimals): 8.99.
String literals: single or double quotes:
Boolean Literals: keywords
RegExp literals: between forward slashes
Array literals: inside square bracket operators
Object literals: inside curly braces {}
Types of JS Literals:
Number literals: Integer literals: -1, 0, 1. Floating point literals (decimals): 8.99.
String literals: single or double quotes:
'text'
. Template literals in backticks `text`
. Boolean Literals: keywords
true
and false
.RegExp literals: between forward slashes
//
Array literals: inside square bracket operators
[]
Object literals: inside curly braces {}
Variables
Variables are containers that store values.
Statements: Declare a variable with the const, let, or var statement.
Identifiers: Variable names.
Declare a variable: with the let (or var) keyword, which tells the browser to create a new variable. Statements: Declare a variable with the const, let, or var statement.
Identifiers: Variable names.
- Can contain only letters, digits, underscores, and dollar signs, but cannot begin with a number. Don't use reserved words.
- Use: descriptive names, lowerCamelCase for multiple words, pluralize array names.
const x = 3;
| let y = 7;
let y;
Initialize the variable: Assign a value to the variable.
y = 7;
Const and Let (ES2015)
Const:
Use const unless you intend to reassign the identifier to another value. Can't be reassigned and must be initialized when declared. Generally declare objects, arrays, functions with const. Modifying object properties/elements doesn't change the variable reference value.
Let:
Use let when you do intend to reassign the value.
Block scoped
Not part of Global Object: even when declared in a global scope.
Hoisted: Variable declarations are hoisted to top of scope, but not initialized.
const arr = ['a', 'b', 'c', 'd', 'e'];
Use const unless you intend to reassign the identifier to another value. Can't be reassigned and must be initialized when declared. Generally declare objects, arrays, functions with const. Modifying object properties/elements doesn't change the variable reference value.
Let:
let i = 0;
Use let when you do intend to reassign the value.
Block scoped
Not part of Global Object: even when declared in a global scope.
Hoisted: Variable declarations are hoisted to top of scope, but not initialized.
Variable Scope
Const and let are block scoped. For var, replace block with function for the below.
Global variables: are variables declared outside a block and all code (inside or outside the block) can access them.Local variables: are variables declared within a block.
A block can access all variables and functions defined inside the scope in which it is defined. So a block defined in the global scope can access all variables defined in the global scope. A block defined inside another block can also access all variables defined in its parent block and any other variable to which the parent block has access.
Block scope: Only valid within the block they are declared and child blocks. Blocks are between curly braces (e.g., if statements, loops, functions).
Cannot declare the same name as another variable or function in the same scope.
Variable Shadowing: Where a local variable shares the same name as a variable in its containing scope. Style guides recommend against shadowing.
A block can access all variables and functions defined inside the scope in which it is defined. So a block defined in the global scope can access all variables defined in the global scope. A block defined inside another block can also access all variables defined in its parent block and any other variable to which the parent block has access.
Block scope: Only valid within the block they are declared and child blocks. Blocks are between curly braces (e.g., if statements, loops, functions).
Cannot declare the same name as another variable or function in the same scope.
Variable Shadowing: Where a local variable shares the same name as a variable in its containing scope. Style guides recommend against shadowing.
Variable lifecycle: Starts when they are declared. Global variables are deleted from memory when you close the web page or exit the program.
Local variables are usually deleted from memory as soon as the block is completed.
Local variables are usually deleted from memory as soon as the block is completed.
Example - declare variable, assign value in conditional
Declare a variable and assign the value in a conditional statement.
Shadowing:
let x;
if (true) x = 7;
x; // returns 7;
Shadowing:
const x = 7;
if (true) {
const x = 10;
}
Var
Var is discouraged in favor of const and let due to scope and hoisting issues.
Details
Hoisting: var declarations are hoisted to the top of the function or script. But their value is undefined until the line it was initialized.
Function scoped: vars are scoped locally only within a function not a block.
Global Object: vars declared in the global scope become part of the global object.
var user = "Joey";
window.user; // "Joey";
Redeclare variables and functions: You can use the same name as an existing variable or function in the same scope. The name will be reassigned to the newly declared variable.
Assigning to Expressions
An expression is any valid unit of code that resolves to a value.
If you assign a variable to an expression, the variable will be set to the expression's resolved value.
If you assign a variable to an expression, the variable will be set to the expression's resolved value.
Examples
Arithmetic: evaluates to a number.
String: evaluates to a character string.
Logical: evaluates to true or false.
Function expression: evaluates to an anonymous function.
Function call: evaluates to the return value of the function call.
const num = 3 + 7;
// num is set to 10.String: evaluates to a character string.
const str = 'Joey ' + 'Smith';
// str is set to 'Joey Smith'Logical: evaluates to true or false.
const isGreater = 7 > 6;
// isGreater is set to trueFunction expression: evaluates to an anonymous function.
const double = (x) => x * 2;
// double is now the function name for: (x) => x * 2Function call: evaluates to the return value of the function call.
const res = double(10);
// res is set to 20;Assigning to primitive types vs objects
Primitive data types: Variables are assigned to the value
Primitives are immutable (can't be changed). When a variable identifier is assigned to a primitive value, it is assigned to an address in stack memory, and the primitive data value is stored in that address.
const x = 7;
const y = 7;
x === y; // returns true. The underlying primitive values are equal.
Stack Memory
Identifier | Memory Address | Value |
---|---|---|
x | 00AA11BB22C | 7 |
y | 001122ZZYY3 | 7 |
Example - Reassigning a variable
- You can reassign a variable to a new primitive value.
- The memory is allocate and the value stored in the call stack which operates on a last-in-first-out basis.
- When you reassign the identifier str to a new memory address with a different value, calling the variable will retrieve the last address/value assigned 'hi'.
- The previous address/value 'Hello' is detached and will get garbage collected.
let str = 'Hello';
str = 'hi;
Identifier | Memory Address | Value |
---|---|---|
str | 00AA11BB22C | 'hi' |
str | 001122ZZYY3 (gets detatched) | 'Hello' |
Objects: Variables are assigned by reference
Variables are assigned to objects (including arrays and functions) by reference.Object properties are stored in heap memory.
Object identifiers point to a memory address in stack memory that stores a reference to the object in heap memory.
Stack Memory
Identifier | Memory Address | Value |
---|---|---|
arr | 0YTE7620IWB | 88UR639YU |
Memory Heap
Memory Address | Value |
---|---|
88UR639YU | ['a', 'b', 'c', 1, 2, 3] |
Example - Assign two variables to the same object
If you assign two variables to the same object reference, changing an underlying property in one variable, changes it for both.
// returns { name: 'Joseph', age: 22 }
const user = { name: 'Joey', age: 22 };
const userCopy = user;
userCopy.name = 'Joseph';
user;
// returns { name: 'Joseph', age: 22 }
Destructuring Assignment (ES2015)
Ref: MDN Operators/Destructuring_assignment
Array Destructuring Assignment
Unpack array into variables:const [var1, var2, var3] = ['item1', 'item2', 'item3']; var1; // 'item1'Ignoring elements:
const [var1, var2] = ['item1', 'item2', 'item3']; const [var1, , var3] = ['item1', 'item2', 'item3'];
Default values:
const [var1, var2=2, var3=3] = ['item1', 'item2'];Swapping values using destructuring:
let var1 = 'a'; let var2 = 'b';Swap array elements:
[var2, var1] = [var1, var2]; // Now var1 is 'b', var2 is 'a'
const arr = ['item1', 'item2', 'item3'];Assign the rest of an array to a variable using the ...rest pattern
[arr[2], arr[1]] = [arr[1], arr[2]]; // arr: ['item1', 'item3', 'item2']
const [var1, ...varRest] = ['item1', 'item2', 'item3'];
// var1 equals 'item1', varRest equals ['item2', 'item3']
Examples
Unpack array into variables:
const [fruit, vegetable, meat] = ['apple', 'carrot', 'chicken']; fruit; // 'apple'Ignoring elements:
const [fruit, vegetable] = ['apple', 'carrot', 'chicken']; const [fruit, , meat] = ['apple', 'carrot', 'chicken'];
Default values:
const [fruit='not specified', vegetable='not specified', meat='not defined'] = ['apple', 'carrot', 'chicken'];Swapping values using destructuring:
let fruit = 'carrot'; let vegetable = 'apple';Swap array elements:
[vegetable, fruit] = [fruit, vegetable]; // Now fruit is 'apple', vegetable is 'carrot'
const food = ['apple', 'carrot', 'chicken'];Assign the rest of an array to a variable using the ...rest pattern
[food[2], food[1]] = [food[1], food[2]]; // arr: ['apple', 'chicken', 'carrot']
const [meat, ...fruitAndVeg] = ['chicken', 'apple', 'carrot'];
// meat equals 'chicken', fruitAndVeg equals ['chicken', 'apple']
Object Destructuring Assignment
Unpack Object into Variables:
const user = { name: 'Joey', age: 22, occupation: 'Sofware Engineer' };
const { name, occupation } = user;
console.log(name, occupation); // "Joey" "Software Engineer"
Assign an alias:
const { name, occupation: job } = user; // alias occupation as job.
console.log(name, job); // "Joey" "Software Engineer"
Assign a default value:
const { name, age='not provided', address='not provided' } = user;
console.log(name, age, address); // "Joey", 22, "not provided"
Expressions and Operators
Expressions
An expression is any valid unit of code that resolves to a value. Example:
An expression can also have side effects such as assigning a value to a variable:
(4 + 3)
. An expression can also have side effects such as assigning a value to a variable:
let x = 7;
JS has the following expression categories:
Arithmetic: evaluates to a number:
String: evaluates to a character string.
Logical: evaluates to true or false.
(4 + 3)
String: evaluates to a character string.
('Joey ' + 'Smith')
Logical: evaluates to true or false.
(7 > 6)
Left-hand-side expressions: new and typeof keywords. The spread operator ...
Primary expressions: Expressions that cannot be evaluated further. Includes:
Primary expressions: Expressions that cannot be evaluated further. Includes:
Literals: strings'hello'
, numbers7
, regexp/pattern/
Certain keywords: true, false, null, this.
Variable references:let x = 'some value';
In this case x is the primary expression.
Operators
In JavaScript, an operator is a special symbol or keyword used to perform operations on data (called operands). Operators are used in expressions.
Ref: MDN Guide/Expressions_and_Operators
Ref List of JS operators: MDN Reference/Operators
Ref: MDN Guide/Expressions_and_Operators
Ref List of JS operators: MDN Reference/Operators
Types of Operators in JS
Assignment, Comparison, Arithmetic, Bitwise, Logical, String, Conditional (ternary), Comma, Unary, Relational.
Operators by number of operands
Operators may be unary, binary, or ternary based on number of operands.
Unary operators: One operand. Operator on the left (++i) or right (i++). Ex: Increment/decrement (++i), unary (+/-), keyword: typeof, delete, etc.
Binary operators: Two operands separated by the operator.
Ex: assignment (x = 7), comparison (x > y), arithmetic (2 + 2), etc.
Ternary operators: have three operands.
Only example in JS: ternary conditional operator (age >= 18 ? 'adult' : 'child')
Assignment Operators
=
is the standard assignment operator. x = 7;Compound assignment operators are are shorthand
res += x;
Addition assignment shorthand for res = res + x;
res -= x;
Subtraction assignment shorthand for res = res - x;
res *= x;
Multiplication assignment shorthand for res = res * x;
res /= x;
Division assignment shorthand for res = res / x;
res %= x;
Remainder assignment shorthand for res = res % x;
res **= x;
Exponentiation assignment shorthand for res = res ** x;
Examples
let res = 4;Use compound assignment operators to add 3:
res += 3; // Same as res = res + 3 res; // returns 7
Subtract 2:
res -= 2; // Same as res = res - 2 res; // returns 5
Multiply by 4:
res *= 4; // Same as res = res * 4 res; // returns 20
Divide by 5:
res /= 5; // Same as res = res / 5 res; // returns 4
Arithmetic Operators
Arithmetic operators are unary and binary operators that take numerical values (either literals or variables) as their operands and return a single numerical value.
Precedence hierarchy - highest on top
(x + y)
groupingx++; x--
postfix increment/decrement-x; +x; ++x; --x
unary operators: negation/conversion, prefix increment/decrementx ** y
exponentx * y; x / y; x % y;
multiply/divide/remainderx + y; x - y;
addition/subtraction
Examples
Multiplication/division/remainder have higher precedence than addition/subtraction:
4 * 2 + 3;
// 11. Executed in the order presented.3 + 4 * 2;
// 11. Multiplication has higher precedence than addition, so 4 * 2 comes first. Then add 3.(3 + 4) * 2;
// 14. Grouping in parentheses has highest precedence. The grouped expression (3 + 4) comes first. Then multiply the result by 2. 4 / 2 + 8;
// 10. Executed in the order resented.8 + 4 / 2;
// 10. Division has higher precedence than addition, so 4 / 2 comes first, then add 8.(8 + 4) / 2;
// 6. Grouping in parentheses has the highest precedence. So add 8 and 4. Then divide that result by 2.4 ** 3 * 2;
// 128. Executed in the order presented.2 * 4 ** 3;
// 128. Exponents take precedence over multiplication, so 4 ** 3 comes first (4 * 4 * 4 = 64), then multiply the result by 2.(2 * 4) ** 3;
// 512 Grouping in parentheses has highest precedence. The grouped expression (2 * 4) is 8. (8 * 8 * 8 = 512)Conversions
For all arithmatic operators, if one of the operands is not a number, JS will first try to convert it to a number using
Exception: If one operand is a sting, addition treats both as strings.
Number(value)
. Exception: If one operand is a sting, addition treats both as strings.
Examples
'11' * '7'; // 77; converts both to numbers.
'11' - 7; // 4; converts '11' to a number.
'11' - true; // 10; Boolean true converts to 1, false converts to 0;
true - false; // 1
true + true; // 2
7 + null; // 7; null converts to 0
- If any either operand is NaN the result is NaN.
1 + NaN; // NaN
1 + undefined; // NaN
- If either of the operands of + is a string, then the other operand is converted to a string and concatenated.
7 + "Eleven"; // "7Eleven"
7 + "11"; // "711";
"7" + true; // "7true";
" " + 11; // " 11"
"" + 11; // "11"
undefined + "11"; // "undefined11"
"7" + null; // "7null"
NaN + "11"; // "NaN11"
- Division by zero produces Infinity
x / 0;
// infinity;Binary Arithmetic operators
+, -, *, /, %, **
+ Produces the sum of numeric operands or string concatenation.
7 + 11; // 18;
11 % 2; // 1; Remainder operator returns the remainder after division. 11/2 is 5 with remainder of 1.
2 ** 3; // 8; Exponentiation operator (ES2016); Same as
7 + 11; // 18;
7 + "11";
// "711"11 % 2; // 1; Remainder operator returns the remainder after division. 11/2 is 5 with remainder of 1.
2 ** 3; // 8; Exponentiation operator (ES2016); Same as
Math.pow(2, 3);
// 8Unary Arithmetic Operators
Increment/Decrement operators:
Prefix returns the value of its operand after adding/subtracting one:
++x; // 8; Adds 1 to its operand.
--x ; // 7; Subtracts 1 from its operand, back to 7.
Postfix returns the value of its operand before adding/subtracting one.
x++; // 7; Returns 7 even though the value is now 8.
x--; // 8; Returns 8 even though the value is now back to 7.
let x = 7;
Prefix returns the value of its operand after adding/subtracting one:
++x; // 8; Adds 1 to its operand.
--x ; // 7; Subtracts 1 from its operand, back to 7.
Postfix returns the value of its operand before adding/subtracting one.
x++; // 7; Returns 7 even though the value is now 8.
x;
// 8;x--; // 8; Returns 8 even though the value is now back to 7.
x;
// 7;More Details
- increment/decrement operators can only be used with variables.
7++;
// SyntaxError
++"7";
// SyntaxError
- Increment/Decrement operators are often used in loops.
- If the variable is not a number, JS will attempt to convert it to a number using
Number(value)
.
Unary Plus operator
Attempts to convert the operand to a number, if it is not already.
+x; // 7;
x; // '7'; Doesn't change the underlying variable x.
-'7'; // -7
Attempts to convert the operand to a number, if it is not already.
let x = '7';
+x; // 7;
x; // '7'; Doesn't change the underlying variable x.
Unary Negation operator
Returns the negation of its operand.
-x; // -7;
x; // 7; Doesn't change the underlying variable x.
If not a number attempts to convert the operand to a number first.Returns the negation of its operand.
-x; // -7;
x; // 7; Doesn't change the underlying variable x.
-'7'; // -7
Examples
Unary + does not change the sign:
let x = -7;Unary + and - can be applied directly to a literal. It uses
+x; // -7
+"-7"; // -7
Number(value)
to convert to number.+7; // 7;
-7; // -7
+(-7); // -7
-(-7); // 7
+"7"; // 7
-"7"; // -7
+true; // 1
-true; // 11
+false; // 0
-false; // -0
+null; // 0
+""; // 0
+" "; // 0
+"Eleven"; // NaN
+undefined; // NaN
-undefined; // NaN
Comparison Operators
Return Boolean values.
Equality Comparisons
Strict Equality
7 === (5 + 2); // true
7 === "7"; // false
Objects (including arrays) are only equal if they point to the same object in memory.
{ name = "Joey" } === { name = "Joey" }; // false
[1, 2, 3] === [1, 2, 3]; // false
===
and !==
must match datatype and value. Use this as default.7 === (5 + 2); // true
7 === "7"; // false
Objects (including arrays) are only equal if they point to the same object in memory.
{ name = "Joey" } === { name = "Joey" }; // false
[1, 2, 3] === [1, 2, 3]; // false
Examples
- Comparison operands can be numeric, string, boolean, or object values.
- Strings are compared based on standard lexicographical ordering, using Unicode values.
Strict Equality corner cases:
NaN !== NaN;
-0 === +0;
undefined !== null;
Object.is(); (ES2015) is the same as the strict equality operator except for NaN, -0 and + 0 comparisons:
Object.is(7, (3 + 4)); // true
Object.is(NaN, NaN); // true
Object.is(-0, +0); // true
Object.is(-0, +0); // false
==
and !=
does type conversion.Type converstion: if the two operands are not of the same type, JS attempts to convert them to an appropriate type for the comparison:
- Number in quotes converts to number.
7 == "7";
// true - true converts to 1.
true == 1;
// true - false, "", and " " convert to 0.
false == 0;
// true - NaN, null and undefined do not convert type. However
null == undefined;
// true
Examples
Loose Equality Examples:
Equal:
7 == "7"; // true
"7" == 7; // true
true == 1; // true
false == 0; // true
"" == 0; // true
" " == 0; // true
" " == false; true
null == undefined; // true
-0 == +0; // true
Not Equal:
NaN == NaN; // false
NaN == 0; // false
null == 0; // false
undefined == 0; // false
Relational Comparisons
<, >, <=, >= Does type conversion using same rules as loose equality.
Returns a boolean.
Strings are compared based on standard lexicographical ordering, using Unicode values.
0-9, then A-Z, then a-z.
Returns a boolean.
Strings are compared based on standard lexicographical ordering, using Unicode values.
0-9, then A-Z, then a-z.
'Z' < 'a';
// trueLogical Operators
&& (and), || (or) , and ! (not)
Values are converted to booleans using the same rules as Boolean(value):
• Falsy: Expressions that evaluate to false, null, 0, NaN, the empty string (''), or undefined.
• Truthy: Everything else.
Values are converted to booleans using the same rules as Boolean(value):
• Falsy: Expressions that evaluate to false, null, 0, NaN, the empty string (''), or undefined.
• Truthy: Everything else.
Used in Conditionals
&&
Logical AND resolves to true only if both of the values given to it are truthy. if (true && true) { /* execute stmts */ }
// executes ||
Logical OR resolves to true if either of the values given to it are truthy. if (true || notEvaluated) { /* execute stmts */ }
// executes if (false || true) { /* execute stmts */ }
// executes!
Logical NOT switches truthy to falsy and falsy to truthy.if (!false) { /* execute stmts */ }
// executes Examples
Logical AND: resolves to true only if both of the values given to it are truthy.
Check that input is greater than 0 and less than 1000.
Check that input is greater than 0 and less than 1000.
const input = someVal; // any value between 1 and 1000 if (0 < input && input <= 1000) console.log('valid');
Logical OR: resolves to true if either of the values given to it are truthy.
Check if input is null or an empty string, log an error.
const input = someVal; // any value
if (input === '' || input === null) console.error('invalid');
Logical NOT: switches truthy to falsy and falsy to truthy.
Check if input is not a finite number, log an error.
const input = someVal; // value should be a finite number
if (!Number.isFinite(input)) console.error('invalid');
Used in Expressions (short-circuit evaluation)
Logical AND
0 && 5; // 0
1 && 6; // 6
Logical OR
0 || 5; // 5
1 || 6; // 1
&&
returns left operand if it can be converted to false, otherwise returns right operand.0 && 5; // 0
1 && 6; // 6
Logical OR
||
returns left operand if it can be converted to true; otherwise returns right operand. 0 || 5; // 5
1 || 6; // 1
Set default value with ||, short-circuit evaluation
- The or operand can be used to set a default value when not using default params.
name = name || 'Unknown'; // Sets a default value if there is no name.
Short-circuit evaluation: As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:
false && 'not evaluated'
is short-circuit evaluated to false.true || 'not evaluated'
is short-circuit evaluated to true.- The second operand of the above expressions is not evaluated, so any side effects of doing so do not take effect.
String Operators
Comparison operators can be used to compare strings:
===, !==, ==, !=, >, >=, <, <= Comparison operators can be used on string values.
Comparisons based on standard lexicographical ordering, using Unicode values.
0-9, then A-Z, then a-z.
Plus + operator concatenates two string values together returning a new string.
Compound assignment operator += concatenates a series of strings.
===, !==, ==, !=, >, >=, <, <= Comparison operators can be used on string values.
Comparisons based on standard lexicographical ordering, using Unicode values.
0-9, then A-Z, then a-z.
'Z' < 'a';
// truePlus + operator concatenates two string values together returning a new string.
'Hello' + ' world';
// "Hello world". Compound assignment operator += concatenates a series of strings.
let str = 'Hello';
str += ' world';
str; // "Hello world"
Conditionals/If Statements | Boolean
Conditional Statements
If...Else
Ref: MDN Statements/if...else
- Executes stmt if condition is truthy. If falsy, another stmt can be executed.
- Often use comparison (e.g., ===, !==) or logical (&& || !) operators in the condition.
if (condition1) {
statements;
} else if (condition2) {
statements;
} else {
statements;
}
Example
let grade;
let score = 77;
if (score >= 90) {
grade = 'A';
} else if (score >= 70) {
grade = 'C';
} else {
grade = 'F';
}
grade; // C
Single statement ifs can omit the curly braces
if (condition) executableStatement;
Example
If age is greater than or equal to 18, set adult to true.
const age = 22; let adult; if (age >= 18) adult = true;
Conditional Ternary Statement
Evaluates to the first option if the condition is truthy, the second if the condition is falsy.
condition ? resultIfTrue : resultIfFalse;
Example
let age = 25;
age >= 18 ? 'Adult' : 'Child'; // "Adult"
Switch Statement
switch (expression) {
case value1: { statements;
break; }
case value2: { statements;
break; }
default: { statements; }
}
Example
Convert day of the week number (0-6) to human readable text.
0 is Sunday, 1 is Monday etc. Only convert weekdays.
let weekday;
let num = 3;
switch (num) {
case 1: {
weekday = 'Mon';
break; }
case 2: {
weekday = 'Tues';
break; }
case 3: {
weekday = 'Wed';
break; }
case 4: {
weekday = 'Thurs;
break; } case 5: { weekday = 'Fri'; break; }
default: { weekday = 'Invalid Day'; }
}
weekday; // returns 'Wed'
When using switch inside a function, use a return statement instead of a break statement.
Example
function weekday(num) { switch (num) { case 1: return 'Mon'; case 2: return 'Tues'; case 3: return 'Wed'; case 4: return 'Thurs'; case 5: return 'Fri'; default: return 'Invalid Day'; } } weekday(3); // returns 'Wed'
Boolean
- boolean is a primitive data type:
typeof true;
// returns 'boolean' - Boolean literals: The keywords true and false.
- Boolean expressions: (1 < 2) resolves to true.
Boolean global object
- Ref: MDN Global_Objects/Boolean
- Boolean is a JavaScript standard built-in object in the global scope.
- Boolean includes a constructor function, static and instance properties and methods.
- Primitives are temporarily wrapped in an object when instance methods are applied.
More info
Boolean global object
- Boolean is a JavaScript standard built-in object in the global scope. It is also called a global object because it is attached to the global object (window or global):
Boolean === window.Boolean; // returns true in the browser environment Boolean === global.Boolean; // returns true in the Node.js environment
- Boolean is a constructor function (functions are a type of object).
typeof Boolean; // returns 'function'
- When called with the new keyword, it instantiates a Number object.
const bool = new Boolean(0); // creates a boolean object with value false
typeof bool; // returns 'object'
- When called in a non-constructor context (i.e., without the new keyword) it converts the argument to a boolean primitive value:
Boolean(0); // returns false
Boolean('Some string'); // returns true
Boolean static properties and methods:
- Boolean has three static properties and no methods:
Object.getOwnPropertyNames(Boolean); // returns length, name, prototype
Boolean instance properties and methods:
- Boolean literals are primitive values and not instances of the Boolean constructor:
typeof true; // returns 'boolean'
true instanceof Boolean; // returns false
- Boolean wrapper object: When a property or method is called on a boolean primitive value (true or false), JavaScript temporarily wraps the primitive with an object by calling new Boolean(primitive value), applies the property or method, then disposes of the object. So boolean literals have a constructor and prototype:
true.constructor === Boolean; // returns true Object.getPrototypeOf(false) === Boolean.prototype; // returns true
- The Boolean.prototype has three instance properties:
Object.getOwnPropertyNames(Boolean.prototype); // returns constructor, valueOf, toString
- valueOf: converts a boolean object to a boolean literal:
const bool = new Boolean(1); typeof bool; returns 'object' bool.valueOf(); // returns true typeof bool.valueOf(); // returns 'boolean'
- toString: converts a boolean to a string
true.toString(); // returns 'true'
Convert other data types to a boolean:
Boolean(expression);
//Returns boolean literal. !!(expression);
//Not not returns boolean literal.Falsy expressions return false, truthy expressions return true.
Falsy:
false, '', 0, NaN, null, and undefined.Truthy:
Everything else (e.g., true, all strings including ' ', '0', and 'false', all numbers except 0 and NaN, [], {}, etc.).Examples
Expressions that resolve directly to true or false:
Missing values are falsy. Includes undefined, null, and an empty string '':
NaN is falsy. This is a special number value that means Not a Number. It is used in a context where a number is expected.
0 is falsy:
Everything else is considered truthy:
Boolean(true);
// trueBoolean(2 > 1);
// trueBoolean(false);
// falseBoolean(2 < 1);
// falseMissing values are falsy. Includes undefined, null, and an empty string '':
Boolean(undefined);
// false let x; Boolean(x);
// false, x is undefined Boolean(null);
// falseBoolean('');
// false, empty strings are falsy.Boolean(' ');
// true, a space string is considered truthy.NaN is falsy. This is a special number value that means Not a Number. It is used in a context where a number is expected.
Boolean(NaN);
// falseBoolean(Number('Some text'));
// false, converting text to a number returns NaN.0 is falsy:
Boolean(0);
// falseBoolean(2-2);
// falseEverything else is considered truthy:
Boolean(1);
// trueBoolean(-0.3);
// trueBoolean('Some text');
// trueBoolean('false');
// true, 'false' in quotes is a string.Boolean(new Boolean(false));
// true, all objects convert to trueBoolean(new Number(0));
// true, all objects convert to trueBoolean([false, undefined, null, 0, NaN]);
// true, any array converts to true regardless of the element values.Check if input value is valid
if (inputValueIsValid) doSomething;
Examples
let input;
// Check that input is truthy.
if (input) console.log(valid);
// Check that input is truthy or 0.
if (input || input === 0) console.log('valid input');
// Check that input is truthy or 0. Use trim() to ensure input isn't blank spaces.
if (input.trim() || input === 0) console.log('valid input');
// Check that input is not undefined or null. Loose equality != combines null and undefined.
if (input != null) console.log('valid input');
// Check that input is not undefined. Typeof will check input type without evaluating it so won't throw an error if input is not declared.
if (typeof input !== 'undefined') console.log('valid input');
Loops
In the various loops:
break;
Stops the loop.continue;
Skips over the current interation and continues with the next iteration.- If only one statement in the loop, the curly braces are optional but recommended.
For Loop
Put the initialization, the condition, and the loop variable update on a single line.for (initialize; condition; incrementExpression) {
statements;
}
- Initialize: Evaluated once before the loop starts. Typically initializes a counter variable. Ex:
let i = 1;
- Condition: Defines the condition for running the loop. Ex:
i < 5;
- IncrementExpression: Executed after each time after the loop is executed. Ex:
i++
- These statements are optional but the semicolon between each is required:
for (;;) { }
Example
for (let i = 1; i < 6; i++) { console.log(i); } // logs 1 through 5
break;
Stops the loop.continue;
Skips over the current interation and continues with the next iteration.- The curly braces are optional (but still recommended) if there is only one statement in the loop.
While Loop
Repeats through a block of code while the condition is true. Condition must return true or false. The condition test occurs before the statement in the loop is executed.
while (condition) {
statements;
}
Example
let i = 1; while (i < 6) { console.log(i); i++; } // logs 1 through 5.
break;
Stops the loop.continue;
Skips over the current interation and continues with the next iteration.- The curly braces are optional (but still recommended) if there is only one statement in the loop.
Do...While Loop
Put the condition after the loop. The loop will run before checking the condition (so will run at least once).
do {
statements;
} while (condition);
Example
let i = 1;
do {
console.log(i++);
} while (i < 6); // logs 1 through 5
break;
Stops the loop.continue;
Skips the rest of the current interation and continues with the next iteration.
For...Of Loop with Arrays (ES2015)
for (const elem of arr) {
statements;
}
You can also iterate through an array using arr.forEach(). See Array section.
Examples
Create a loop Iterating over iterable objects (Array, Map, Set, arguments object, etc.):
Iterables:
const arr = ['a', 'b', 'c', 'd', 'e'];
for (const elem of arr) {
console.log(elem);
} // logs a b c d e.
for (const char of 'Hello') {
console.log(char);
} // logs each of the characters in the string as separate elements.
const numArr = [1,2,3];
let res = 1;
for (const val of numArr) {
res *= val;
} res; // 6
- Use const unless you are going to reassign the variable in the loop.
break;
Stops the loop.continue;
Skips over the current interation and continues with the next iteration.- The curly braces are optional (but still recommended) if there is only one statement in the loop.
Iterables:
- Iterable objects are objects that can be iterated over with for...of.
- Technically, iterables must implement the Symbol.iterator method.
- Built-in iterables: Arrays, String, TypedArray, Map, and Set.
For...In Loop with Objects
for (const property in object) {
statements;
}
- The in operator gets the property keys of an enumerable object.
Example
const person = { name: 'Joey', gender: 'male', age: 30 };
let res = '';
for (const prop in person) {
res += person[prop] + ' ';
}
res; // "Joey male 30 "
Functions
- Functions are self contained blocks of code that accomplish a specific task.
- It may take inputs, called parameters, and return an output.
- Functions are not executed until they are invoked (called).
- JS has first class functions: i.e., treated like any other variable. Can be stored in a variable, obj, or array; passed as an arg to another function; returned from a function.
Function parts
- Function names: Same rules as variables. Contain only letters, digits, underscores, dollar signs. Can't start with numbers. Multiword names use lowerCamelCase.
- Function definition: The first line of the function. Includes function name (unless anonymous), keyword function (or =>), parentheses with optional parameters.
- Function body: block of one or more statements to be executed, inside curly braces.
Example
function double(num) { //Fn definition: fn keyword, fn name, params.
const res = num * 2; //Function body.
return res;
}
double(5);
Function declaration
function name(params) {
statements;
return statement (if any);
}
name(args); // calls the function
Hoisted: Functions are hoisted to the top of its script or function.
Function Scoped: If defined within another function, not accessible outside that fn.
Function Scoped: If defined within another function, not accessible outside that fn.
- If defined in a block that is not a function, they are accessible outside that block.
- If defined in the global scope, they are attached to the global object.
Examples
function square(num) {
return num * num;
};
square(2); //Returns 4
Hoisting: Function declarations get hoisted to the top if it's script, or if it is embedded in another function it is hoisted to the top of that function. That means it can be called before it is declared:
square(2); // 4 function square(num) {
return num * num;
};
Function declared in a function:
Functions declared in another function are not accessible outside the function.
Functions declared in another function are not accessible outside the function.
function mathFunctions() {
function square(x) { return x * x; }
} square(2); //Uncaught ReferenceError: square is not defined
Function declared in a block:
Functions declared in a block that is not a function are accessible outside that block.
if (true) {
function square(x) { return x * x }
} square(2); //Returns 4
Global Scope: Function declarations in the global scope are attached to the global object.
function square(num) { return num * num; }
window.square(2); //Returns 4
Function Expression
const functionName = function(params) {Function expressions are anonymous functions assigned to a variable. Follows same rules as the variable in terms of allowed names, redeclaration, scope, and hoisting.
statements;
return statement (if any);
};
functionName(args); // calls the function.
Example, more details
const square = function(num) {
return num * num;
};
square(4); // 16
Assigning it to a const means:
- The name can only contain letters, digits, underscores, and dollar signs, but cannot begin with a number. Use lowerCamelCase for multiword names.
- It is block scoped.
- It cannot use the same name as another function or variable in the same scope.
- It cannot be redeclared in the same scope.
- It is not hoisted, so it cannot be called before it is declared.
- It does not become part of the global object even if declared in the global scope.
Arrow Function Expression (ES2015)
const functionName = (params) => {Arrow functions are anonymous functions generally assigned to a const variable. Follows the rules for const in terms of allowed names, redeclaration, scope, hoisting.
statements;
return statement (if any);
} functionName(args); // calls the function
Style guides recommend arrow functions over function declarations.
More details and examples
Arrow function expressions are similar to regular function expressions with the following differences:
Assigning it to a const means:
Style guides recommend arrow functions over function declarations:
Examples:
- Arrow functions do not have their own bindings to this. They establish this based on the scope the Arrow function is defined within.
- They cannot be used as constructors.
Assigning it to a const means:
- The name can only contain letters, digits, underscores, and dollar signs, but cannot begin with a number. Use lowerCamelCase for multiword names.
- It is block scoped.
- It cannot use the same name as another function or variable in the same scope.
- It cannot be redeclared in the same scope.
- It is not hoisted, so it cannot be called before it is declared.
- It does not become part of the global object even if declared in the global scope.
Style guides recommend arrow functions over function declarations:
- Google and AirBnB style guides both recommend using arrow functions over function declarations. Reasoning is hoisting potentially harms readability/maintainability since function declarations can be called before they are declared.
Examples:
They are anonomous functions generally assigned to a const variable.
Arrow functions are not hoisted so they can only be called after they are declared.
Arrow functions (declared as a const variable) are block scoped. They can't be accessed if they are inside a block such as an if statement:
Arrow functions (declared as a const variable) do not become part of the global object even if declared in the global scope.
const double = (num) => {
return num * 2;
} double(10); // returns 20
Arrow functions are not hoisted so they can only be called after they are declared.
double(10); // Uncaught ReferenceError: double is not defined const double = (num) => {
return num * 2;
}
Arrow functions (declared as a const variable) are block scoped. They can't be accessed if they are inside a block such as an if statement:
if (true) {
const double = (x) => { return x * 2; }
}
double(10); // Uncaught ReferenceError: double is not defined
Arrow functions (declared as a const variable) do not become part of the global object even if declared in the global scope.
const double = (num) => {
return num * 2;
}
double(10); // returns 20
window.double(10); // Uncaught TypeError: window.double is not a function
Single statement arrow function
Put on one line, omit the curly braces and the return keyword:
const functionName = (params) => statement;
//Define single statement arrow function.functionName(args);
//Call the function the usual way.Examples
const double = (num) => num * 2;
double(10); // returns 20
- Single line returning an object, enclose in parentheses:
const setUser = (user) => ({name: user});
setUser("Joey"); // {name: "Joey"}
- If you add curly braces you must also add the return statement:
const double = (num) => { return num * 2; }
double(10); // returns 20
Immediately Invoking Function Expression (IIFE)
Anonymous function that calls itself. Wrap it in parentheses and call it on itself.
(function (params) {
statements; return statement (if any)
}(args));
Example
The function square:
Can be converted to an IIFE:
function square(num) {
return num * num;
}
square(4); //Returns 16
Can be converted to an IIFE:
- Remove the function name making it an anonymous function.
- Wrap the function in parentheses.
- Place parentheses with arguments directly after the function to call it on itself.
(function (num) {
return num * num;
}(4)); //Returns 16
Methods
Methods are functions that are properties of objects.
obj.methodName();
//Methods are called on an object by chaining the method to it.Examples
Add a method to an object:
In the below user object, add a property called addYear. Assign it to a function that adds 1 to the user.age value.
Call it by chaining it to the user object.
Use methods of built-in global objects:
JavaScript's built-in global objects have methods attached to their prototypes.
Example: the String global object has a method called toUpperCase() defined on
It is called by chaining it to a string instance:
In the below user object, add a property called addYear. Assign it to a function that adds 1 to the user.age value.
Call it by chaining it to the user object.
const user = { name: 'Joey', age: 22 };
user.addYear = function() {
user.age = user.age + 1;
}
user.addYear();
user.age; //Returns 23
Use methods of built-in global objects:
JavaScript's built-in global objects have methods attached to their prototypes.
Example: the String global object has a method called toUpperCase() defined on
String.prototype.toUpperCase
. It is called by chaining it to a string instance:
'hello'.toUpperCase();
// returns 'HELLO'Parameters/Arguments
- Parameters are placeholders for input values in the function definition.
- Arguments are the actual input values passed to the function when it is called.
- Inside the function, the argument values are used as local variables.
Too many/few arguments
- If too many arguments are passed in, the additional arguments are ignored.
- If not enough args are passed in, the missing args are substituted with undefined.
Examples
If there are too many arguments, the additional arguments are ignored.
function double(num) {
return num * 2;
}
double(10, 8, 77);
// returns 20
If there are not enough arguments, the missing args are substituted with undefined.
function double(num) {
return num * 2;
}
double();
// returns NaN which is the result of undefined * 2
Default parameters (ES2015)
The default value for parameters is undefined. You can set your own default values.
function funcName(param1, param2 = defaultVal) { statements }
More details
- Assign a default value to the second parameter:
function multiply(a, b = 1) {
return a * b;
}
multiply(7); //Returns 7
- Passing undefined as an argument to a parameter that has a default will result in the default. Passing null will result in null.
function multiply(a, b = 1) {
return a * b;
}
multiply(7, null); //Returns 0. 7 * null becomes 7 * 0 which returns 0.
- Parameters already encountered are available to later default parameters. If not yet encountered, throws a ReferenceError.
function func(x, y = x/2) { return x + y; }
func(4); // 6
Rest Parameters (ES2015)
Rest parameter accepts an indefinite number of arguments and stores them in an array.
const funcName = (param1, ...restParamName) => { restParamName.forEach((param) => console.log(param));
}
funcName(arg1, [arg2, arg3,...]);
More details and example
- Ref: MDN Functions/rest_parameters
- The rest parameter can be any valid variable name and is prefixed with
...
- Only the last parameter can be a "rest parameter".
- If no arguments are passed to the ...rest parameter, it's value is an empty array [];
- Rest parameter syntax looks exactly like the spread syntax. However, it does the opposite. The spread syntax expands an elements out of an array, while the rest syntax condenses the values into an array.
Example:
const highScore = (name, ...scores) => {
const sorted = scores.sort((a,b) => b - a);
return `${name}'s highest score is ${sorted[0]}.`
}
highScore('Judy', 75, 82, 94, 72, 88); //Returns 'Judy's highest score is 94.'
Options object as parameter
Options object is a common pattern for passing options into a function.
function funcName(arg1, options = {}) {}
funcName(arg1, { opt1: val, opt2: val }
Variable Scope
Global variables: fns can access all variables/functions defined in the global scope.
Up the chain: If the function is nested in another function it has access to the variables declared in the parent's scope as well.
Local variables: Variables declared within the function are local variables, which the function can also access. Param values behave like local variables.
Variable Shadowing: A variable in an outer scope can be overwritten in the function, without affecting the original.
Up the chain: If the function is nested in another function it has access to the variables declared in the parent's scope as well.
Local variables: Variables declared within the function are local variables, which the function can also access. Param values behave like local variables.
Variable Shadowing: A variable in an outer scope can be overwritten in the function, without affecting the original.
Examples
let age = 22;
function addYear() {
age += 1;
return age;
}
addYear(); //Returns 23; The updated variable value is returned.
age; //Returns 23; The function has access to all variables up the chain.
Variable Shadowing example:
A variable in an outer scope can be overwritten in the function, without affecting the original.
let age = 22;
function overwriteVar() {
let age = 23; //Redeclare the age variable.
return age;
}
overwriteVar(); //Returns 23; The redefined variable value is returned.
age; //Returns 22; The variable in the outer scope is unchanged.
Value vs reference arguments
primitive value arguments are passed by value, objects passed by reference.Examples
- Below two variables are defined. One is a primitive value, the other is an object.
- The function changeVals is called passing in these two variables as arguments.
- The changeVals function takes two parameters, a number primitive and an object.
- The function adds 1 to the age primitive variable, and to the person.age property, then logs both.
let age = 22;
const person = { name: 'Joey', age: 22 };
function changeVals(age, person) {
age += 1;
person.age += 1;
console.log('Inside function:', age, person.age); //Inside function: 23, 23
}
changeVals(age, person);
console.log('Outside function:', age, person.age); //Outside function: 22, 23
- Arguments passed to a function that are primitives (e.g., strings, numbers, booleans) are passed by value. If the function changes the passed in argument, it only affects the function's local scope.
- The parameter names are like variable declarations in the scope of the function, where the argument value passed in initializes them.
Person.age: The person.age property value changes both inside and outside the function.
- Objects are stored in heap memory while primitives are stored in stack memory. Variables assigned to objects hold the memory address as their value, not the actual object property values.
- Objects (including arrays) passed in as arguments actually pass in a reference to the object in memory, not the actual object property values.
- The function parameter creates a local variable that refers to that object. If the function changes the object's properties, the change is applied to the object/array in the heap memory. This changes the values both inside and outside the function.
Return Value
JS functions always return a value.
Return statement: The return statement causes the function to stop executing and return the value of its expression to the caller.
Single line arrow functions have an implicit return statement.
Undefined: Functions can exist to produce a side effect only with no return statement. In these cases the function returns undefined and moves to the next statement.
Return statement: The return statement causes the function to stop executing and return the value of its expression to the caller.
Single line arrow functions have an implicit return statement.
(num) => num * num;
//Returns the result of num * numUndefined: Functions can exist to produce a side effect only with no return statement. In these cases the function returns undefined and moves to the next statement.
Example
const toBoolean = (value) => {
if (value === 'Yes') {
return true;
} else if (value === 'No') {
return false;
}
}
toBoolean('Yes'); //Returns true
toBoolean('No'); //Returns false
toBoolean('Not sure'); //Returns undefined
Function standard built-in object
- JavaScript functions are a special type of object that can be called.
Object.getOwnPropertyNames(Function.prototype)
// gets the below properties:
Instance Properties
func.name;
//Returns the name of the function.func.length;
//Returns the number of arguments expected by the function.Prototype Property:
func.prototype;
//Returns the prototype object. Used if the function is a constructor. Becomes the prototype object of any objects it creates.
Arrow functions cannot be constuctor functions and do not have a prototype property.
Instance Methods
func.toString();
//Returns a string representing the source code of the function.bind, call, and apply methods relate to modifying the function's this scope.
String
- JavaScript strings are sequences of Unicode characters represented by one UTF-16 code unit or two for some Asian characters and emojis.
- string is a primitive data type:
typeof 'Hello'; // returns 'string'
Create a String
Strings can be created as primitives or as objects.1) String Literal:
const str = 'text';
//A string literal is characters surrounded by single or double quotes. It creates a string primitive value.Examples and more details
- Strings can use single or double quotes:
const str = 'Hello';
orconst str = "Hello";
- Both Google and AirBnB JS style guide recommend using single quotes for strings and template literals (``) if the string contains single quotes.
- Primitive values are represented directly at the lowest level of the language implementation. This makes it fast and efficient.
- Use string primitives over String objects.
- You can call any of the properties and methods of the String object on a string literal value. JS automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object.
'Hello'.constructor; // String()
'Hello'.constructor.prototype; // String
'Hello'.toUpperCase(); // "HELLO"
String Escape Notation:
\'
single quote; \"
double quote; \\
backslash; \n
new line; \t
tabExample
let str = "Advice for new web devs:\n\t\"Learn JavaScript Basics\"";Returns:
str;
"Advice for new web devs:
"Learn JavaScript Basics""
"Learn JavaScript Basics""
1b) Template Literals (ES2015) - allow interpolation and multiline strings:
let str = `Text ${expression}`;
//Template string. Embedded expressions go inside ${} Examples
Interpolation:
Multiline example:
const name = 'Joey';// Returns "Hello Joey"
const str = `Hello ${name}`; // Embedded expressions go inside ${}
str;
Multiline example:
const multiLine = `This string//Returns:
spans multiple
lines.`;
multiLine;
"This string
spans multiple
lines."
spans multiple
lines."
2) String object (not recommended):
Strings can be created as objects by calling the constructor function.new String('value');
//Instantiates a string object, not a primitive. Example
let str = new String('Hello');
// Creates a string object.typeof str;
//Returns 'object'.str === 'Hello';
//Returns false. They are not equal because str is an object while "Hello" is a string literal.str;
// Returns a String object with internal property [[PrimitiveValue]]: "hello"str.valueOf();
//Returns 'Hello'String global object
- String is a JavaScript standard built-in object in the global scope.
- String includes a constructor function, static and instance properties and methods.
- Primitives are temporarily wrapped in an object when instance methods are applied.
More info
String global object
- String is a JavaScript standard built-in object in the global scope. It is also called a global object because it is attached to the global object (window or global):
String === window.String; // returns true in the browser environment String === global.String; // returns true in the Node.js environment
- String is a constructor function (functions are a type of object).
typeof String; // returns 'function'
- When called with the new keyword, it instantiates a String object.
const str = new String('Hello');
typeof str; // returns 'object'
- When called in a non-constructor context (i.e., without the new keyword) it converts the argument to a string primitive value:
String(10); // returns '10'
String(true); // returns 'true'
String static properties and methods:
- String has some static properties:
Object.getOwnPropertyNames(String); // returns length, name, prototype, fromCharCode, fromCodePoint, raw
String Instance properties and methods:
- String literals are primitive values and not instances of the String constructor:
typeof 'Hello'; // returns 'string'
'Hello' instanceof String; // returns false
- String wrapper object: When a property or method is called on a string primitive value, JavaScript temporarily wraps the primitive with an object by calling new String(primitive value), applies the property or method, then disposes of the object. So string literals have a constructor and prototype:
'Hello'.constructor === String; // returns true Object.getPrototypeOf("Hello") === String.prototype; // returns true
- String.prototype has properties and methods that can be called on a string instance. Below is the full list:
Object.getOwnPropertyNames(String.prototype); // Returns: length, constructor, anchor, big, blink, bold, charAt, charCodeAt, codePointAt, concat, endsWith, fontcolor, fontsize, fixed, includes, indexOf, italics, lastIndexOf, link, localeCompare, match, matchAll, normalize, padEnd, padStart, repeat, replace, replaceAll, search, slice, small, split, strike, sub, substr, substring, sup, startsWith, toString, trim, trimStart, trimLeft, trimEnd, trimRight, toLocaleLowerCase, toLocaleUpperCase, toLowerCase, toUpperCase, valueOf, at.
- constructor is a reference to the String() constructor function.
Static Methods
String.fromCharCode(charCode);
//Returns a string created from the specified sequence of UTF-16 code units.Ref: en.wikipedia.org/wiki/List_of_Unicode_characters
String.fromCodePoint(codePoints);
//The same as fromCharCode but can also access some supplementary characters from UTF-32 code units.String.raw`templateLiteral`;
//Converts template string to a regular string.Examples
String.fromCharCode(72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33);
//Returns Hello World!Raw method:
Template literals are syntactic sugar. JavaScript converts them to regular strings behind the scenes.
The raw static method converts template strings to regular strings, although there is generally no need to use it:
The raw static method converts template strings to regular strings, although there is generally no need to use it:
String.raw`5 to the third power is ${5**3}.`;
//Returns 5 to the third power is 125.Instance Properties
Strings are array-like objects (i.e., they have a length property and indexed elements).
str.length;
//Returns the number of characters in the string.Example
let str = 'Hello';
str.length; // 5
Instance Methods
Return a modified copy of the string
str.toLowerCase();
//Returns copy of the calling string value converted to uppercase.str.toUpperCase();
//Returns copy of the calling string value converted to lowercase.Examples, Capitalize first letter
let str = 'hELLo'; str = str.toUpperCase(); // HELLO
str = str.toLowerCase(); // hello
str = str.charAt(0).toUpperCase() + str.slice(1); // Hello
str.trim();
//Trims whitespace from the beginning and end of the string.str.trimStart();
//Trims whitespace from the beginning of the string.str.trimLeft()
//Alias of trimStart.str.trimEnd();
//Trims whitespace from the end of the string.str.trimRight()
//Alias of trimEnd.Examples
let str = ' Hello ';
str.trim();
// "Hello"; Returns as a new string representing the calling string stripped of whitespace from both ends.str.trimStart();
// "Hello ";str.trimLeft()
// "Hello "str.trimEnd();
// " Hello"str.trimRight()
// " Hello"str;
// " Hello "str.padStart(targetLength [, padString]);
//Returns new string padded from the start with the given padString. Length of new string is the longer of targetLength or string's length.str.padEnd(targetLength [, padString]);
//Same as above with the padding at the end.Examples
let str = 'Hello';
Pad start:
str.padStart(8);
// " Hello"; Default padString is blank space.str.padStart(2);
// "Hello"; Does not add padding if targetLength shorter then the length of the string.str.padStart(8, '-');
// "---Hello"Pad end:
str.padEnd(8);
// "Hello "; Default padString is blank space.str.padEnd(2);
// "Hello"; Does not add padding if targetLength shorter then the length of the string.str.padEnd(8, '.');
// "Hello..."str.charAt(index);
//Returns character at the given index.//Strings are array-like objects (i.e., they have a length property and indexed elements).
str[index];
//Returns character at the given index.Examples
const str = 'Hello';
charAt: get indexed character using charAt() method.
str.charAt(1);
// "e";str.charAt(str.length - 1);
// "o"; Returns the last letter in the string.str.charAt();
// "H", Default index is 0.str.charAt(6);
// "", Returns empty string if out of range.Bracket notation: get indexed character using bracket notation.
Strings are array-like objects. Using bracket notation with index will return the char:
str[1];
//returns 'e'Strings are immutable so attempting to set a character using it's index will not succeed:
str[1] = 'i';
str;
//Returns 'Hello'str.charCodeAt(index);
//Returns the unicode integer of the character at the given index. Example
'Hello'.charCodeAt(4);
// 111str.slice(beginIndex[, endIndex]);
//Returns part of the string extracted from beginIndex to the character before endIndex. Negative indexes count from the end of the string.str.substring(beginIndex[, endIndex]);
//Like slice but doesn't accept negative parameters. Examples
Slice:
'Hello'.slice(1,4);
// "ell" 'Hello'.slice(1,-1);
// "ell"; Negative values start from the end of the array.'Hello'.slice(1);
// "ello"; Leave out the endIndex to include all elements to the end. Substring:
'Hello'.substring(1,4);
// "ell" 'Hello'.substring(1);
// "ello"; Leave out the endIndex to include all elements to the end. str.replace(regexpOrSubstr, newSubstr|function);
//Returns string with the substring or regExp match in the 1st arg replaced by the substring or function return value of the 2nd arg. Parameters explained, Example
Parameters:
1) regexp or substring: Search the string for a matching regexp or substring. The first match (or all if using a regexp with the global flag) is replaced by the second parameter.
2a) newSubStr: Replaces the match(es).
2b) function: Alternatively invoke a function to create the new substring.
Return value: A new string with some or all matches of a pattern replaced by a replacement.
2a) newSubStr: Replaces the match(es).
2b) function: Alternatively invoke a function to create the new substring.
Return value: A new string with some or all matches of a pattern replaced by a replacement.
let phone = '415-555-5555';
phone.replace(/-/g, '.'); // "415.555.5555"
See MDN replace for more complex examples.
str.repeat(count);
//Returns new string containing the specified num of copies of given str. Example
'-'.repeat(10);
// "----------"str.concat(string2[, string3, ..., stringN]);
//Returns new concatenated string.same as
str + 'string2';
Examples
let str = 'Hello';
str.concat(' ', 'World');
// "Hello World"str + ' World';
// "Hello World"; The + operator also concatenates strings. str += ' World';
// += changes the str variable by appending the string.str;
// "Hello World"; str.valueOf();
//If str is a String object, returns it's primitive value. Examples
let str = new String('Hello');
// str is an object of the String prototype.str.valueOf();
// "Hello"; converted to a primitive.'Hello'.valueOf();
// "Hello"; If string is already a primitive string type then valueOf just returns itself.Search/Find methods
Search/Find and return matches:
str.match(/regexp/);
//Searches string for a match against a regular expression. Returns an array object with match info of the first match. With the global flag returns an array of all matched characters. If no matches, returns null.Examples
Find first match: Returns an array object with match info of the first match.
Global: With the global flag returns an array of all matched characters.
No matches:
'Hello'.match(/l/);
//['l', index: 2, input: 'Hello', groups: undefined]'Hello'.match(/[aeiou]);
//['e', index: 1, input: 'Hello', groups: undefined]Global: With the global flag returns an array of all matched characters.
'Hello'.match(/H/g);
// ["H"]; g modifier: global search.'Hello'.match(/[aeiou]/gi);
// ["e", "o"]; i modifier: case insensitive, g modifier: global search.'Hello'.match(/[aeiou]/gi).length;
// 2; gets the count.No matches:
'Hello'.match(/z/);
// nullstr.matchAll(/regexp/g);
//Returns an iterator of all results matching a string against a regular expression. Example
- Use matchAll to get an array of information on each match (searching globally, case insensitive) and put the matches in an iterator.
- Use array destructuring to put the matches in an actual array. Then iterate over the array, logging the info for each match.
const str = 'This string contains cat and dog. Cat by itself is in twice, then there are category and catch.';
const matches = [...str.matchAll(/cat/ig)];
matches.forEach((match) => console.log(match));
Search/Find and return index position:
str.indexOf(searchValue[, fromIndex]);
//Returns the index position where the first occurrence of the string begins. Returns -1 if not found.str.lastIndexOf(searchValue[, fromIndex]);
//Same as above but finds last.str.search(/regexp/);
//Returns the index position where the first occurrence of the regex occurs. Returns -1 if not found. Global option is ignored.Examples
'Hello'.indexOf('l');
// 2'Hello'.indexOf('l', 4);
// -1; Starts at index 4. Returns -1 since there is no match.'Hello'.lastIndexOf('l');
// 3'Hello'.search(/l/i);
// 2'Hello'.search(/l/gi);
// 2; The global option is ignored.Search/Find and return boolean:
str.includes(searchString[, position]);
//Returns true if searchString is found in the string; otherwise, false. Position is where to begin the search, default is 0. Is case sensitive. str.startsWith(searchString[, position]);
//Like above but string must start with searchString.str.endsWith(searchString[, length]);
//Like above but string must end with searchString.Examples
'Hello'.includes('he');
// false; 'Hello'.includes('He');
// true'Hello'.startsWith('He');
// true'Hello'.endsWith('He');
// falseCompare Strings
str === 'text';
//Returns true/false.str [>|=>|<|<=] 'chars';
//Compare 2 strings using comparison operators, returns true/false.Strings compared in lexicographical order (char by char). Chars are compared by their unicode decimal: [0-9]=[48-57], [A-Z]=[65-90], [a-z]=[97-122].
str.localeCompare('chars');
//Compares two strings in the current locale, based on the browser's language settings. Returns sort order -1, 1, or 0 (for before, after, or equal).Example
let str = 'Hello';
str === 'Hello';
//Returns true.str === 'hello';
//Returns false. Capital letters come before lower case letters. How strings are compared:
Strings are compared in lexicographical order (i.e., character by character).
Characters are compared by their unicode decimal:
[0-9] is [48-57], [A-Z] is [65-90], [a-z] is [97-122].
str.charCodeAt(0);
//Returns 72, the unicode integer of the character at the given index.'hello'.charCodeAt(0);
//Returns 104, the unicode integer of the character at the given index.str < 'Hello2';
//Returns true. Comparison is equal until the 2 character. str <= 'Hello2';
//Returns true. str > 'hello';
//Returns true. Lowercase letter unicode numbers come after uppercase letter unicode numbers.str >= 'hello';
//Returns true.LocaleCompare:
The current locale is based on the language settings of the browser:
str.localeCompare('Hello');
// 0;Compares two strings in the current locale. Returns sort order -1, 1, or 0 (for before, after, or equal).
Convert Data Types to/from String
Test if string
typeof value;
//Returns data type of value.typeof value === 'string';
//Tests if the value is string data type. Returns true/false.Object.getPrototypeOf(value);
//Returns the prototype object of the passed in value. Object.getPrototypeOf(value) === String.prototype;
//Tests if the value's prototype is String.Examples
const val = 'Hello';
typeof val;
//Returns 'string'.typeof val === 'string';
//Returns true.Object.getPrototypeOf(val);
//Returns String.prototype.Object.getPrototypeOf(val) === String.prototype;
//Returns true. Convert to string representation of a value
String(value);
//Call String in non-constructor context (without new keyword) converts value to a string primitive.Examples
String(7);
// "7"String(true);
// "true"String([1, 2, 3]);
// "1,2,3"String({ name: 'Joey', age: 22 });
//Returns '[object Object]'.objOrExp.toString();
//Returns a string representation of the object or expression. Examples
(21).toString();
//Returns '21'.(true).toString();
//Returns 'true'.['a', 'b', 'c'].toString;
// "a,b,c"{ name: 'Joey', age: 22 }.toString();
//Returns '[object Object]'.Convert To/From Array
str.split([separator[, limit]]);
//Returns array by splitting string at the separator character provided. Separator can be a string or regexp.arr.join([separator]);
//Joins all elems of array converting to a string. Returns the string. Examples
Split string into array:
Join array to string:
let phone = '415-555-1212';
phone.split('-');
// ["415", "555", "1212"]phone.split(/[\s-.]/);
//["415", "555", "1212"] // You can use Regexp. Splits on either space, dash, or period.'Hello'.split();
// ["Hello"]; Without a separator puts the whole string as one element.'Hello'.split('');
// ["H", "e", "l", "l", "o"]; To split on every character use empty quotes as the separator.'Hello'.split('', 3);
// ["H", "e", "l"]; With a limit argument.'1,2,3,4,5'.split(',').map(Number);
// [1, 2, 3, 4, 5]; Splits string of numbers into array of strings then converts them to numbers.Join array to string:
['a', 'b', 'c', 'd', 'e'].join('-')
// "a-b-c-d-e"; Convert String to Number
Number('numStr');
//Converts string to integer, float, or NaN.parseInt('numStr');
//Converts string to an integer (number without decimals) or NaN.parseFloat('numStr');
//Converts string to a number or NaN.+'numStr';
//The + unary operator convert a string to a number. -'numStr';
//The - unary operator convert a string to a number and switches the sign. Examples
Number()
, parseInt()
, and parseFloat()
are JS Global functions.Number('3.2');
// 3.2; Converts to integer, float, or NaN.parseInt('3');
// 3; parseFloat('3.2');
// 3.2; The unary operators (+ and -) also convert strings to numbers.
+'42';
// 42; -'3.2';
// -3.2-'-3.2';
// 3.2Regular Expressions
- The RegExp object is used for matching text with a pattern.
Create a Regular Expression
- There are two ways to create a RegExp object.
- Literal notation is preferred, but the constructor function accepts variables as input.
- Literal notation:
/pattern/[flags]
- Constructor function:
new RegExp('exact text'[, 'flags'])
ornew RegExp(/pattern/[, 'flags'])
Examples
Create a regular expression that finds the text "findme", with no flags:
Literal Notation (preferred):
Constructor function (accepts variables):
Passing in a string:
Literal Notation (preferred):
let regex = /findme/;
Constructor function (accepts variables):
Passing in a string:
let regex = new RegExp('findme');Passing in a RegExp literal:
let regex = new RegExp(/findme/);Passing in a variable:
let input = 'findme'
let regex = new RegExp(input);
RegExp global object
- Ref: MDN Global_Objects/RegExp
- RegExp is a JavaScript standard built-in object in the global scope.
- RegExp includes a constructor function, static and instance properties and methods.
More info
RegExp global object
- RegExp is a JavaScript standard built-in object. It is also called a global object because it is attached to the global object (window or global):
RegExp === window.RegExp; // returns true in the browser environment RegExp === global.RegExp; // returns true in the Node.js environment
- RegExp is a constructor function (functions are a type of object).
typeof RegExp; // returns 'function'
- When called with the new keyword, it instantiates a RegExp object.
const re = new RegExp('pattern', 'g');
typeof re; // returns 'object'
RegExp static properties and methods:
- RegExp has some static properties:
Object.getOwnPropertyNames(RegExp); // returns length, name, prototype, input, $_, lastMatch, $&, lastParen, $+, leftContext, $`, rightContext, $', $1, $2, $3, $4, $5, $6, $7, $8, $9,
RegExp Instance properties and methods:
- RegExp literals are instances of the RegExp constructor:
typeof /pattern/; // returns 'object'
/pattern/ instanceof RegExp; // returns true /pattern/.constructor === RegExp; // returns true
- The prototype of a regular expression literal is RegExp.prototype:
Object.getPrototypeOf(/pattern/) === RegExp.prototype; // returns true
- RegExp.prototype contains properties and methods you can call on a RegExp instance.
Object.getOwnPropertyNames(RegExp.prototype); // Returns: constructor, exec, dotAll, flags, global, hasIndices, ignoreCase, multiline, source, sticky, unicode, compile, toString, test
- constructor is a reference to the RegExp() constructor function.
RegExp Literals
Format:
/pattern/[flags];
Flags
g
global search i
case insensitive. You can combine them: gi
m
Perform multiline matching. Examples
Replace "a" with "x":
Multiline matching:
Treat string input as multiple lines. Example: if m is used, ^ and $ change from matching at only the start or end of the entire string to the start or end of any line within the string.
'Replace first "a" only'.replace(/a/, 'x');
// 'Replxce first "a" only''Replace all "a"s globally'.replace(/a/g, 'x');
// "Replxce xll "x"s globxlly"
'Letter A should be replaced'.replace(/a/i, 'x');
// 'Letter x should be replaced'
"All letter A's should be replaced".replace(/a/gi, 'x');
// "xll letter x's should be replxced"
Multiline matching:
Treat string input as multiple lines. Example: if m is used, ^ and $ change from matching at only the start or end of the entire string to the start or end of any line within the string.
const str = `Multi-line matching.
At least one line starts with "a".`;
/^A/.test(str); // false
/^A/m.test(str); // true
Character classes
Ref: MDN Regexp Character_Classes
.
Any single character, except newline or line terminator \w
word character [A-Za-z0-9_] \W
non-word character \d
digit \D
non-digit\s
whitespace character \S
non-whitespace character \char
Escapes characters with special meaning. Inside /chars/ escape these: / \ . + - * ^ = ! | : ? $ ( ) [ ] { } < >
Inside [chars] escape these: ^ ] / and - when between characters
Examples
str = 'Letters 0123, ^_.$%/]\n';
- .
str.replace(/./g, '-');
// '---------------------\n' - \w
str.replace(/\w/g, '-');
// '------- ----, ^-.$%/]\n' - \W
str.replace(/\W/g, '-');
// 'Letters-0123---_------' - \d
str.replace(/\d/g, '-');
// 'Letters ----, ^_.$%/]\n'; - \D
str.replace(/\D/g, '-');
// '--------0123----------'; - \s
str.replace(/\s/g, '-');
// 'Letters-0123,-^_.$%/]-'; - \S
str.replace(/\S/g, '-');
// '------- ----- -------\n'; - \specialCharacter: / \ . + - * ^ = ! | : ? $ ( ) [ ] { } < >
- \^
str.replace(/\^/g, '-');
// 'Letters 0123, -_.$%/]\n''; - \.
str.replace(/\./g, '-');
// 'Letters 0123, ^_-$%/]\n''; - \$
str.replace(/\$/g, '-');
// 'Letters 0123, ^_.-%/]\n' - \/
str.replace(/\//g, '-');
// 'Letters 0123, ^_.$%-]\n' - \]
str.replace(/\]/g, '-');
// 'Letters 0123, ^_.$%/-\n' - \Special characters inside square brackets: \ ^ ] -
- [\^\]]
str.replace(/[\^\]]/g, '-');
// 'Letters 0123, -_.$%/-\n'; str.replace(/[\^_.$%/\]]/g, '-');
// 'Letters 0123, -------\n';
Groups
Ref: MDN Regexp Groups_and_Ranges
Sequential Characters:
| Or:
[ ] Square Brackets:
( ) Parentheses (captured groups):
abc
Find "abc"| Or:
abc|123
Find "abc" or "123"[ ] Square Brackets:
[abc]
Find any character between the brackets [^abc]
Find any character NOT between the brackets [A-Z]
Find any character between the brackets using a range (any uppercase letter) [^A-Z]
Find any chars NOT in the bracket range (any non-uppercase letter character)[\^\]\-\\]
Escape "^", "]", "/". And "-" when it is between characters.( ) Parentheses (captured groups):
(ab|c)
Capture group of characters with parentheses. Find "ab" or "c"(?:chars)
Exclude the captured group from reference. Saves memory.\n
Reference the captured group by sequential number. \1 is the first group left to rt.Examples
Sequential Characters:
/abc/.test('123abcd');
// true, there is "abc" in this string./abc/.test('abXc');
// false, there is is not an "abc" in this string.
| Or:
/abc|123/.test('efg12345');
// true, there is either an "abc" or "123" in this string./abc|123/.test('abxc1203');
// false.
[ ] Square Brackets:
/[abc]/.test('cdef');
// true, there is at least one a, b, or c in this string./[^abc]/.test('abcd');
// true, there are characters other than a, b, and c in this string./[^\d]/.test('01234');
// false, there are no non-digit characters in this string so this test fails./[A-Z]/.test('Joey');
// true, there is at least one capital letter (A-Z) in this string./[^A-Z]/.test('Joey');
// true, there is at least one character that is not a capital letter (A-Z) in this string./[^A-Z]/.test('JOEY');
// false, there are characters that are not capital letters (A-Z) so this test fails./[^A-Z]/.test('JOEY2');
// true, there is at least one character (the number 2) that is not a capital letter (A-Z)./[^A-Z]/.test('JOEY ');
// true, there is at least one character (a space) that is not a capital letter (A-Z).
( ) Parentheses (captured groups):
/(ab|c)/.test('ab');
// true, there is either an "ab" or "c".
Boundaries
Ref: MDN RegExp Assertions
^str Matches from the beginning of the input string.
str$ Matches to the end of the input string.
str$ Matches to the end of the input string.
\bchar Matches any word with char at the beginning of it.
char\b Matches any word with char at the end of it.
\bword\b Match a full word.
\B Find a match not at the beginning/end of a word.
char\b Matches any word with char at the end of it.
\bword\b Match a full word.
\B Find a match not at the beginning/end of a word.
Examples
- /^T/.test('This string starts with a T'); // true
- /X$/.test('This string ends with an X'); // true
- /\.$/.test('This string ends with a period.'); // true. Escape the period with \.
- /^T.*X$/.test('This string starts with a T and ends with an X'); // true, .* means it has 0 or more characters between the T and X.
- /\bJoe/.test('Username is Joey'); // true, contains a word that starts with "Joe".
- /s\b/.test('There are plurals in this string.'); // true, contains a word ending with "s".
- /\bcat\b/.test('cats, category, scat, Cat'); // false, does not contain the word "cat".
- /\bcat\b/i.test('cats, category, scat, Cat'); // true, does contain the word "cat" when case is insensitive.
- /\BT/.test('To, Tim, Tim'); // false, does not contain a T that is not at the beginning of a word.
Quantifiers (numbers of characters or expressions to match)
Ref: MDN RegExp Quantifiers
char?
Matches zero or one occurrence of char.char+
Matches one or more occurences of char. char*
Matches zero or more occurrences of char.char{x}
Matches sequence of x chars.char{x,y}
Matches sequence of x to y chars. char{x,}
Matches sequence of at least x chars. Examples
'oooo123'.replace(/o/,'X');
// "Xooo123", replace the first occurrence of "o".
'oooo123'.replace(/o?/,'X');
// "Xoo123", replace the first occurrence of "o".
'oooo123'.replace(/o+/,'X');
// "X123", replace the first occurrence of one or more "o"s.
'oooo123'.replace(/o{3}/,'X');
// "Xo123", find 3 "o"s and replace.'oooo123'.replace(/o{3,}/,'X');
// "X123", find 3 or more "o"s and replace.'oooo123'.replace(/o{2,3}/,'X');
// "Xo123", find 2 to 3 "o"s and replace.'oooo123'.replace(/o{1,3}/,'X');
// "Xo123", find 1 to 3 "o"s and replace.
/^[A-Za-z\s']+$/.test("Patrick O'Brien");
// true, contains one or more letters, spaces, or apostrophies from beginning to end./^[A-Za-z\s']{3,}$/.test("Patrick O'Brien");
// true, contains at least 3 letters, spaces, or apostrophies from beginning to end./^\d{3}\s?\d{3}-\d{4}$/.test("(415)555-1234");
// true, contains 3 digits, 0 or 1 spaces, 3 digits, "-", and 4 digits from beginning to end.
$1-$9 // Regex properties that reference parenthesized substring matches. This feature is non standard JS so use with caution.
Example
let re = /(\w+)\s(\w+)/; 'John Smith'.replace(re, '$2, $1');
// "Smith, John" RegExp Objects
Call the RegExp constructor functionnew RegExp(pattern[, flags]);
RegExp function (omits new keyword)
RegExp(pattern[, flags])
Example
let regex = new RegExp("l", "gi");
"Hello".match(regex); // ["l", "l"]
Using the constructor function provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.
Escaping
- In string literals \ is an escape character when paired as \b \f \n \r \t \v \0 \' \" \\.
- If not paired with the above it is removed. To keep it you must double escape.
- \s\d\w\t\n\" becomes new RegExp('\\s\\d\\w\t\n\"');
- Addionally, double escape ( ) [
- (1,2,3) becomes new RegExp('\\(1,2,3\\)');
Using variables
- A RegExp literal /.../ cannot include a variable.
- You can pass a variable in the pattern arg when instantiating a RegExp object.
- let name = 'Joey';
- new RegExp('Hello ' + name, 'g'); Search globally for "Hello Joey"
- new RegExp(`Hello ${name}`, 'g'); Using a template literal.
Examples
Test if a document contains the regular expression:
- Start with a document to search:
const data = 'This is a document that contains the letter X';
- RegExp literal: Search the document for the letter "x", case insensitive:
/x/i.test(data); // true
- RegExp object: To include a variable in the regular express you must instantiate a RegExp object.
const letter = 'x'; new RegExp(letter, 'i').test(data); // true
Return each instance of a match into an array:
- Start with a document to search:
const data = 'Cat, category, dog, mouse, cat, cats, copycat, horse, cow';
- RegExp literal: Search the document for the bounded word "cat" that may end with "s", case insensitive, search globally (i.e., find all instances):
data.match(/\bcats?\b/gi); // ["Cat", "cat", "cats"]
- RegExp object: Using a variable in the regular expression:
const animal = 'cat' data.match(new RegExp('\\b' + animal + 's?\\b', 'gi'));data.match(new RegExp(`\\b${animal}s?\\b`, 'gi'));// ["Cat", "cat", "cats"]
RegExp Methods
regexp.test(str); //Tests for a match in a string. Returns true/false.
Example
/lo/.test('hello'); // true
regexp.exec(str);
//Executes a search for a match in a string. Returns an array of information on the first match, or null if no match. To iterate over multiple matches use the str.matchAll() method. Example
(/l/i).exec("hello");
// ["l", index: 2, input: "hello", groups: undefined] String Methods that use RegExp
str.match(regexp);
//Searches a string for a match against a regular expression. Returns an array object with match info of the first match. With the global flag returns an array of all matched values. If no match returns null.str.matchAll(regexp);
//Returns an iterator of all results matching a string against a regular expression, including capturing groups.str.search(regex or str);
//Returns the index position where the first occurrence of the regex occurs. Returns -1 if not found. Global option is ignored.str.replace(regex or substring, replacement str);
//Replaces match(es) with replacement substring and returns the new string.str.split(separator);
Splits string to array using given substring or regexp as the separator. Returns array.Number | Math
Number
- number is a primitive data type.
typeof 7; // returns 'number'
- Arithmetic expressions resolve to a number literal: 5 + 2 resolves to 7
- JS numbers are floating points. They can have decimal points and the number of decimals is not fixed. It floats depending on the value.
- Number symbolic values: Infinity, -Infinity, NaN.
- NaN ("Not a Number"): represents non numbers within the number datatype.
Typeof examples
The typeof operator returns a string indicating the data type of the operand.
Test whether an input value is a number:
typeof 7;
//Returns 'number'typeof 9.99;
//Returns 'number'typeof Infinity;
//Returns 'number'typeof -Infinity;
//Returns 'number'typeof NaN;
//Returns 'number' typeof new Number(7);
//Returns 'object' typeof Number('7');
//Returns 'number'typeof BigInt(9007199254740991);
//Returns 'bigint'typeof 7n;
//Returns 'bigint'Test whether an input value is a number:
let input = 7
typeof input === 'number'; // Returns true
Number global object
- Number is a JavaScript standard built-in object in the global scope.
- Number includes a constructor function, static and instance properties and methods.
- Primitives are temporarily wrapped in an object when instance methods are applied.
More info
Number global object
- Number is a JavaScript standard built-in object in the global scope. It is also called a global object because it is attached to the global object (window or global):
Number === window.Number; // returns true
- Number is a constructor function (functions are a type of object).
typeof Number; // returns 'function'
- When called with the new keyword, it instantiates a Number object.
const numObj = new Object(7); // creates a Number object with value 7
typeof numObj; // returns 'object'
- When called in a non-constructor context (i.e., without the new keyword) it converts the argument to a primitive number:
Number('7'); // converts the string '7' to number 7 Number('Hello'); // converts the string 'Hello' to number NaN Number(true); // converts the boolean true to number 1 Number(false); // converts the boolean false to number 0
Number static properties and methods:
- Number has several static properties and methods:
Object.getOwnPropertyNames(Number); // returns length, name, prototype, isFinite, isInteger, isNaN, isSafeInteger, parseFloat, parseInt, MAX_VALUE, MIN_VALUE, NaN, NEGATIVE_INFINITY, POSITIVE_INFINITY, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER, EPSILON
Number instance properties and methods:
- Number literals are primitive values and not instances of the Number constructor:
typeof 7; // returns 'number'
7 instanceof Number; // returns false
- Number acts as a wrapper around number primitives. JavaScript automatically converts primitive number values to Number objects when an instance method is called them. So number literals have a constructor and prototype:
- Number wrapper object: When a property or method is called on a number primitive value (i.e., a number literal), JavaScript temporarily wraps the primitive with an object by calling new Number(primitive value), applies the property or method, then disposes of the object. So number literals have a constructor and prototype:
(7).constructor === Number; // returns true Object.getPrototypeOf(7) === Number.prototype; // returns true
- Number.prototype contains properties and methods you can call on number values. Below is the full list of instance properties and methods.
Object.getOwnPropertyNames(Number.prototype); // returns constructor, toExponential, toFixed, toPrecision, toString, valueOf, toLocaleString
- constructor is a reference to the Number() constructor function.
BigInt Data Type (ES2020)
Ref: MDN Global_Objects/BigInt
- BigInt: primitive data type. Handles integers larger than the maximum safe integer.
Number.MAX_SAFE_INTEGER
//Returns 9,007,199,254,740,991
7n;
//Append n to a number.BigInt(num);
//Call the BigInt(num) function without the new operator.
Example
Create a BigInt number:
const bigInt = 9007199254740992n;
//Appending n to a number makes it a BigInt.const bigInt = BigInt(9007199254740991 + 1);
//Calling BigInt constructor w/o new makes it a BigInt.bigInt - 1n;
//Returns 9007199254740991nCreate a Number
1) Number Literal:
Numbers are generally created as literals with primitive numbers. Ex: -1, 0, 7, 3.14.Or with expressions that reduce to number literals. Ex: (1 + 5), (4 * 3), (7).
Example
Number literal:
const num = 7;
typeof num;
// Returns 'number'num instanceof Number;
// Returns falseObject.getPrototypeOf(num);
// Returns Number.prototypeObject.getPrototypeOf(num) === Number.prototype;
// true2) Number object (not recommended):
Numbers can be created as objects by calling the constructor function.new Number(value);
//Instantiates a number object, not a primitive.Examples
Number object:
const numObj = new Number(7);
typeof numObj;
// Returns 'object' numObj instanceof Number;
// Returns true Object.getPrototypeOf(numObj);
// Returns Number.prototype numObj;
// Returns // Number {7} as a number object;numObj + 3;
//Returns 10numObj.valueOf();
// Returns 7 as a primitive value.numObj == 7;
// true; converts the object to a primitive for the comparison.numObj === 7;
// false; compares an object with a primitive.Number() function converts values to primitive numbers
Number(value);
//Called without new keyword, converts value to a number primitive.Number(new Number(7)); //7
//Number objects convert to number primitives.- String values convert to a number:
Number('7'); //7
//Digit characters converts to the number.Number(' '); //0
//Empty strings or white space converts to 0.Number('Text'); //NaN
//Otherwise converts to NaN.- Boolean values convert to 0 or 1.
Number(false); //0
//False converts to 0.Number(true); //1
//True converts to 1.Number(null); //0
//Null converts to 0.Number(undefined); //NaN
//Undefined converts to NaN.Number({}); //NaN
//Objects convert to NaN.Number([]); //0
//Empty arrays convert to 0Number(new Date('2025-12-31')); //1767139200000
//Date objs convert to JS timestamp.
Examples
Return 0: null, false, '', ' ', [] convert to 0.
Return Non-Zero Number: number expressions, digit strings, true, date objects
Return NaN: non-digit strings, objects including non-empty arrays, undefined.Number(null);
// 0Number(false);
// 0Number("");
// 0Number(" ");
// 0Number([]);
// 0Return Non-Zero Number: number expressions, digit strings, true, date objects
Number(7);
// 7Number(5+2);
// 7Number(new Number(7));
// 7Number('7');
// 7Number([7]);
// 7Number(true);
// 1Number(new Date('2025-12-31'));
// 1767139200000Number('Hello');
// NaNNumber ('7 Eleven');
// NaN Number([1, 2]);
// NaNNumber({});
// NaNNumber({num: 7});
// NaNNumber(undefined);
// NaNStatic Methods and Number-related Global Functions
Convert String to Integer or Float
Number.parseInt('num');
//Parses string arg, returns an integer. Truncates decimal points. parseInt('num');
//Identical to above.Number.parseFloat('num');
//Parses an argument (converting it to a string first if needed) and returns a floating point number.parseFloat('num');
//Identical to above.Examples
The
parseInt()
and parseFloat()
global functions are equivalent to the Number.parseInt()
and Number.parseFloat()
Number static functions.parseInt('7.9');
// 7; Truncates any decimals.Math.round('7.9');
// 8; Use Math.round instead.parseInt('Eleven');
// NaN; parseInt('7 Eleven');
// 7; Will parse a number until it hits a non number character.parseInt('7 11');
// 7parseInt('Seven 11');
// NaNparseInt(null);
// NaN; Does not convert non-strings to numbers.parseInt(true);
// NaNparseFloat('7.1');
// 7.1; Number.parseFloat('7.1');
// 7.1Test numbers
Number.isFinite(value);
//Determines whether the passed value is a finite number. Returns false if: Infinity, -Infinity, NaN, or if data type is not number.Examples
Number.isFinite and isFinite same result:
Number.isFinite(7); // true
Number.isFinite(Infinity); // false
Number.isFinite(-Infinity); // false
Number.isFinite(NaN); // false
Number.isFinite(0); // true
Number.isFinite(2e64); // true
Number.isFinite(undefined); // false
Number.isFinite does not convert data types:
Number.isFinite('7'); // false;
Number.isFinite(true); // false;
Number.isFinite(false); // false;
Number.isFinite(null); // false;
Number.isFinite(""); // false;
Number.isFinite(" "); // false;
Number.isInteger(value);
//Determine if integer. Returns true/false. Doesn't convert type.Number.isSafeInteger(value);
//Determine whether the passed value is a safe integer (number between -(2^53 - 1) and 2^53 - 1). Returns true/false. Doesn't convert type. Examples
Number.isInteger(7); // true Number.isInteger(-7); // true Number.isInteger(7.0); // true
Number.isInteger(7.1); // false
Number.isInteger("7"); // false
Number.isInteger(NaN); // false Number.isInteger(Infinity); // false Number.isInteger(-Infinity); // false
Number.isSafeInteger(7); // true Number.MAX_SAFE_INTEGER; // Returns 9007199254740991 Number.isSafeInteger(Number.MAX_SAFE_INTEGER); // true Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 1); // false
Number.isNaN(value);
//Returns true if the value is NaN and false if not.Examples
- When converting non-number types to numbers, the same rules of conversion are used as with the Number() function.
Number.isNaN:
Number.isNaN(Math.PI); // false Number.isNaN('7.3'); // false Number.isNaN(NaN); // true Number.isNaN(Number('some text')); // true
Number.isNaN(true); // false
Number.isNaN(false); // false
Number.isNaN(null); // false
Number.isNaN(""); // false
Number.isNaN(" "); // false
Number.isNaN does not convert data types:
Number.isNaN(undefined); // false; Number.isNaN('sometext'); // false; Number.isNaN({}); // false,
Static Properties
Number.MAX_SAFE_INTEGER;
//The maximum safe integer in JavaScript (2^53 - 1 or 9,007,199,254,740,991).Number.MIN_SAFE_INTEGER;
//The minimum safe integer in JavaScript (-(2^53 - 1)).Number.MIN_VALUE;
//The smallest positive representable number—that is, the positive number closest to zero (without actually being zero).Number.MAX_VALUE;
//The largest positive representable number.Number.EPSILON;
//The smallest interval between two representable numbers.Number.NaN;
//Special "Not a Number" value.Number.POSITIVE_INFINITY;
//Special value representing infinity. Returned on overflow.Number.NEGATIVE_INFINITY;
//Special val representing -infinity. Returned on overflow.Instance Methods
numObj.valueOf();
//Returns the wrapped primitive value of a Number object.Convert Number to String
expression.toString();
//Returns the number as a stringexpression.toFixed(digits);
//Returns string. Param: digits after the decimal point. Rounds.expression.toPrecision(digits);
//Returns a string. Param: total number of digits. Rounds. expression.toExponential(fractionalDigits);
//Returns a string representing the number in exponential notation. Rounds.Locales
Ref: MDN Intl/NumberFormatexpression.toLocaleString([locales [, options]]);
//Returns a string using locale format.Examples
Convert number object to number primitive:
Convert number to a string:
new Number(7).valueOf();
//Returns 7Number(new Number(7));
//Returns 7Convert number to a string:
(3.1415).toString();
// "3.1415" (3.1415).toFixed(3);
// "3.142" (3.1415).toPrecision(4);
// "3.142"(1234.5).toExponential(3);
// "1.235e+3" Use Locale:
(1234.5).toLocaleString();
// Uses the language from the user's browser settings.(1234.5).toLocaleString('en-US');
// '1,234.5'(1234.5).toLocaleString('en-US', { style: 'currency', currency: 'USD' });
// '$1,234.50'(1234.5).toLocaleString('de-DE');
// '1.234,5'Math
Ref: MDN Global_Objects/MathMath is a built-in object that has properties and methods for mathematical constants and functions. It does not have a constructor function, or instance properties or methods.
More info
When you apply typeof to a constructor function, it returns 'function'
Math typeof returns 'object':
The Math object contains the following properties and methods:
Math typeof returns 'object':
typeof Math; // returns 'object'
The Math object contains the following properties and methods:
Object.getOwnPropertyNames(Math); // returns abs, acos, acosh, asin, asinh, atan, atanh, atan2, ceil,cbrt, expm1, clz32, cos, cosh, exp, floor, fround, hypot,imul,log, log1p, log2, log10, max, min, pow, random, round, sign,sin, sinh,sqrt, tan, tanh, trunc, E, LN10,LN2, LOG10E, LOG2E, PI, SQRT1_2, SQRT2
Math Properties
Math.PI;
// 3.141592653589793 Math Methods
Math Object has trigonometric, logarithmic, exponential, and other standard mathematical functions.
Math.round(11/5);
// 6 Math.floor(11/5);
// 5 Math.ceil(12.0001);
// 13; Rounds upward to the nearest integer. Math.ceil(Math.PI);
// 4 Math.trunc(12.785);
// 12; Returns only the integer part. Math.max(7, -5, 12, 0, 9);
// 12; Returns the highest value.Math.min(7, -5, 12, 0, 9);
// -5; Returns the lowest value. Math.sqrt(81);
// 9Math.cbrt(27);
// 3, returns the cubic root.Math.hypot(2, 2);
// 2.82842; Square root of the sum of square arguments.Math.pow(x,y);
// Returns the value of x to the power of y. Math.abs(-21);
// 21, Returns the absolute value Math.sign(-834);
// -1, returns 1 if positive, -1 if negative, 0 if 0, and NaN if NaN. Math.random();
// Returns a random number between 0 (inclusive) and 1 (exclusive). sin(); cos(); tan();
// Standard trigonometric functions, with the argument in radians. asin(); acos(); atan(); atan2();
// Inverse trigonometric functions, return values in radians. sinh(); cosh(); tanh();
// Hyperbolic functions, argument in hyperbolic angle. asinh(); acosh(); atanh();
// Inverse hyperbolic functions; return values in hyperbolic angle. pow(); exp(); expm1(); log10(); log1p(); log2();
// Exponential and logarithmic functions. Generate a random number
Function to generate a random number:
function random(min, max) {
return Math.floor(Math.random()*(max-min+1))+min;
}
random(1, 10);
Date
- JS does not have a data type for dates or a date literal syntax.
- Dates are stored as a string or a timestamp number.
- UNIX epoch: Timestamps start from Jan 1, 1970, 00:00:00 UTC.
UNIX timestamp used by computers is the number of seconds since 1/1/1970 UTC.
JS Timestamp: Dates are stored as the number of milliseconds since 1/1/1970 UTC.
Date global object
- Ref: MDN Global_Objects/Date
- Date is a JavaScript standard built-in object in the global scope.
- Date includes a constructor function, static and instance properties and methods.
More info
Date global object
- Date is a JavaScript standard built-in object. It is a global object since it is attached to the global object (window in the browser or global in Node.js):
Date === window.Date; // returns true in the browser environment Date === global.Date; // returns true in the Node.js environment
- Date is a constructor function (functions are a type of object).
typeof Date; // returns 'function'
- When called with the new keyword, it instantiates a Date object.
const date = new Date(); // instantiates an new Date object
typeof date; // returns 'object'
- When called in a non-constructor context (i.e., without the new keyword) it returns the current date string using the system's timezone and language format:
const date = Date(); // returns "current day date time timezone"
Date static properties and methods:
- Date static properties and methods are called on the Date object (e.g., Date.parse())
Object.getOwnPropertyNames(Date); // returns length, name, prototype, now, parse, UTC
Date Instance properties and methods:
- There are no date literals, only date objects.
- Date values are returned as a timestamp number or a string.
- The prototype of a date object is Date.prototype:
Object.getPrototypeOf(new Date() === Date.prototype); // returns true
- Date.prototype contains properties and methods that can be called on a Date instance object.
- Below are the Date instance methods and properties.
Object.getOwnPropertyNames(Date.prototype); // Returns: constructor, toString, toDateString, toTimeString, toISOString, toUTCString, toGMTString, getDate, setDate, getDay, getFullYear, setFullYear, getHours, setHours, getMilliseconds, setMilliseconds, getMinutes, setMinutes, getMonth, setMonth, getSeconds, setSeconds, getTime, setTime, getTimezoneOffset, getUTCDate, setUTCDate, getUTCDay, getUTCFullYear, setUTCFullYear, getUTCHours, setUTCHours, getUTCMilliseconds, setUTCMilliseconds, getUTCMinutes, setUTCMinutes, getUTCMonth, setUTCMonth, getUTCSeconds, setUTCSeconds, valueOf, getYear, setYear, toJSON, toLocaleString, toLocaleDateString, toLocaleTimeString
- constructor is a reference to the Date() constructor function.
Time Zones
- Local Time: taken from the client operating system's time zone.
Intl.DateTimeFormat().resolvedOptions().timeZone
//Returns the client's timezone.- Timezone list: en.wikipedia.org/wiki/List_of_tz_database_time_zones
- UTC: Coordinated Universal Time. Equivalent to GMT time zone.
Time zones are expressed as positive or negative offsets from UTC.
Constructor Function
Create a date object by calling the Date constructor function
- JS has no date literal. Date objects are instantiated from date strings or JS timestamp.
- If time zone is not specified, the local time zone is used as default.
except when using ISO format YYYY-MM-DD which defaults to UTC. - If hours, minutes, or seconds are omitted, the value will be set to zero.
- If day is omitted, day defaults to 1. If month omitted defaults to January.
new Date();
//Returns the current date object. new Date(timestamp);
//Creates date object from JS timestamp.new Date('dateString')
; //Creates date object from a parseable date string. new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
//Date.UTCExamples
const now = new Date();
// Creates date object of the current date/time.const date = new Date('1756719000000');
// Creates date object of the specified timestamp. Create date objects from a date string:
- If time zone is not specified, the local time zone is used.
- Exception to this: if date is formatted as YYYY-MM-DD, then the UTC time zone is used.
new Date('December 31, 2025, 23:59:59');
new Date('December 31, 2025');
new Date('Dec 31, 2025 UTC');
new Date('Dec 31 2025 EST');
new Date('Dec 31 2025');
new Date('2025-12-31');
// YYYY-MM-DD format uses UTC time zone by default.new Date('2025-12-31 PST');
// Uses the specified time zone.Example using Date.UTC() method's format:
- Uses the UTC time zone.
- Month uses 0 index so January is 0, February is 1, December is 11.
new Date('2025, 11, 31, 23, 59, 59'); // same as 'December 31, 2025, 23:59:59 UTC'
Date() static function
Date();
//Returns current date string. Does not create an object and does not take args. Static Methods
Convert date strings or UTC numbers to JS timestamp integer
Date.parse('dateString');
//Parses date string. Returns JS timestamp number. - ISO 8601 Extended format: Ref: tc39.es/ecma262/#sec-date-time-string-format
- Ideally use ISO 8601 Extended format.
'YYYY-MM-DD'
|'YYYY-MM-DDThh:mm:ss.sssZ'
. T is for time.- Z is for zero offset from UTC. For other offsets use +/-hh:mm
- Use non-standard date string formats with caution. If other formats are used, the client's local time zone will be used, unless time zone or offset is specified.
Examples
ISO 8601 Format: Time defaults to 00:00:00. Time zone offset defaults to Zero.
The below examples all return timestamp: 1767139200000
The below examples all return timestamp: 1767139200000
Date.parse('2025-12-31');
Date.parse('2025-12-31T00:00:00Z'); // Zero offset
Date.parse('2025-12-31T00:00:00+00:00'); // Zero offset
Date.parse('2025-12-30T16:00:00-08:00'); // Offset -8 hours from UTC
To use local time zone, leave out any offset:
Date.parse('2025-12-31T00:00:00'); // Local time zone
Non-standard date strings (use with caution). Default to local time zone.
Date.parse('31 December, 2025'); // 1767168000000To avoid confusion, best not to use digital month (other than ISO 8601 format):
Date.parse('31 Dec 2025'); // 1767168000000
Date.parse('31 Dec 2025, 23:59:59'); // 1767250799000 Date.parse('31 Dec 2025, 23:59:59 PST'); // 1767254399000, specifying time zone Date.parse('31 Dec 2025, 23:59:59 -08:00'); // 1767254399000, specifying offset from UTC
US date format is MM-DD-YYYY:
Date.parse('12-31-2025'); // Returns local timestampEuropean date format is DD-MM-YYYY:
Date.parse('31-12-2025'); // Returns NaN
Date.UTC(year, monthIndex[, day[, hour[, minute[, second[, millisecond]]]]]);
//Takes comma-delimited date and time parameters. Returns the JS timestamp. Uses UTC time zone.- MonthIndex is digit from 0 to 11. 0 = January. 11 = December.
- Day 0 is last day of prev month. -1 is second to last day of prev month. etc.
Examples
Date.UTC(2025, 11, 31);
// 1767139200000; For Dec 31, 2025. Time defaults to 00:00:00.Date.UTC(2025, 11, 31, 23, 59, 59);
// 1767225599000; For Dec 31, 2025 end of day UTC time zone.Date.now();
//Returns the current date and time as a JS timestamp integer. Example
Date.now();
// 1571606417357Instance Methods
Get timestamp:
date.valueOf();
//Returns the JS timestamp number (milliseconds since 1/1/1970 UTC).date.getTime();
//Returns the JS timestamp number (milliseconds since 1/1/1970 UTC). Get string in local time and format:
date.toString();
//Returns a string representing the date in local time zone and format.date.toDateString();
//Returns the "date" portion in local time time zone and format.date.toTimeString();
//Returns the "time" portion in local time time zone and format.Get string in UTC time zone:
date.toUTCString();
//Converts a date to a string using the UTC time zone.e.g., 'Tue, 02 Sep 2025 00:30:00 GMT'
date.toISOString();
//Converts date to ISO 8601 Extended Format string: 'YYYY-MM-DDThh:mm:ss.sssZ'. T is for time. Uses UTC time zone. Z is for zero offset. date.toISOString().slice(0, 10)
//Substring just the date portion: 'YYYY-MM-DD'.date.toJSON();
//Same as toISOString(). Intended for use by JSON.stringify().Examples
const date = new Date('2025-09-01, 17:30:00 UTC');
//Create date object using UTC time zone.date.valueOf();
//Returns 1756747800000. Returns the object's primitive value, in the case of Date is a number representing the number of milliseconds since 1/1/1970 UTC.
date.getTime();
//Returns 1756747800000date.toString();
//Returns something like 'Mon Sep 01 2025 10:30:00 GMT-0700 (Pacific Daylight Time)'date.toDateString();
//Returns something like 'Mon Sep 01 2025'date.toTimeString();
//Returns something like '10:30:00 GMT-0700 (Pacific Daylight Time)'date.toUTCString();
//Returns 'Mon, 01 Sep 2025 17:30:00 GMT'date.toISOString();
//Returns '2025-09-01T17:30:00.000Z'date.toISOString().slice(0, 10)
//Returns: '2025-09-01'date.toJSON();
//Returns '2025-09-01T17:30:00.000Z'Customize Format with Locales and Options
Ref: MDN toLocaleString
Dates are given in local time.
Localizes the date and time format based on language-region (e.g.,
Defaults to system language.
year: 'numeric' (e.g., 2025) | '2-digit' (e.g., 25)
month: 'numeric' | '2-digit' | 'short' (e.g., 'Sep') | 'long' (e.g., 'September')
day: 'numeric' (e.g., 1) | '2-digit' (e.g., 01)
minute: 'numeric' | '2-digit'
second: 'numeric' | '2-digit'
timeZoneName: 'long' | 'short' | 'shortOffset' | 'longOffset' | 'sortGeneric' | 'longGeneric'
Dates are given in local time.
date.toLocaleString([locales[, options]]);
//Return date string. Format locale and options. Locales argument:
Unicode locale identifier. Ref: MDN Global_Objects/Intl#locale.Localizes the date and time format based on language-region (e.g.,
'en-US'
, 'en-GB'
).Defaults to system language.
navigator.language
//Returns the system's locale.Options argument:
Set specific date and time formats. Ref: MDN DateTimeFormat#parametersyear: 'numeric' (e.g., 2025) | '2-digit' (e.g., 25)
month: 'numeric' | '2-digit' | 'short' (e.g., 'Sep') | 'long' (e.g., 'September')
day: 'numeric' (e.g., 1) | '2-digit' (e.g., 01)
weekday: 'short' (e.g., Thu) | 'long' (e.g., Thursday)
hour: 'numeric' (e.g., 1) | '2-digit' (e.g., 01)minute: 'numeric' | '2-digit'
second: 'numeric' | '2-digit'
timeZoneName: 'long' | 'short' | 'shortOffset' | 'longOffset' | 'sortGeneric' | 'longGeneric'
Examples
Use toLocaleString() to customize the date format:
const date = new Date('2025-09-01 17:30:00');
- //Display date based on the default system locale.
date.toLocaleString(); // (e.g., en-US default) '9/1/2025, 5:30:00 PM'
- //Display date using English-US locale, then using English-Great Britain locale.
date.toLocaleString('en-US'); // '9/1/2025, 5:30:00 PM' date.toLocaleString('en-GB'); // '01/09/2025, 17:30:00'
- //Set locale to en-US and display date/time as: '09/01/2025, 05:30:00 PM'
date.toLocaleString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit'});
- //Set locale to en-US and display date/time as: '9/1/25, 5:30:00 PM'
date.toLocaleString('en-US', {year: '2-digit', month: 'numeric', day: 'numeric', hour: 'numeric', minute: '2-digit'});
- //Set locale to en-US and display date/time as: 'Sep 1, 2025, 5:30 PM'
date.toLocaleString('en-US', {year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit'});
- //Set locale to en-US and display date/time as: 'Thursday, September 1, 2025, 5:30 PM Pacific Daylight Time'
date.toLocaleString('en-US', {year: 'numeric', month: 'long', day: 'numeric', weekday: 'long', hour: 'numeric', minute: '2-digit', timeZoneName: 'long'});
date.toLocaleDateString([locales [, options]])
//Return string, format language and options. Examples
const date = new Date('2025-09-01');
- //Display date based on the default system locale.
date.toLocaleDateString(); // (e.g., en-US default) '9/1/2025'
- //Display date using English-US locale, then using English-Great Britain locale.
date.toLocaleDateString('en-US'); // '9/1/2025' date.toLocaleDateString('en-GB'); // '01/09/2025'
- //Set locale to en-US and display date/time as: '09/01/2025'
date.toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'});
- //Set locale to en-US and display date/time as: '9/1/25'
date.toLocaleDateString('en-US', {year: '2-digit', month: 'numeric', day: 'numeric'});
- //Set locale to en-US and display date/time as: 'Sep 1, 2025'
date.toLocaleDateString('en-US', {year: 'numeric', month: 'short', day: 'numeric'});
- //Set locale to en-US and display date/time as: 'Thursday, September 1, 2025'
date.toLocaleDateString('en-US', {year: 'numeric', month: 'long', day: 'numeric', weekday: 'long'});
date.toLocaleTimeString([locales [, options]])
//Return string, format language and options. Examples
const date = new Date('2025-12-31 09:30:00 PST'); date.toLocaleTimeString(); // "9:30:00 AM" date.toLocaleTimeString('en-US', {hour: 'numeric', minute: '2-digit'}); // "9:30 AM" date.toLocaleTimeString('en-US', {hour: '2-digit', minute: '2-digit'}); // "09:30 AM"
Get number values from the date object
Get date number components in local time (host system settings):
date.getFullYear()
//Returns the year (4 digits for 4-digit years).date.getMonth();
//Returns the month (0–11). Jan=0, Dec=11.date.getDate();
//Returns day of the month (1–31).date.getDay();
//Returns the day of the week (0–6). Sun=0, Sat=6.date.getHours();
//Returns the hour (0–23).date.getMinutes();
//Returns the minutes (0–59).date.getSeconds();
//Returns the seconds (0–59).date.getMilliseconds();
//Returns the milliseconds (0–999).date.getTimezoneOffset();
//Returns difference in minutes from local time zone to UTC.Get date number components in UTC time zone:
date.getUTCFullYear();
//Returns the year (4 digits for 4-digit years).date.getUTCMonth();
//Returns the month (0–11). Jan=0, Dec=11.date.getUTCDate();
//Returns day of the month (1–31).date.getDay();
//Returns the day of the week (0–6).date.getUTCDay();
//Returns the day of the week (0–6). Sun=0, Sat=6.date.getUTCHours();
//Returns the hour (0–23).date.getUTCMinutes();
//Returns the minutes (0–59).date.getUTCSeconds();
//Returns the seconds (0–59).date.getUTCMilliseconds();
//Returns the milliseconds (0–999).Examples
const date = new Date('2022-12-31 09:30:00 PST');
Local time zone:
date.getFullYear()
// 2022date.getMonth();
// 11; Returns the month number using 0 index in local time. Dec is 11.date.getDate();
// 31; date.getDay();
// 6; 0 indexed. 0 is Sun, 1 is Mon, 6 is Sat.date.getHours();
// 9; Returns number 0 to 23. date.getMinutes();
// 30; Returns number 0-59.date.getTimezoneOffset();
// 480; Returns the difference, in minutes, from local time zone to UTC.UTC time zone:
date.getUTCFullYear();
// 2022date.getUTCMonth();
// 11; Returns the month number using 0 index in local time. Dec is 11.date.getUTCDate();
// 31 date.getDay();
// 6; 6 is Sat.date.getUTCDay();
// 6; 0 indexed. 0 is Sun, 1 is Mon, 6 is Sat.date.getUTCHours();
// 9; Returns number 0 to 23. date.getUTCMinutes();
// 30; Returns number 0-59.Set Date and Time Values in Date objects
Below methods return the new JS timestamp (milliseconds since 1/1/1970 UTC).
Timestamp (milliseconds since 1/1/1970 UTC):
Timestamp (milliseconds since 1/1/1970 UTC):
date.setTime(timestamp);
//Sets the Date object to the timestamp date.Set date number components in local time (host system settings):
date.setFullYear(year[, monthIndex[, date]]);
//Set year. Optionally set month, date.date.setMonth(monthValue[, dayValue]);
//Month is 0 indexed: Jan=0, Feb=1, Dec=11.date.setDate(dayValue);
//1-31. 0 is last day of prev month. -1 is 2nd to last day of prev month.date.setHours(hours[, minutes[, seconds[, ms]]]);
//Set hour 0-23. Optionally: hour, minutes.date.setMinutes(minutes[, seconds[, ms]]);
date.setSeconds(seconds[, ms]);
date.setMilliseconds(ms);
Set date number components in UTC time:
date.setUTCFullYear(year[, monthIndex[, date]]);
date.setUTCMonth(monthValue[, dayValue]);
//Month is 0 indexed (0-11).date.setUTCDate(dayValue);
//Set the day of the month.date.setUTCHours(hours[, minutes[, seconds[, ms]]]);
//Set hours (0-23).date.setUTCMinutes(minutes[, seconds[, ms]]);
date.setUTCSeconds(seconds[, ms]);
date.setUTCMilliseconds(ms);
Examples
Examples setting multiple values:
Local Time:
const date = new Date('2025-12-31 09:30:00 -8:00');
(-8 hours offset from UTC) date.setFullYear(2026, 0, 1);
// Jan 1, 2026, 9:30, -8:00; Set year, month and date.date.setMonth(1, 2);
// Feb 2, 2026 9:30 -8:00; Set month and date.date.setDate(3);
// Feb 3, 2026 9:30 -8:00date.setDate(0);
// Jan 31, 2026 9:30 -8:00; Set date to the last date of the previous month.date.setDate(-1);
// Dec 30, 2025 9:30 -8:00; Set the date to the second to last date of the previous month.date.setHours(8, 5, 30);
// Dec 30, 2025 8:05:30 -8:00date.setMinutes(0, 0);
// Dec 30, 2025 8:00:00 -8:00UTC Time:
const date = new Date('2025-12-31 09:30:00 UTC');
date.setUTCFullYear(2026, 0, 1);
// Jan 1, 2026, 9:30, UTC; Set year, month and date.date.setUTCMonth(1, 2);
// Feb 2, 2026 9:30 UTC; Set month and date.date.setUTCDate(3);
// Feb 3, 2026 9:30 UTCdate.setUTCDate(0);
// Jan 31, 2026 9:30 UTC; Set date to the last date of the previous month.date.setDate(-1);
// Dec 30, 2025 9:30 UTC; Set the date to the second to last date of the previous month.date.setUTCHours(8, 5, 30);
// Dec 30, 2025 8:05:30 UTCdate.setUTCMinutes(0, 0);
// Dec 30, 2025 8:00:00 UTCArray
- Arrays are not their own data type.
typeof [];
// 'object' - Arrays store multiple values (called elements) in a single variable.
- [] operators initialize an array literal.
- Use index numbers starting with 0 to access the elements.
Array global object
- Ref: MDN Global_Objects/Array
- Array is a JavaScript standard built-in object in the global scope.
- Array includes a constructor function, static and instance properties and methods.
More info
Array global object
- Array is a JavaScript standard built-in object. It is also called a global object because it is attached to the global object (window or global):
Array === window.Array; // returns true in the browser environment Array === global.Array; // returns true in the Node.js environment
- Array is a constructor function (functions are a type of object).
typeof Array; // returns 'function'
- Array when called with or without the new keyword will instantiate an Array object.
const arr2 = new Array('cherry', 'watermelon', 'peach'); const arr3 = Array('mango', 'tangerine', 'pomagranite');
Array static properties and methods:
- Array static properties:
Object.getOwnPropertyNames(Array); // returns length, name, prototype, isArray, from, of
Array Instance properties and methods:
- Array literals are instances of the Array constructor:
typeof []; // returns 'object'
[] instanceof Array; // returns true [].constructor === Array; // returns true
- The prototype of an array literal is Array.prototype:
Object.getPrototypeOf([]) === Array.prototype; // returns true
- Array.prototype contains properties and methods you can call on an Array instance.
Object.getOwnPropertyNames(Array.prototype); // Returns: length, constructor, concat, copyWithin, fill, find, findIndex, lastIndexOf, pop, push, reverse, shift, unshift, slice, sort, splice, includes, indexOf, join, keys, entries, values, forEach, filter, flat, flatMap, map, every, some, reduce, reduceRight, toLocaleString, toString, at, findLast, findLastIndex
- constructor is a reference to the Array() constructor function.
Create an Array
1) Array literal (preferred):
const arr = ['a', 'b', 'c', 'd', 'e'];const nums = [1, 2, 3, 4, 5];
const objs = [{name: 'Joey', age: 22}, {name: 'Sheena', age: 29}];
const arr2a = new Array(elem0[, elem1[, ...[, elemN]]]);Note: if arg is a single integer, creates array with that number of undefined elems.
const arr2b = Array(elem0[, elem1[, ...[, elemN]]]);
new Array(num);
Examples
With multiple non-integer elements as args:
Both create arrays ['a', 'b', 'c', 'd', 'e']
const arr = new Array('a', 'b', 'c', 'd', 'e');
const arr2 = Array('a', 'b', 'c', 'd', 'e');
Both create arrays ['a', 'b', 'c', 'd', 'e']
With a single postive integer as the arg:
const arr3 = new Array(3);
arr3;
returns [undefined, undefined, undefined];3) Array.of(elem0[, elem1[, ...[, elemN]]]) static method
Similar to using new Array() except, a single number arg creates a one elem array.
Similar to using new Array() except, a single number arg creates a one elem array.
const arr3 = Array.of(5);
// numArr is [5].Example
const arr = Array.of('a', 'b', 'c', 'd', 'e');
Creates array instance ['a', 'b', 'c', 'd', 'e']
Get and Set Array Elements
Get element valuearr[index];
//Returns elem value. If elem doesn't exist, returns undefined.arr[arr.length - 1];
//Returns the last elem value.Examples
Arrays are zero indexed so the first element is arr[0], the second is arr[1]
const arr = ['a', 'b', 'c']; arr[0]; // returns 'a' arr[1]; // returns 'b' arr[arr.length - 1]; // returns 'c' arr[7]; // returns undefined
Set element value
arr[index] = newValue; //Changes the value of the element at the given index.
arr[index] = newValue; //Changes the value of the element at the given index.
Example
Change the values of the second and last elements. Arrays are zero indexed so the first element is index 0, the second is index 1.
const arr = [1, 2, 3];
arr[1] = 'b';
arr[arr.length - 1] = 'c';
arr; // returns [1, 'b', 'c']
Static Methods
Array.isArray(value)
//Determines if value is an Array. Returns true/false.Example
Array.isArray([1, 2, 3, 4, 5]);
// trueInstance Properties
arr.length;
//Returns number of elems in the array.arr.length = n;
//Sets the number of elems in the array and returns that number. If more than actual length, undefined elems are added. If less, excess elems are removed.Examples
const arr = ['a', 'b', 'c', 'd', 'e'];
arr.length;
// returns 5
arr.length = 7;
// returns 7. Changes arr to ['a', 'b', 'c', 'd', 'e', undefined, undefined]
arr.length = 3;
// returns 3. Changes arr to ['a', 'b', 'c']
Instance Methods
Mutator Methods: Add/update/remove array elements
Mutator methods change the underlying array.
Add/remove elements at start/end of array:
arr.shift();
//Removes element from beginning of array and returns it.arr.unshift(elem);
//Adds element to beginning of array. Returns new arr length.arr.pop();
//Removes element from end of array and returns it.arr.push(elem);
//Adds element to end of array. Returns new arr length.Examples
Remove elements from the beginning and end of the array:
const arr = [1, 2, 3]; arr.shift(); // returns 1, removes first elem from arr. arr.pop(); // returns 3, removes last elem from arr. arr; // returns [2]
Add elements to the beginning an end of the array:
const arr = [1, 2, 3];
arr.unshift('a');
arr.push('z');
arr;
// returns ['a', 1, 2, 3, 'z']
Add/change/remove elements in middle of array:
arr.splice(index, 1);
//Remove element from arr. Return it as new array.arr.splice(startIndex[, deleteCount]);
//Remove items from arr. Return them as new array. Examples, including indexOf() to find the index
const arr ['a','b', 'c', 'd','e'];
- Remove element at index 3.
arr.splice(3, 1); //arr is now ['a','b','c','e']
- Remove two elems starting at index 1.
arr.splice(1, 2); //arr is now ['a','d','e']
- To remove all elems starting from the index in arg 1, leave out the count arg.
arr.splice(2); //arr is now ['c','d','e']
- Remove the last 2 elements. Negative numbers start backward from end of array.
const nums = [1, 2, 3, 4, 5]; arr.splice(-2); //arr is now ['a','b','c']
- IndexOf() finds the index. Use conditional to ensure index 0 or higher exists.
- Find index and remove elem 'c'.
const idx = arr.indexOf('c'); if (idx >= 0) arr.splice(idx, 1); //arr is now ['a','b','d','e']
arr.splice(startIndex[, deleteCount[, item1[, item2[, ...]]]]);
//Replace items. Examples, including indexOf() to find the index
const arr = ['a', 'b', 'c', 'd', 'e'];
- Starting at index 1, replace three elements with elem 'TBD'.
arr.splice(1, 3, 'TBD'); //arr is now ['a', 'TBD', 'e']
- Starting at index 2, replace one elem with elems 'c1', 'c2', 'c3'.
arr.splice(2,1,'c1','c2','c3'); //arr is now ['a','b','c1','c2','c3','d','e']
- Replace elem, putting replaced elems in new array:
- Relace elem at index 2 with 'newC'. Place the removed elem in array replacedElems.
const replacedElems = arr.splice(2, 1, 'newC'); //arr is now ['a','b','newC','d','e'], replacedElems is ['c']
- IndexOf() finds the index. Use conditional to ensure index 0 or higher exists.
- Find index of elem 'b'. Replace three elements starting with elem 'b' with 'TBD'.
const idx = arr.indexOf('b'); if (idx >= 0) arr.splice(idx, 3, 'TBD'); //arr is now ['a','TBD','e']
arr.splice(startIndex, 0, item1[, item2[, ...]]]]);
//Add items. Examples, including indexOf() to find the index
const arr = ['a', 'b', 'c', 'd', 'e'];
- Insert 'c1' at index 3.
arr.splice(3, 0, 'c1'); //arr is now ['a','b','c','c1','d','e']
- IndexOf() finds the index. Use conditional to ensure index 0 or higher exists.
- Find index of elem 'c'. Insert elements 'c1', 'c2', 'c3' after it.
const idx = arr.indexOf('c'); if (idx >= 0) arr.splice(idx + 1, 0, 'c1', 'c2', 'c3'); //arr is now ['a','b','c','c1','c2','c3','d','e']
Find index of element by it's value:
const i = arr.indexOf(val);
arr[i] = newVal;
//Assign elem to a new value.Examples
const arr = ['a', 'b', 'c', 'd', 'e'];
Find index of element 'd'
let i = arr.indexOf('d'); // returns 3Change element from 'd' to 'X'.
arr[i] = 'X'; // arr is now ['a', 'b', 'd', 'X', 'e']Remove element.
arr.splice(i, 1); // arr is now ['a', 'b', 'd', 'e']
Array of objects: add, update, and remove elems
arr.push(newObj);
//Add object to array.let i = arr.findIndex((elem) => obj.prop === propVal);
//Find an obj by its prop.arr[i] = updatedObj;
//Assign index to updated object.arr.splice(i, 1);
//Remove obj from the array.Example
const users = [{id: 1, name: 'Joey'}, {id: 2, name: 'Sheena'}, {id: 3, name: 'Johnny'}];
Find item index by object property value, and set to variable i
const i = users.findIndex((user) => user.id === 1); // returns index 0
Add user obj user4.
const user4 = { id: 4, name: 'Judy' }; users.push(user4);
Update user at index i, replacing it with the below.
const user1 = { id: 1, name: 'Joseph' }; users[i] = user1;Or just change the property:
users[i].name = 'Joseph';
Remove user at index i.
users.splice(i, 1);
users; // returns [{id: 2, name: 'Sheena'}, {id: 3, name: 'Johnny'}, {id: 4, name: 'Judy'}]
Other Mutator Methods
arr.sort([compareFunction]);
//Sorts the elements in place and returns the modified array. Default compare function examples
The default compare function: Undefined elements are sorted to the end of the array. All other elements are converted to strings and compared by UTF-16 code unit order (wikipedia.org/wiki/List_of_Unicode_characters).
Default order: 0-9, then uppercase letters, then lower case letters.
Numbers are treated as individual characters so the character 1 in 10 comes before 9.
['cat', 'eel', 'ant', 'bee', 'dog'].sort();
// returns ['ant', 'bee', 'cat', 'dog', 'eel']Default order: 0-9, then uppercase letters, then lower case letters.
['ant', 'Bird', 'cat', 9, 10].sort();
// returns [10, 9, 'Bird', 'ant', 'cat']Numbers are treated as individual characters so the character 1 in 10 comes before 9.
arr.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
//Case insensitive, ascarr.sort((a, b) => b.localeCompare(a, 'en', { sensitivity: 'base' }));
//Case insensitive, descnums.sort((a, b) => a - b);
//Numbers in ascending order.nums.sort((a, b) => b - a);
//Numbers in descending order. objs.sort((a, b) => a.prop.localeCompare(b.prop, 'en', { sensitivity: 'base' }));
//Obj propertyExamples
To sort numbers or to make the sort case insensitive, define the compareFunction.
If compare result:
Sort Array of Objects:
// Sort numeric property
// Sort string property
compareFunction(a, b) { return statement; }
If compare result:
- is less than 0, then a comes before b.
- is greater than 0, then b comes before a.
- returns 0, leave a and b unchanged with respect to each other.
Sort Strings, case insensitive:
Sort strings case insensitive in ascending order:
// returns ['ant', 'Bee', 'cat', 'dog', 'Eel']
Sort strings case insensitive in ascending order:
['cat', 'Eel', 'ant', 'Bee', 'dog'].sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
// returns ['ant', 'Bee', 'cat', 'dog', 'Eel']
Sort strings case insensitive in descending order:
// returns ['Eel', 'dog', 'cat', 'Bee', 'ant']
['cat', 'Eel', 'ant', 'Bee', 'dog'].sort((a, b) => b.localeCompare(a, 'en', { sensitivity: 'base' }));
// returns ['Eel', 'dog', 'cat', 'Bee', 'ant']
Sort Numbers:
Sort numbers in ascending order:
Step by step:
Sort numbers in decending order:
Sort numbers in ascending order:
[7, -3, 21, 0].sort((a, b) => a - b);
// [-3, 0, 7, 21] Step by step:
(7, -3) => 7 - -3 equals 10. 10 > 0 so switch them: [-3, 7, 7, 21]
(7, 21) => 7 - 21 equals -14. -14 < 0 so leave them: [-3, 7, 21, 0]
(21, 0) => 21 - 0 equals 21. 21 > 0 so switch them: [-3, 7, 0, 21]
(7, 0) => 7 - 0 equal 7. 7 > 0 so switch them: [-3, 0, 7, 21]
(-3, 0) => -3 - 0 equal -3. -3 < 0 so leave them: [-3, 0, 7, 21]
(7, 21) => 7 - 21 equals -14. -14 < 0 so leave them: [-3, 7, 21, 0]
(21, 0) => 21 - 0 equals 21. 21 > 0 so switch them: [-3, 7, 0, 21]
(7, 0) => 7 - 0 equal 7. 7 > 0 so switch them: [-3, 0, 7, 21]
(-3, 0) => -3 - 0 equal -3. -3 < 0 so leave them: [-3, 0, 7, 21]
Sort numbers in decending order:
[7, -3, 21, 0].sort((a, b) => b - a);
// [21, 7, 0, -3]Sort Array of Objects:
const users = [{name: 'Joey', age: 31}, {name: 'Sheena', age: 22}, {name: 'DeeDee', age: 19}];
// Sort numeric property
users.sort((a, b) => a.age - b.age);
// Sort string property
users.sort((a, b) => a.name.localeCompare(b.name, 'en', { sensitivity: 'base' }));
arr.reverse();
Transposes the elements in place. Changes and returns underlying array. Example
const arr = [1, 2, 3];
arr.reverse();
// [3, 2, 1]arr.fill(value[, startIndex[, endIndex]]);
//Fills array from start index to the element before the end index with the first argument's value. Changes and returns underlying array. Examples
const arr = ['a', 'b', 'c', 'd', 'e'];
arr.fill('-', 1, 3);
// ["a", "-", "-", "d", "e"]; Starts on the start index. Ends just before the end index.arr.fill('-');
// ["-", "-", "-", "-", "-"]; Without a start and end index it changes all elements.arr.fill('-', 2);
// ["-", "-", "c", "d", "e"]; Without an end index it changes all elements from the start index to the end.arr.copyWithin(targetIndex[, startIndex[, endIndex]]);
//Shallow copies array elements from startIndex to one before the endIndex and pastes them at the targetIndex, overwriting the existing elements. Changes and returns underlying array.Examples
const arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
arr.copyWithin(0,2,4);
// ["c", "d", "c", "d", "e", "f", "g"]; Copies elements starting at index 2 ending just before index 4 (i.e., 'c' and 'd') to the targetIndex 0.arr.copyWithin(4, 0, 2);
// ["a", "b", "c", "d", "a", "b", "g"]; Copies elements at index 0 and 1 to targetIndex 4.Accessor Methods (Returns representation of an array. Doesn't modify array)
arr.slice([beginIndex[, endIndex]]);
//Return extracted array from beginIndex to the element before endIndex without changing the original.Examples, includes: shallow copy, indexOf() to find the index
const arr = ['a', 'b', 'c', 'd', 'e'];
- Copy two elems starting at index 1 (so ending before index 3).
const partialCopy = arr.slice(1, 3); //partialCopy is ['b','c']
- Copy all elems from index 2 on. Leave out endIndex to copy the remaining elems.
const partialCopy = arr.slice(2); //partialCopy is ['c','d','e']
- Copy last 2 elems. Negative numbers start backward from end of array.
const partialCopy = arr.slice(-2); //partialCopy is ['d','e']
- Shallow copy: Copy all the elems by leaving out the args.
const arrCopy = arr.slice(); //arrCopy is ['a','b','c','d','e']
- Alternatively use the spread syntax inside an array literal.
const arrCopy = [...arr];
- IndexOf() finds the index of the value passed in if it is in the array.
- Find element with value 'c' and copy that element and those after it to the new array named partialCopy.
const i = arr.indexOf('c'); const partialCopy = arr.slice(i); //partialCopy is ['c','d','e']
arr.concat([value1[, value2[, ...[, valueN]]]]);
//Joins elements or other arrays to an array. Returns new array without changing original array. Examples, including reassign arr to return value
const arr = ['a', 'b', 'c', 'd', 'e'];
Concatenate new values:
Create array named newArr that concatenates 'f', 'g', 'h' to arr:
Create array named newArr that concatenates 'f', 'g', 'h' to arr:
const newArr = arr.concat('f', 'g', 'h');
// newArr is ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] while arr is unchanged.
Concatenate array:
Create array named newArr that adds nums to the end of arr:
Concatenate array:
Create array named newArr that adds nums to the end of arr:
const nums = [1, 2, 3];
const newArr = arr.concat(nums);
// newArr is ['a', 'b', 'c', 'd', 'e', 1, 2, 3] while arr and nums are unchanged.
Reassign variable to result:
Arr.concat() returns a new array without changing the underlying array.
To change arr to the new concatenated array, reassign it to the return value.
Add 'f', 'g', 'h' onto the end of arr.
Arr.concat() returns a new array without changing the underlying array.
To change arr to the new concatenated array, reassign it to the return value.
let arr = ['a', 'b', 'c', 'd', 'e'];
Add 'f', 'g', 'h' onto the end of arr.
arr = arr.concat('f', 'g', 'h'); //arr is now ['a','b','c','d','e','f','g','h']
Add nums to the end of arr:
const nums = [1, 2, 3];
arr = arr.concat(nums); //arr is now ['a','b','c','d','e',1,2,3]
arr.join([separator]); //Joins all elems of array converting to a string. Returns the string.
Examples, including putting "and" before last elem
Like toString but allows you to specify the separator.
const arr = ['a', 'b', 'c', 'd', 'e'];
arr.join(); // "a,b,c,d,e"; Default separator is comma.
arr.join(', '); // "a, b, c, d, e"; Add a space after the comma.
arr.join('-'); // "a-b-c-d-e";
arr.join(' '); // "a b c d e";
arr.join(''); // "abcde";
Put "and" before last element:
const str = arr.slice(0, -1).join(', ') + ', and ' + arr.slice(-1);
returns "a, b, c, d, and e"
arr.toString();
//Returns string representation of array separated with commas. More details
Like arr.join(',') except you can't choose the separator.
Elements are separated by commas with no space after the comma.
ToString() is an Object.prototype method inherited by Array.
const arr = ['a', 'b', 'c', 'd', 'e'];
arr.toString(); // returns "a,b,c,d,e".
Search methods
arr.indexOf(searchElement[, fromIndex]);
//Searches the array for searchElement and returns the index of the first match. Returns -1 if no match.Example
const users = ['Joey', 'Sheena', 'Johnny', 'Joey', 'DeeDee']; users.indexOf('Joey'); // returns 0
arr.lastIndexOf(searchElement[, fromIndex]);
//Searches array for searchElement and returns the index of the last match. Returns -1 if no match. Examples
lastIndexOf works like indexOf, but starts at the end and searches backwards.
const users = ['Joey', 'Sheena', 'Johnny', 'Joey', 'DeeDee']; users.lastIndexOf('Joey'); // returns 3
arr.findIndex(callback(element[, index[, array]])[, thisArg]);
//Returns index of first elem that passes a test in a function. If none then returns -1. Example
Parameters:
1) callback: Function to test for each element, taking three arguments:
1) callback: Function to test for each element, taking three arguments:
1a) element: The current element being processed in the array.
1b) index (optional): The index of the current element being processed in the array.
1c) array (optional): The array findIndex was called upon.
2) thisArg (optional): Value to use as this when executing callback.
const ages = [20, 16, 19, 24, 26, 19];
ages.findIndex((age) => age >= 21); // returns 3
arr.includes(searchElement[, fromIndex]);
(ES2016) //Searches for elem in array. Returns true/false. Example
const users = ['Joey', 'Sheena', 'Johnny', 'Judy', 'DeeDee']; users.includes('Judy'); // returns true
arr.some(callback(element[, index[, array]])[, thisArg]);
//Return true if callback returns true for at least one item in the array.Example
Parameters:
1) callback: Function to test for each element, taking three arguments: 1a) element: The current element being processed in the array.
1b) index (optional): The index of the current element being processed in the array.
1c) array (optional): The array some was called upon.
2) thisArg (optional): Value to use as this when executing callback.
1b) index (optional): The index of the current element being processed in the array.
1c) array (optional): The array some was called upon.
2) thisArg (optional): Value to use as this when executing callback.
const ages = [20, 16, 19, 24, 26, 19]; ages.some((age) => age >= 21); // true
arr.every(callback(element[, index[, array]])[, thisArg]));
//Returns true if callback returns true for every item in the array. Example
Parameters:
1) callback: Function to test for each element, taking three arguments: 1a) element: The current element being processed in the array.
1b) index (optional): The index of the current element being processed in the array.
1c) array (optional): The array every was called upon.
2) thisArg (optional): Value to use as this when executing callback.
const ages = [20, 16, 19, 24, '26', 19];
ages.every((elem) => typeof elem === 'number'); // false, '26' is a string
arr.find(callback(element[, index[, array]])[, thisArg]);
//Returns first element that passes a test in a function. Returns undefined if no match. Examples
Parameters:
1) callback: tests each element of the array. Return true to keep the element, false otherwise. It accepts three arguments:
1a) element: The current element being processed in the array.
1b) index (optional): The index of the current element being processed in the array.
1c) array (optional): The array filter was called upon.
2) thisArg (optional): Value to use as this when executing callback.
Find the first element with value 21 or higher.
const ages = [20, 16, 19, 24, 26, 19]; ages.find((age) => age >= 21); // returns 24
Array of objects: Find the first user with age 21 or over.
const users = [{name: 'Joey', age: 18}, {name: 'Sheena', age: 27}, {name: 'Johnny', age: 26}];
users.find((user) => user.age >= 21); // returns {name: 'Sheena', age: 27}
arr.filter(callback(element[, index[, array]])[, thisArg]);
//Returns a new array containing the items for which callback returned true. Examples
Parameters:
1) callback: tests each element of the array. Return true to keep the element, false otherwise. It accepts three arguments:
1a) element: The current element being processed in the array.
1b) index (optional): The index of the current element being processed in the array.
1c) array (optional): The array filter was called upon.
2) thisArg (optional): Value to use as this when executing callback.
Filter for ages 21 and over.
const ages = [20, 16, 19, 24, 26, 19]; ages.filter((age) => age >= 21); // returns [24, 26]
Array of objects: Return array of all users age 21 and over
const users = [{name: 'Joey', age: 18}, {name: 'Sheena', age: 27}, {name: 'Johnny', age: 26}];
users.filter((user) => user.age >= 21);
// returns [{name: 'Sheena', age: 27}, {name: 'Johnny', age: 26}]
Iteration Methods
arr.forEach(callback(currentValue[, index [, array]])[, thisArg]);
//Executes callback on every array item and returns undefined. Examples and additional info
Additional info:
Iterate through each element in an array. The callback function logs the element value to the console.- Can be used in place of a for...of loop.
- Unassigned items are not iterated over, but items assigned to null or undefined are.
- You can't break a forEach() loop.
- ForEach will not wait for Promise results.
const arr = ['a', 'b', 'c', 'd', 'e'];Simple example:
arr.forEach((elem) => {As a one liner:
console.log(elem);
});
arr.forEach((elem) => console.log(elem));
Optional index argument:
arr.forEach((elem, i) => {
console.log(`${i}: ${elem}`);
}); // logs each index and element starting with 0: a
Build a string of each item separated by commas.
let str = '';
arr.forEach((elem, i) => {
str += elem;
});
console.log(str); // a, b, c, d, e.
Treat last item differently. Last item is preceded by "and" and ends in a period.
let str = '';
arr.forEach((elem, i) => {
str += i < arr.length -1 ? `${elem}, ` : `and ${elem}.`;
});
console.log(str); // a, b, c, d, and e.
arr.map(callback(currentValue[, index[, array]])[, thisObject]);
//Executes callback on every element in the array, putting each return value into a new array. Returns new array. Does not change original array. Examples
const arr = ['a', 'b', 'c', 'd', 'e'];Simple example:
- Modify all elements in the below array to uppercase letters and assign the result to newArr.
const arr = ['a', 'b' ,'c' ,'d' ,'e']; const newArr = arr.map((item) => item.toUpperCase());
newArr; // ["A", "B", "C", "D", "E"]
Optional index argument:
Multiply each element in the below array by its index number. Assign the result to newNums.
const nums = [1, 2, 3, 4, 5]; const newNums = nums.map((num, i) => num * i));
newNums; // [0, 2, 6, 12, 20]
Reassign variable name to result:
Map returns a different array without changing the underlying array. To change arr to the modified array it needs to be reassigned to the result.
Modify all elements in the below array to uppercase letters and reassign arr to the result.
let arr = ['a', 'b' ,'c' ,'d' ,'e']; arr = arr.map((item) => item.toUpperCase()); arr; // ['A', 'B', 'C', 'D', 'E']
arr.reduce(callback(previousValue, currentValue[, index[, array]])[, initialValue]);
//Executes a reducer function (the callback argument) on each member of the array resulting in a single output value. Examples
- The previousValue arg acts as a variable that accumulates the callback's return value after each iteration.
- The initial previousValue is the first array elem by default, or the initialValue arg if you provide it.
- CurrentValue arg is the current element being processed in each array iteration.
- See MDN for more complex examples.
const nums = [1, 2, 3, 4, 5];
Simple example:
nums.reduce((previousValue, currentValue) => {As a one-liner:
return previousValue + currentValue;
}); // returns 15
nums.reduce((previousValue, currentValue) => previousValue + currentValue); // 15
Set an initial value:
nums.reduce((previousValue, currentValue) => previousValue + currentValue, 1000); // 1015
Modify values before accumulating:
Get the average of the percents in the below array.
const pcts = ['70%', '60%', '90%', '75%', '80%']; pcts.reduce((previousValue, currentValue) => previousValue + Number(currentValue.replace('%','')), 0) / pcts.length;// returns 75
- The default initial value is the first element of the array. But in this case each element needs to be converted to a number with the % symbol removed. As such, add an initial value argument of 0.
arr.reduceRight(callback(prevValue, currentValue[, index[, array]])[, initialValue]);
// Same as reduce except it executes from end of the array to the beginning (right to left). Example
Flatten an array of arrays starting from the end of the array moving left:
const arrs = [['a', 'b'], ['c', 'd', 'e'], ['f']]; const flatArr = arrs.reduceRight((prev, curr) => { return prev.concat(curr); }, []);
flatArr; // ["f", "e", "d", "c", "b", "a"]
Shallow Copy
Copy all the element values of an array to a new array.
Use one of these: spread operator, arr.slice(), Array.from(arr)
Use one of these: spread operator, arr.slice(), Array.from(arr)
Spread Operator (ES2015)
Ref: MDN Operators/Spread_syntax
[...iterableObj];
Spread operator inside an array literal shallow copies an iterable object.Example
The spread operator unpacks the elements of an iterable object (e.g., an array).
Spreading them out inside an array literal creates a new array, thus making a shallow copy.
const arr = ['a', 'b', 'c', 'd', 'e'];
const arrCopy = [...arr];
// arrCopy is ['a', 'b', 'c', 'd', 'e'];
Slice and Array.from
arr.slice();
//Slice with no args returns a shallow copy.Example
const arr = ['a','b','c','d','e']; const arrCopy = arr.slice(); //arrCopy is ['a','b','c','d','e']
Array.from(arrayLike[, mapFn[, thisArg]]);
//Returns a new, shallow-copied array instance. Use this to copy an array-like or iterable object to an array.Examples and additional info
- This is an Array static method.
- Used to copy array-like objects to an actual array.
Parameters:
1) arrayLike: An array-like or iterable object to convert to an array.
2) mapFn (optional): Map function to call on every element of the array.
3) thisArg (optional): Value to use as this when executing mapFn.
Convert a string to an array:
Shallow copy an array to a new array:
const arr = Array.from('abcde');
// arr; returns ['a', 'b', 'c', 'd', 'e'];Shallow copy an array to a new array:
const newArr = Array.from(arr);
// newArr; returns ['a', 'b', 'c', 'd', 'e'];The optional map function: allows an array-like object to be modified before returning it as an array.
Shallow copy the string to an array, converting the data type of each character from string to number.
Shallow copy the string to an array, converting the data type of each character from string to number.
const str = '12345';
const nums = Array.from(str, (item) => Number(item));
nums; // returns [1,2,3,4,5]
Shallow copy array and add, update, or remove elems
[...arr, newItem] //Copy and add an elem.
arr.map((elem) => elem === elemToUpdate ? newElem : elem); //Copy and update elem.arr.filter((elem) => elem !== elemToRemove);
//Copy and remove an elem.Example
const arr = ['a', 'b', 'c'];
Add: Shallow copy arr and add element 'f'.
let copiedArr = [...arr, 'd'];
// copiedArr is ['a', 'b', 'c', 'd'];
Update: Shallow copy arr and change elem 'c' to 'X'.
copiedArr = arr.map((elem) => elem === 'c' ? 'X' : elem);
// copiedArr is ['a', 'b', 'X'];
Remove: Shallow copy arr and remove elem 'b'.
copiedArr = arr.filter((item) => item !== 'b');
// copiedArr is ['a', 'c'];
Shallow copy array of objects and add, update, or remove elems
[...arr, newObj]
//Copy and add an obj.arr.map((obj) => obj.prop === prop ? newObj : obj);
//Copy and update obj.arr.filter((obj) => obj.prop !== prop);
//Copy and remove an obj.Example
const users = [{id: 1, name: 'Joey'}, {id: 2, name: 'Sheena'}, {id: 3, name: 'Johnny'}];
Add: Shallow copy users and add object judy.Reassign users to the result.
Update user with id 1, replacing it with the below. Reassign users to the result.
Remove user with id 2. Reassign users to the result.
const judy = {id: 4, name: 'Judy'}; users = [...users, judy];
Update user with id 1, replacing it with the below. Reassign users to the result.
const id1 = {id: 1, name: 'Joseph'}; users = users.map((user) => user.id === 1 ? id1 : user);
Remove user with id 2. Reassign users to the result.
users = users.filter((user) => user.id !== 2);
Array-like and Iterable Objects
Array-like objects: non-array objects with length property and indexed properties. Cannot use Array instance methods.
Iterable objects: can be iterated with a for...of loop.
Examples that are both include: strings, sets, function arguments object, htmlCollections.
Convert to an array using
Iterable objects: can be iterated with a for...of loop.
Examples that are both include: strings, sets, function arguments object, htmlCollections.
Convert to an array using
Array.from(arrLike)
or spread operator [...arrLike]
Example - String
String as array-like object:
String as iterable:
const str = 'hello';
str.length; // 5
str[0]; // 'h'
Array-like objects can be copied to an array using Array.from()
Array.from(str); // returns ['h','e','l','l','o']
String as iterable:
const str = 'hello';
for (const letter of str) { console.log(letter); }
Iterable objects can be copied to an array using the spread operator inside the array operator or Array.from()
[...str]; // returns ['h','e','l','l','o']
Set
Set is a Global Object sibling of Array. It is part of ES2015. Set creates an object out of an array eliminating duplicates.new Set([1,2,3,2,4,4,5,6,5]); // {1, 2, 3, 4, 5}
You can use it to remove duplicates from array;
let uniqArr = Array.from(new Set([1,2,3,2,4,4,5,6,5]));
let uniqArr = [...new Set([1,2,3,2,4,4,5,6,5])];
Object
- An object is an unordered collection of properties written as name:value pairs.
- object is a data type, and the only one that is not a primitive:
typeof {}; // 'object'
- Object is a JavaScript standard built-in object in the global scope.
Object.getPrototypeOf({}); // Object.prototype
Create an Object Instance
1) Object Literal (preferred way)
const objName = { prop1: value, prop2: value, };
Example
Properties can be of any data type, including objects.
const article = {
title: 'Learn JavaScript',
content: 'Lorem Ipsum',
categories: ['education', 'tech'],
author: { name: 'Joey'},
};
2) Call the Object constructor function
Objects can also be created by calling the Object constructor function.
const varName = new Object({name: value, name2: value});
The Object function without the new keyword will also create a new object.
const varName = Object({name: value, name2: value});
Examples
Call the Object constructor function:
const user = new Object({name: 'Joey', age: 29});
Or without the new keyword.
const user = Object({name: 'Joey', age: 29});
Properties
Objects contain properties and methods.Properties are name: value pairs. They are like variables except they are attached to an object.
Get property values: Use dot or bracket notation.
Computed property name: Bracket notation with variable:
Set new properties:
Change existing property values:
Property values can be other objects. Chain the property names to access them.
Get property values: Use dot or bracket notation.
user.name;
// "Joey"user['name'];
// "Joey"Computed property name: Bracket notation with variable:
let prop = 'name';
user[prop];
// "Joey"Set new properties:
user.occupation = 'Software Engineer';
Change existing property values:
user.age = 30;
Property values can be other objects. Chain the property names to access them.
article.author.name;
// "Joey"article.category.push('programming');
// adds element to the category property.Delete property:
delete user.age;
If the property key and value are the same, you don't have to use key: value
let title = userInput;
const article = { title }; // in place of { title: title }
Return undefined instead of error if parent property is null or undefined.
const obj = {};
obj.key?.nestedKey; // undefined
Example
Referencing a nested property when the parent is null/undefined will throw an error:
const article = {}
article.author; // undefined
article.author.name // Uncaught TypeError Cannot set property 'name' of undefined
Short-circuit solution:
article.author && article.author.name // undefined
Optional chaining solution:
article.author?.name // undefined
Methods
Methods are functions associated with an object. They are essentially a property of an object that is a function.const user = {
name: 'Joey',
log: function() { return 'You executed the log method' },
}
user.log(); // "You executed the log method"
Shorthand syntax (drop the colon and the function keyword):
log() { return 'You executed the log method' }
Shorthand syntax example
The shorthand syntax is a little shorter so recommended.
const user = {
name: 'Joey',
log() { return 'You executed the log method' },
}
user.log(); // "You executed the log method"
This
The keyword this represents the current object. For a method to access a property in the object you need to chain it to this.
const user = {
name: 'Joey',
log() { return `User's name is ${this.name}` },
}
user.log(); // "Users's name is Joey"
More details
You could instead use the actual name of the object, but the convention is to always use this.
const user = {
name: 'Joey',
log() { return `User's name is ${user.name}` },
}
user.log(); // "Users's name is Joey"
Spread Operator (ES2015)
Shallow copy: Use the spread operator to shallow copy an object.const user = { name: 'Joey', age: 21 };
const userCopy = { ...user };
More details
Shallow copy means you copy the property and method values, making it a new object.
Now user and userCopy are two separate objects. If you change a property value in one:
If you had instead done it this way:
Then both the user and userCopy variables would be pointing to the same object. Changing one would affect both variables.
Now user and userCopy are two separate objects. If you change a property value in one:
user.age = 22;
user; // { name: 'Joey', age: 22 }
It does not change the property in the other:
userCopy; // { name: 'Joey', age: 21 }
If you had instead done it this way:
const user = { name: 'Joey', age: 21 }
const userCopy = user;
Then both the user and userCopy variables would be pointing to the same object. Changing one would affect both variables.
Copy and Modify an object (using spread operator)
let user = {name: 'Joey', age: 22, interests: ['sports', 'music']};
Create shallow copy of user object and change the age property:
user = {...user, age:23};
Shallow copy user and add item to the "interests" array property:
user = {...user, interests: [...user.interests, 'cars'];
Shallow copy user and remove item from the "interests" array property:
user = {...user, interests: user.interests.filter((interest) => interest !== 'cars')};
Object global object
- Object is a JavaScript standard built-in object in the global scope.
- Object includes a constructor function, static and instance properties and methods.
- Object.prototype is the parent prototype of all other built-in global objects.
All objects ultimately inherit from Object and have access to its properties/methods.
More info
Object global object
- Object is a JavaScript standard built-in object in the global scope. It is also called a global object because it is attached to the global object (window or global):
Object === window.Object; // returns true in the browser environment
Object === global.Object; // returns true in the Node.js environment
- Object is a constructor function (functions are a type of object).
typeof Object; // returns 'function'
- When called with the new keyword, it instantiates an object.
const obj = new Object('Hello'); // creates a Sting object with value 'Hello'
typeof obj; // returns 'object'
- When called in a non-constructor context (i.e., without the new keyword) it converts the argument to an object:
Object(7); // converts the primitive value to a Number object with value 7
Object('Hello'); // converts the primitive value to a String object with value "Hello"
Object static properties and methods:
- Object has several static properties that can be used with any object.
Object.getOwnPropertyNames(Object); // returns length, name, prototype, assign, getOwnPropertyDescriptor, getOwnPropertyDescriptors, getOwnPropertyNames, getOwnPropertySymbols, is, preventExtensions, seal, create, defineProperties, defineProperty, freeze, getPrototypeOf, setPrototypeOf, isExtensible, isFrozen, isSealed, keys, entries, fromEntries, values, hasOwn
Object instance properties and methods:
- Object literals are instances of the Object constructor:
typeof {}; // returns 'object'
{} instanceof Object; // returns true {}.constructor; // returns Object
- The prototype of an object literal is Object.prototype:
Object.getPrototypeOf({}) === Object.prototype; // returns true
- The prototype of the standard built-in object prototypes is Object.prototype:
Object.getPrototypeOf(String.prototype) === Object.prototype; // true Object.getPrototypeOf(Number.prototype) === Object.prototype; // true Object.getPrototypeOf(Boolean.prototype) === Object.prototype; // true Object.getPrototypeOf(Date.prototype) === Object.prototype; // true Object.getPrototypeOf(Array.prototype) === Object.prototype; // true Object.getPrototypeOf(Function.prototype) === Object.prototype; // true
- Object.prototype contains properties and methods you can call on any object. Below is the full list of non-deprecated instance properties.
Object.getOwnPropertyNames(Object.prototype); // Returns: constructor, hasOwnProperty, isPrototypeOf, propertyIsEnumerable, toString, valueOf, __proto__, toLocaleString
- constructor is a reference to the Object() constructor function, it is not the constructor function itself.
- The __proto__ property contains a reference to the objects prototype object. This property is deprecated in favor of calling Object.getPrototypeOf()
Static Methods
Get an object's prototype
Object.getPrototypeOf(obj);
//Returns obj's prototype (internal [[Prototype]] property). Examples
const user = { name: 'Joey', age: 22 };
Object.getPrototypeOf(user);
// Returns the Object prototype.Get an object's owned properties
Object.getOwnPropertyNames(obj);
//Returns array of the names of the obj's own enumerable and non-enumerable properties (includes methods).Object.keys(obj);
//Returns array of the names of the obj's own enumerable properties.Object.values(obj);
//Returns array of the values of the obj's own enumerable properties.Object.entries(obj);
//Returns array of all of the obj's property [key, value] pairs.Examples
const user = { name: 'Joey', age: 22 };
Object.getOwnPropertyNames(user);
// ["name", "age"]Object.keys(user);
// ["name", "age"]Object.values(user);
// ["Joey", "22"]Object.entries(user);
// [["name", "Joey"], ["age", 22]]Prevent objects from being modified
Object.freeze(obj);
Freezes an object. Properties cannot be added or deleted and values can't be changed. Returns the obj.Object.isFrozen(obj);
Determines if an object was frozen. Returns true/false.Object.preventExtensions(obj);
Prevents any extensions (adding properties) to an object. Returns the obj.Object.isExtensible(obj);
Determines if extending of an object (adding properties) is allowed. Returns true/false.Object.seal(obj);
Seals an obj. Prevents extensions or deletions of properties to the obj. Returns the obj.Object.isSealed(obj);
Determines if an object is sealed. Returns true/false.Example
const user = { name: 'Joey', age: 22 };
// Prevent properties from being added.
Object.preventExtensions(user);
Object.isExtensible(user); // returns false
// Prevent properties from being deleted.
Object.seal(user);
Object.isSealed(user); // returns true
// Prevent properties from being added, deleted or values changed.
Object.freeze(user);
Object.isFrozen(user); // returns true
Instance Properties
obj.constructor;
//Specifies the function that creates an object's prototype.obj.constructor.name;
//Get the name of the function that creates an object's prototype.obj.__proto__;
//Points to the object which was used as prototype when the object was instantiated. This property is deprecated. Instead use Object.getPrototypeOf(obj).Examples - constructor property
- Get the constructor function of an array literal.
[1,2,3].constructor;
// Returns the Array constructor function.[1,2,3].constructor.name;
// Returns 'Array'- Get the constructor function of an object literal.
const user = { name: 'Joey', age: 22 };
user.constructor;
// Returns the Object constructor function.user.constructor.name;
// Returns 'Object'- //Make a class for user objects with properties for name and age and instantiate an object.
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
} const user1 = new User('Joey', 22);
- //Get the constructor function of the user1 object.
user1.constructor;
// Returns the User class (class is an alternate syntax for a constructor function).user1.constructor.name;
// Returns "User", the name property value of the constructor function.Instance Methods
obj.valueOf();
//Returns the primitive value of the specified object.obj.toString();
//Returns string representation of the obj: [object Object] unless shadowedExamples
obj.valueOf():
obj.toString():
let str = new String('Hello'); // create a String object
typeof str; //Returns 'object'
typeof str.valueOf(); //Returns 'string'
obj.toString():
const user = { name: 'Joey', age: 22 };
user.toString(); // Returns [object Object]
// Shadow the toString method.
user.toString = () => `User name is ${user.name}, age is ${user.age}`;
user.toString(); // returns 'User name is Joey, age is 22'
prototypeObj.isPrototypeOf(obj);
Indicates whether the object this method is called upon is in the prototype chain of the specified object. Returns true/false.Examples
Confirm that the Object prototype is the prototype of the other global objects.
Confirm that the Object prototype is the prototype of objects created as an object literal.
Object.prototype.isPrototypeOf(String.prototype);
// Returns trueObject.prototype.isPrototypeOf(Array.prototype);
// Returns trueConfirm that the Object prototype is the prototype of objects created as an object literal.
const user = { name: 'Joey', age: 22 };
Object.prototype.isPrototypeOf(user);
// Returns trueInstanceof operator
obj instanceof ConstructorFn;
//Tests if an object is an instance of the specified constructor anywhere up the prototype chain.Examples
Use the instanceof operator to prove:
- Prove that Global Objects are instances of Object:
String instanceof Object;
//Returns trueArray instanceof Object;
//Returns trueFunction instanceof Object;
//Returns true- Prove that an array literal is an instance of both Array and Object:
[1, 2, 3] instanceof Array;
//Returns true [1, 2, 3] instanceof Object;
//Returns true - Prove that an object literal is an instance of Object:
{} instanceof Object;
//Returns true - Prove that a string literal is not an instance of String:
'Hello' instanceof String;
//Returns false- Make 'Hello' an object, then prove it is an instance of String and Object:
const hello = new String('Hello');
hello instanceof String;
//Returns true hello instanceof Object;
//Returns true Make a class for user objects with properties for name and age.
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
Create a User instance called user1 with name 'Joey' and age 22.
const user1 = new User('Joey', 22);
- Prove that user1 is an instance of both User and Object.
user1 instanceof User;
// Returns trueuser1 instanceof Object;
// Returns trueClass
Overview
- JavaScript is an object object-oriented programming language, but unlike most OOP languages it uses prototypes instead of classes.
- Prototypes are objects that contain constructor functions. Constructor functions are used to create object instances of the prototype. The prototype's constructor function is a template that defines the properties that all prototype instances will have.
- The constructor function has a property called prototype. This is an object that holds the instance methods defined in the class. Each object created with the class has an internal property pointing to the prototype object.
- New instance objects are returned from a constructor function when it is called, appended with the "new" operator, passing in property values as arguments.
- Traditional OOP classes do essentially the same thing. The difference is that unlike classes, JS constructors are just regular functions. Any function can be converted to a constructor function to make objects. And objects created from a prototype can be mutated. You can just add properties to an instance without regard to its prototype.
- ES2015 introduced the class keyword to use for prototypes and gave them a special syntax. Despite using the word class, they are still JS constructor functions (you could call it syntactic sugar). But just like traditional classes, a JS class is a template of properties and methods used to create instance objects of the prototype.
Class Declaration
class ClassName { constructor(prop1, prop2) { this.prop1 = prop1; this.prop2 = prop2; } } const instance1 = new ClassName(val1, val2);
- Constructor function generates new objects.
- The constructor function defines properties, which are passed in as arguments.
- The this keyword refers to the instance object.
- To instantiate an object call the class with the new operator. Pass in the props as args.
Examples
Example 1:
Generate users with a User class.
Generate users with a User class.
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const user1 = new User('Joey', 22);
user1; // User {name: "Joey", age: 22}
Example 2:
Generate articles with an Article class.
Generate articles with an Article class.
class Article {
constructor(title, content, categories, author) {
this.title = title;
this.content = content;
this.categories = categories;
this.author = author;
}
}
const article1 = new Article('Learn JavaScript', 'Lorem ipsum', ['education', 'tech'], user1);
Instance Properties
Get property values: Use dot or bracket notation.
Set property values:
Property values can be other objects. Chain the property names to access them.
instance1.propName;
// Returns the property value.instance1['propName'];
// Returns the property value.Set property values:
instance1.propName = val;
Property values can be other objects. Chain the property names to access them.
const otherObj = {prop1: 'val', prop2: 'val'};
instance1.otherObj.prop1;
Examples
Get property values:
Set property values:
Property values can be other objects. Chain the property names to access them.
user1.name;
// "Joey"user1['name'];
// "Joey"Set property values:
user1.age = 30;
Property values can be other objects. Chain the property names to access them.
article.author.name;
// "Joey"article.categories.push('programming');
// adds element to the categories property.Instance Methods
Put instance methods outside the constructor function.
- methodName() {}
class ClassName { constructor(prop1, prop2) { this.prop1 = prop1; this.prop2 = prop2; } method1() {}; method2() {}; } const instance1 = new ClassName(val1, val2); instance1.method1();
Example
class Article {
constructor(title, content, published = false) {
this.title = title;
this.content = content;
this.published = published;
this.publishDate = published ? (new Date).toDateString() : null;
}
publish() {
this.published = true;
this.publishDate = (new Date).toDateString();
}
};
const article1 = new Article('Learn JavaScript', 'Lorem Ipsum');
article1; // {title: 'Learn JavaScript', content: 'Lorem Ipsum', published: false, publishDate: null}
article1.publish(); // calls the publish instance method. article1; // Article {title: 'Learn JavaScript', content: 'Lorem Ipsum', published: true, publishDate: 'date string'}
Getter Method
To return data besides properties you can define a getter method.
- Prepend the get operator to the method.
- Don't use parentheses when you call a getter function.
class ClassName { constructor(prop1, prop2) { this.prop1 = prop1; this.prop2 = prop2; } get methodName() { return 'some data' } } const instance1 = new ClassName(val1, val2); instance1.methodName;
Example
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
get profile() {
return `User ${this.name} is age ${this.age}`;
}
}
const user1 = new User('Joey', 22); user1.profile; // 'User Joey is age 22';
Shadowing properties
Declaring a property with the same name as an inherited property supercedes it.
Example - toString()
- toString() is an instance method of the Object global object, so all objects inherit it.
- In the below example we are shadowing toString with our own definition.
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
toString() { return `<User: ${this.name}>`; }
}
const user1 = new User('Joey', 22);
user1.toString(); // '<User: Joey>'
- Without shadowing the result would be:
user1.toString(); // "[object Object]"
Static Properties and Methods
Static properties and methods are called on the class itself, not an instance of the class. To declare a static property or method prefix the static operator.
class ClassName { constructor(prop1, prop2) { this.prop1 = prop1; this.prop2 = prop2; } static propName = val; static methodName() {} }// Call the static property or method by chaining it to the class name.
ClassName.propName;
ClassName.methodName();
Example
Static method:
Static property: Count the number of users created.
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
static about() {
return 'The User class has properties for name and age.';
}
} User.about(); //Returns "The User class has properties for name and age."
Static property: Count the number of users created.
class User {
constructor(name, age) {
this.name = name;
this.age = age;
this.id = ++User.count;
}
static count = 0;
}
const joey = new User('Joey', 22);
joey; // { name: "Joey", age: 22, id: 1 }
User.count; // 1
Inheritance
A class can have a parent class that it inherits from.
class ChildClass extends ParentClass { constructor(prop1, prop2, prop3) {
super(prop1, prop2);
this.prop3 = prop3;
}
} const instance1 = new ChildClass(val1, val2, val3);
- Use the extends keyword between the subclass name and the superclass name.
- In the constructor function you can accept parameters defined in the parent class. But you need to use the super keyword with the parameters in parentheses.
More details
Parent class:
Child class:class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
static about() {
return 'The User class has properties for name and age.';
}
}
class PremiumUser extends User {
constructor(name, age, access) {
super(name, age);
this.access = access;
}
}
const premiumUser1 = new PremiumUser('Johnny', 32, 'all');
premiumUser1; // PremiumUser {name: "Johnny", age: 32, id: 3, access: "all"}
Module
Node.js
- Node projects can use either CommonJS or Import/Export statements.
- Node version 13 (released 2019): first version that allows import/export statements.
- Transpilers like Babel transpile Import/Export statements to CommonJS.
- Modules are cached when imported.
- Components not exported are private and not accessible outside the module.
Terms - library, module, package
- Library: A Collection of prewritten code snippets, related in some way, that you can import as a whole and use in your code. It can be a single file or a directory. Examples: jQuery, React, packages installed with npm. You can also create your own libraries.
- Module: In JS, to use a library it must be exported as a module. Modules can be third party packages, Node built-in modules, or merely a separate file in your project. In Node.js, each file is treated as a separate module.
- Package: A package is a library/module that has been prepared to be installed using a package manager like npm. Packages must have a package.json file. NPM installs packages in the node_modules folder. All packages are modules, but not all modules are packages.
Types of Modules:
'moduleName'
Some core Node modules must be imported (e.g., fs, path, http).'localPackage'
Third party packages installed locally in the node_modules folder.'globalPackage'
Third party packages installed globally.'./fileName'
Files used in the project. Node treats all JS project files as modules.
Search locations and order
- Built-in Node modules. Binary files executed in the Node runtime environment.
- If moduleName includes a path, Node searches for the file at the provided path.
- Searches the node_modules folder. If multiple, starts at folder closest to proj root.
- Searches for global packages at location provided by NODE_PATH env variable.
- e.g., /usr/local/lib/node_modules
- If module not found, throws MODULE_NOT_FOUND error.
More info: file paths
Provide the relative path to file imports.
'./fileName'
Import file from the same directory.'./path/to/fileName'
Import file from a child directory.'../fileName'
Import file from the parent directory.'../path/to/fileName'
Import file from a sibling directory.- Absolute paths start with
/
and are from the computer's root directory. Generally avoid absolute paths since they will likely differ from the development and production machines.
CommonJS
Require and use Built-in Node modules and NPM packages
Require Node modules and 3rd party NPM packages at top of file.
Using module namespace:
Using destructuring:
Using module namespace:
const moduleOrPackage = require('moduleOrPackage');
moduleOrPackage.methodName();
//Call a method from the module or package.Using destructuring:
const { method1, method2, method3 } = require('packageName');
method1();
//Call the methods in the file.Examples
Note: The imported module can be assigned to any variable name. Generally use the same name as the module.
Node module: import the file system module then call the readdirSync method to get the file names in an array from the path provided.
Module name as namespace:
NPM package: import the axios package from the node_modules directory. Axios is an alternative to fetch(). Chain axios' get method passing in a test API url. Axios uses Promises so preface the call with await to make the call synchronous.
Module name as namespace:
Node module: import the file system module then call the readdirSync method to get the file names in an array from the path provided.
Module name as namespace:
const fs = require('fs');Using destructuring:
console.log(fs.readdirSync('.'));
const { readdirSync, readFile } = require('fs');
console.log(readdirSync('.'));
NPM package: import the axios package from the node_modules directory. Axios is an alternative to fetch(). Chain axios' get method passing in a test API url. Axios uses Promises so preface the call with await to make the call synchronous.
Module name as namespace:
const axios = require('axios'); const users = await axios.get('https://jsonplaceholder.typicode.com/users');Using destructuring:
const { post, get } = require('axios'); const users = await get('https://jsonplaceholder.typicode.com/users');
User created modules
Single Export
Export file
To export a single construct, assign it to a variable and export it at the bottom of the file:const varName = /* function, object, or variable */;
module.exports = varName;
//Export module as a single construct.Import file
const namespace = require('./fileName');
//Import file. Include path. Node looks for file name as is, then appends .js, .json, finally .node.Can be any variable name. Generally use the same name as the module.
namespace.methodName();
//Chain module methods to the module namespace.Examples
Example1: Module exports a single object literal:
File name calculator.js contains and exports an object named Calculator.
Import the file and access the methods
Example2: Module contains a single class, instantiates single instance object, exports object:
File name calculator.js contains a class named Calculator. Makes a single instance object called calculator. Exports the object.
File name calculator.js contains and exports an object named Calculator.
Export file: calculator.js
const calculator = { double: (x) => x * 2, triple: (x) => x * 3 };
module.exports = calculator;
Import the file and access the methods
Import file: app.js
const calculator = require('./calculator'); // relative path
console.log(calculator.double(10)); // logs 20
console.log(calculator.triple(10)); // logs 30
Example2: Module contains a single class, instantiates single instance object, exports object:
File name calculator.js contains a class named Calculator. Makes a single instance object called calculator. Exports the object.
Export file: calculator.js
class Calculator { double(x) { return x * 2; } triple(x) { return x * 3; } } const calculator = new Calculator();
module.exports = calculator;
Import file: app.js
const calculator = require('./calculator'); // relative path
console.log(calculator.double(10)); // logs 20
console.log(calculator.triple(10)); // logs 30
Multiple exports
Export file
Export multiple constructs as properties of the module object:const var1 = () => {}; //Export a function
const var2 = 'text'; //Export a variable
module.exports = { var1[, var2,...] }; //Export multiple items.
Import file
const { var1[, var2, ...] } = require('moduleName');
//Import module's named properties.var1();
//Then call the named properties or methods without a module namespace.Examples
Example 1: Using Destructuring
Create a file named calculator.js, add two functions to it, and export them as properties of the module object.
Create a file named calculator.js, add two functions to it, and export them as properties of the module object.
Export file: calculator.js
const double = (x) => x * 2;Require the module using a relative path.
const triple = (x) => x * 3;
module.exports = { double, triple };
Import file: app.js
const { double, triple } = require('./calculator');
console.log(double(10)); // logs 20
console.log(triple(10)); // logs 30
Example 2: Import module using namespace
Export file: calculator.js
const double = (x) => x * 2;
const triple = (x) => x * 3;
module.exports = { double, triple };
Import file: app.js
const calculator = require('./calculator');
console.log(calculator.double(10)); // logs 20
console.log(calculator.triple(10)); // logs 30
Example3: Export functions individually.
Export file: calculator.js
exports.double = (x) => x * 2;
exports.triple = (x) => x * 3;
Import file: app.js
const { double, triple } = require('./calculator');
console.log(double(10)); // logs 20
console.log(triple(10)); // logs 30
Import/Export Statements (ES2015)
Import and use Built-in Node modules and NPM packages
Import Node modules and 3rd party NPM packages at top of file:
Using module namespace:
Using destructuring:
Using module namespace:
import moduleOrPackage from 'moduleOrPackage';
moduleOrPackage.methodName();
//Call a method from the imported module.Using destructuring:
import { export1[, export2, ...] } from 'module';
//Import module, destructure named props.export1();
//Call module method without the module namespace.Examples
Node module: import the file system module then call the readdirSync method to get the file names in an array from the path provided.
Npm package: import the axios package from the node_modules directory. Axios is an alternative to fetch(). Chain axios' get method passing in a test API url. Axios uses Promises so preface the call with await to make the call synchronous.
import fs from 'fs';Using destructuring:
console.log(fs.readdirSync('.'));
import { readdirSync, readFile } from 'fs';
console.log(readdirSync('.'));
Npm package: import the axios package from the node_modules directory. Axios is an alternative to fetch(). Chain axios' get method passing in a test API url. Axios uses Promises so preface the call with await to make the call synchronous.
import axios from 'axios'; const users = await axios.get('https://jsonplaceholder.typicode.com/users');Using destructuring:
import { get, post } from 'axios'; const users = await get('https://jsonplaceholder.typicode.com/users'); post('https://jsonplaceholder.typicode.com/users', { name: 'Joey', age: 22 });
User created modules
Exported modules are automatically in strict mode.
When importing files, Include the file extensions.
Can't use
When importing files, Include the file extensions.
Can't use
__dirname
or __filename
. Get project path with: process.cwd()
Single Export (Default export)
Export file
To export a single construct, assign it to a variable and export it at the bottom of the file:const varName = /* function, object, or variable */;
export default varName;
//Default export one per module.Import file
import namespace from './fileName.js';
//Import file. Include path and extension.namespace.methodName();
//Chain module methods to the module namespace.Examples
Example1: Module exports a single object literal:
File name calculator.js contains and exports an object named Calculator.
Import the file and access the methods
Example2: Module contains a single class, instantiates single instance object, exports object:
File name calculator.js contains a class named Calculator. Makes a single instance object called calculator. Exports the object.
File name calculator.js contains and exports an object named Calculator.
Export file: calculator.js
const calculator = { double: (x) => x * 2, triple: (x) => x * 3 };
export default calculator;
Import the file and access the methods
Import file: app.js
import calculator from './calculator.js'; // relative path
console.log(calculator.double(10)); // logs 20
console.log(calculator.triple(10)); // logs 30
Example2: Module contains a single class, instantiates single instance object, exports object:
File name calculator.js contains a class named Calculator. Makes a single instance object called calculator. Exports the object.
Export file: calculator.js
class Calculator { double(x) { return x * 2; } triple(x) { return x * 3; } } const calculator = new Calculator();
export default calculator;
Import file: app.js
import calculator from './calculator.js'; // relative path
console.log(calculator.double(10)); // logs 20
console.log(calculator.triple(10)); // logs 30
Multiple exports (named exports)
Export file
Export multiple constructs as properties of the module object:
const var1 = () => {}; //Export a function const var2 = 'text'; //Export a variable export { var1[, var2,...] }; //Export multiple named export items.
Import file
import { var1[, var2, ...] } from './filePath.js';
//Import module's named properties.var1();
//Call methods and named properties without a namespace.Examples
Example 1: Using Destructuring
Example 2: Import module using namespace
Example3: Export functions individually.
Create a file named calculator.js, add two functions to it, and export them.
Export file: calculator.js
const double = (x) => x * 2;Require the module using a relative path.
const triple = (x) => x * 3;
export { double, triple };
Import file: app.js
import { double, triple } from './calculator.js';
console.log(double(10)); // logs 20
console.log(triple(10)); // logs 30
Example 2: Import module using namespace
Export file: calculator.js
const double = (x) => x * 2;
const triple = (x) => x * 3;
export { double, triple };
Import file: app.js
import calculator from './calculator.js';
console.log(calculator.double(10)); // logs 20
console.log(calculator.triple(10)); // logs 30
Example3: Export functions individually.
Export file: calculator.js
export const double = (x) => x * 2; //named export
export const triple = (x) => x * 3; //named export
Import file: app.js
import { double, triple } from './calculator.js';
console.log(double(10)); // logs 20
console.log(triple(10)); // logs 30
Use Aliases
import * as name from 'moduleName';
//Import entire module assigned to a namespace.import { var1 as alias1, var2 as alias2 } from 'moduleName';
//Import module. Alias property names.Examples
Create a calculator module, exporting two functions as export object properties.
Export file: calculator.js
const double = (x) => x * 2;
const triple = (x) => x * 3;
export { double, triple };
Import the entire module assigning it to a namespace calculator.
Import file: app.js
import * as calculator from './calculator.js';
console.log(calculator.double(10)); // logs 20
console.log(calculator.triple(10)); // logs 30
Import one or more property names aliased:
Import file: app.js
import { double as twoTimes, triple as threeTimes } from './calculator.js';
console.log(twoTimes(10)); // logs 20
console.log(threeTimes(10)); // logs 30
Import a module for its side effects only
import './fileName.js';
//Import module to run its side effects, without importing anything.Example
Import a module just to run its side effects:
myModule.js
console.log('Performing some side effect');
myFile.js
import './myModule.js'; // Logs "Performing some side effect"
.Mjs Extension or Type Property
There are two ways to use import/export statements without a transpiler:
- Use the .mjs file extension.
- Change the file extension of both the importing and exporting files from .js to .mjs to indicate that they are modules.
- Add the .mjs extension to the filenames used on the import statements.
"type": "module"
//Server-side package.json file: Set the type property to module.
<script type="module" src="file" defer></script>
Client-side script tag: set type to module.
Examples
1) Use the .mjs file extension:
- Change the file extension of both the importing and exporting files from .js to .mjs to indicate that they are modules.
- Add the .mjs extension to the filenames used on the import statements.
calculator.mjs
const double = (x) => x * 2; const triple = (x) => x * 3;
export { double, triple };
myFile.mjs
import { double, triple } from './calculator.mjs';
console.log(double(10)); // logs 20
console.log(triple(10)); // logs 30
2) Set file type to module:
Alternatively, set the type property to module.- On the server side, set the type property in the package.json file.
package.json
{
...
"type": "module",
...
}
- On the client side (i.e., in the HTML document), set the type attribute in the script tag:
<script type="module" src="myJSFile" defer></script>
Promises
Event Loop
Explain diagram
Explain Diagram:
- The JS Engine contains the call stack and a memory heap.
- It parses the JS code, converts it to machine code, and executes it.
- To do this it creates a space in RAM memory to hold data objects (variables, function definitions, objects, arrays) using a heap data structure.
- Functions are placed on the call stack and executed. When the functions are executed, all the data is written to the heap and the stack references the memory addresses when executing the code. When the code finishes executing, the JS Garbage Collector removes the data from memory.
- The call stack operates on a Last-In-First-Out (LIFO) basis. So if the function on the stack calls another function, that will get placed on top of the stack and executed first.
- Functions in the call stack are executed synchronously. Other code is blocked from running until it is complete. Once complete it is removed from the stack and the function below it is executed. This continues until the stack is empty.
- Web APIs: Calls to web APIs are executed asynchronously using callbacks and the event loop.
- Functions that access the web APIs such as manipulating the DOM, fetching data from a server with ajax or fetch, timers, etc. generally need to be processed asynchronously for performance reasons.
- Web API calls are handled asynchronously. When called the function is immediately removed from the call stack before the result is received.
- The task is processed in parallel outside JS's single thread.
- Web API calls are passed with a callback function (or a Promise object). When the task is complete the callback function is added to the end of the callback queue with the result.
- User initiated DOM events like onLoad or onClick have callback functions as well, which get added to the callback queue when triggered.
- The browser runs an event loop. The event loop monitors the call stack which runs synchronously. When the call stack is empty the event loop checks the callback queue for the next callback function. If there is one it places it on the call stack to be executed.
- The Callback Queue operates on a First-In-First-Out basis. If there are multiple callback functions in the queue it takes the oldest one first.
- When the callback queue is empty, the event loop continually monitors it for a new callback.
- Note: some Web API calls are synchronous. Console.log() for instance is a Web API call the executes synchronously logging a string to the console. It has no return value to wait for (returns undefined).
Terms:
- Script: Program or sequence of instructions interpreted/executed by another program.
- Core JavaScript: ECMAScript. Excludes Web APIs.
- Single Treaded: Has one call stack and one memory heap.
- Synchronous: Blocking code executed in sequence.
- Call Stack: Stack data structure of currently executing nested function. Uses LIFO.
- API: Interface for programs to communicate with each other.
- Web APIs: DOM, fetch, storage, timers, etc. Node APIs: Core modules and NPM packages.
- Asynchronous: Non-blocking. Doesn't await result before moving to next line.
- Callback Queue: On event, message and associated callback are added to the Queue.
- Event Loop: Monitors Call Stack and Queue. Places Callback on stack when empty.
- Microtask queue: Similar to Callback Queue but for Promises.
Detailed definitions
- Runtime: Stage of the programming lifecycle when the program is running.
- Runtime Environment: Environment in which JS is run. Browser, Node.js.
- Script: Program or sequence of instructions interpreted/executed by another program.
- Core JavaScript: ECMAScript. Excludes Web APIs.
- JS engine: An interpreter that parses and executes a JavaScript program.
- JIT Compilation: JS engines compile JS directly to machine code before executing it.
- API: Interface for programs to communicate with each other.
- Web APIs: Browser I/O APIs such as DOM, fetch, storage, timers, etc.
- Node I/O APIs: Core Node.js modules and 3rd party NPM packages.
- Heap Memory: Region of memory, mostly unstructured, that stores objects, functions.
- Call Stack: Stack data structure of currently executing nested function. Uses LIFO.
- Events: Actions/occurrences that happen to HTML elements like a button click.
- Callback Queue: On event, message and associated callback are added to the Queue.
- Microtask queue: Similar to Callback Queue but for Promises.
- Event Loop: Monitors Call Stack and Queue. Places Callback on stack when empty.
- Single Treaded: Has one call stack and one memory heap.
- Synchronous: Blocking code executed in sequence.
- Asynchronous: Non-blocking. Doesn't await result before moving to next line.
- ---
- Runtime: The stage of the programming lifecycle when the program is running alongside any external instructions such as interfacing with Input/Output APIs.
- Runtime environment (or runtime system): The environment in which a programming language is run. JavaScript has two principal runtime systems, the browser and Node.js.
Browser Runtime environment: Includes a JS engine, Input/output APIs, and an event loop. The I/O APIs are the Web APIs, particularly the DOM to manipulate HTML documents.
Node Runtime environment: Includes the V8 JS engine (also used in Chrome and Edge), Input/output APIs, and an event loop. The I/O APIs are Node modules and 3rd party npm packages for interfacing with the computer's file system, external storage (e.g., database), HTTP requests/responses, etc.
The event loop listens for and responds to events like a user clicking on a button in the Browser or a database query returning a response in a Node.js app. - Core JavaScript: Also called ECMAScript with standards set by the Ecma International organization. Includes the language syntax, data types, built-in objects and functions (String, Number, Boolean, Array, Object, RegExp, Math, Error, etc.), prototype-based inheritance mechanism, basic memory model. In the browser, core JavaScript is JavaScript without the Web APIs.
- JS Engine: The JavaScript engine is an interpreter that parses and executes a JavaScript program.
JavaScript was created to run in the browser. Each browser includes a JavaScript engine and a rendering engine that renders HTML documents, images, and CSS styling. The two work in concert via the Document Object Model (DOM).
The JS engine executes core JavaScript code (JS without Web APIs) and manages heap and stack memory including garbage collection. Chrome, Edge and Node.js use a JS engine created by Google called V8. - Script: A program or sequence of instructions that is interpreted or carried out by another program. This is in contrast to a language that is compiled ahead of time, and executed by the computer processor at runtime.
- Scripting language: A programming language that can be executed by an interpreter at runtime, without being compiled ahead of time. JavaScript is a scripting language.
- Interpreted: High level programming languages are either executed as is by an interpreter at run time, or are compiled to lower level code ahead of time.
C, C++, C#, Swift and Java are examples of compiled languages. They require an extra "build" step when the program is complete, but before it can be run. This is generally done through an IDE like Eclipse for Java or a compiler like GCC for C and C++.
JavaScript, Python, PHP, and Ruby are examples of interpreted languages. - JIT Compilation: Since the release of V8 in 2008, JS engines use just-in-time (JIT) compilation. The JS engine compiles the JavaScript source code directly into native machine code during run time before executing it. Since JavaScript is not compiled by the user ahead of time, it is still considered an interpreted language.
- API (Application Programming Interface): An interface for two or more computer programs to communicate with each other.
- Web APIs: Web browsers offer a multitude of Input/Output APIs called Web APIs. The DOM API lets you access and modify a web page with JavaScript. The fetch API lets you fetch data from the server. Storage APIs store/access data in the browser. Web APIs are executed behind the scenes using lower level programming languages like C++.
- Node I/O APIs: The Node.js Runtime Environment has Input/Output APIs to access Node.js modules and 3rd party npm packages. The fs module allows interacting with the computer's file system. The http module creates a web server and interact with the HTTP request/response cycle. There are npm packages to interact with a database, create a web framework, and many other things.
- Heap Memory: Region of computer memory, mostly unstructured, that stores objects, including functions.
- Call Stack: A mechanism used by the JavaScript engine to keep track of nested function calls. Follows the Last In First Out (LIFO) principle. The last function called is at the top of the stack and executed first. When complete it is removed from the stack.
- Events: Actions or occurrences that happen to HTML elements. They can be user actions such as clicking a mouse button, or network or browser state changes like a web page load completing. Events are also generated by APIs to represent the progress of an asynchronous task.
- Event Listener/Handler: DOM elements can be set up to "listen" for HTML events by attaching the EventTarget.addEventListener() method to them. The first parameter of the function is the event to listen for. The second argument is a callback function (aka handler function) to handle the event.
- If there is no event listener attached to the element, the event is lost. For instance, if you click on a button element without a listener function attached, nothing will happen.
- Callback Queue: When an event occurs it returns a message. Each message has an associated function that gets called to handle the message. The message and associated callback function are added to the Callback Queue to await execution. The Queue follows the First In First Out (FIFO) principle, so functions in the Queue are executed in the order they were added.
- For DOM events, the callback function in the addEventListener method is added to the callback queue, along with the "event" object as the "message".
- Other asynchronous I/O API function calls like querying a database, making Ajax/Fetch requests to a server, or calling setTimeout, return data or other message when complete and add it to the callback Queue along with the associated function that gets called to handle it.
- Microtask queue: Similar to Callback Queue but for Promises. Takes precedence over Callback Queue.
- Event Loop: The event loop monitors the call stack and the callback queue. When the call stack is empty, it checks the callback queue. The first callback in the queue (the oldest) gets placed onto the call stack and executed. The "message" is the function's input parameter.
- When done, the event loop grabs the next one. If there are no callbacks in the Queue, the event loop pauses and waits for one to come.
- Single Treaded: JavaScript is a single threaded programming language. This means it has one call stack and one memory heap. So it can only execute one sequence of code at a time. Multi-threaded programming languages can split code sequences into separate threads and process them concurrently, but at the cost of managing the multiple treads.
- Synchronous (sync): Blocking architecture. Code is executed in sequence, line by line, one line at a time. When a synchronous function is called, the program waits until the function returns its value before proceeding to the next line. Synchronous API calls can slow the program down if it takes a while for execution.
- Asynchronous (async): Non-blocking architecture. Calls to asynchronous Web API or Node module functions may be asynchronous. JS does not wait for the result before moving on to the next line. They are processed concurrently in the Runtime environment but outside the JS engine. When complete, the API generates an event, passing the result to a callback function, which is added to the callback queue, then executed by the JS engine. Examples of asynchronous functions include HTTP request/responses, Database queries, SetTimeout, File System access.
- Core JS executes synchronously. Some Web APIs and Node.js modules are synchronous and some are asynchronous. Asynchronous API calls can be made synchronous using JS Promises.
Callback Functions
- Callback: a function that is to be executed after another function has finished executing.
- The callback is passed in as an argument to the outer function.
- Callbacks are used in many standard JS methods that run synchronously.
Examples - Array methods with callbacks
There are a number of JavaScript methods that take callback functions as an argument. Some Array examples include:
const arr = [1,2,3,4,5];
arr.forEach(callback(currentValue[, index [, array]])[, thisArg]);
//Executes callback on every array item and returns undefined. arr.forEach((num) => console.log(num));
//logs each element.arr.map(callback(currentValue[, index[, array]])[, thisObject]);
//Executes callback on every element in the array, putting each return value into a new array. Returns new array. arr.map((num) => num * 2);
//Returns [2, 4, 6, 8, 10];arr.filter(callback(element[, index[, array]])[, thisArg]);
//Returns a new array containing the items for which callback returned true. arr.filter((num) => num >= 3);
//Returns [3, 4, 5]arr.find(callback(element[, index[, array]])[, thisArg]);
//Returns first element that passes a test in a function. Returns undefined if no match.arr.find((num) => num >= 3);
//Returns 3Callbacks in asynchonous API function calls
Callbacks can also be used in asynchronous functions to perform an operation on the result.Prior to ES6 Promises, this was the only way to handle asynchronous function results.
const asyncFunc = (callback) => { const result = /* do some asynchronous task that returns a result */
return callback(result); }; const callback = (result) => /* do some operation on the result */;
asyncFunc(callback); //Call an asynchronous function passing in a callback.
Examples
Example1: Node module
The Node.js file system module interfaces with the host computer's file system. If it doesn't include "Sync" in the function name, it operates asynchronously by passing in a callback function that executes when the result is returned.
The below method returns an array of file names and passes them as an argument to the callback function.
Example2: setTimeout
Make a function that calls setTimeout with a parameter for a callback function. Define and pass in the callback to be executed when the timer expires.
The Node.js file system module interfaces with the host computer's file system. If it doesn't include "Sync" in the function name, it operates asynchronously by passing in a callback function that executes when the result is returned.
fs.readdir(path[, options], callback)
//Returns array of all file and directory names in the given path.The below method returns an array of file names and passes them as an argument to the callback function.
const fs = require('fs'); fs.readdir('.', (err, files) => console.log(files));
Example2: setTimeout
Make a function that calls setTimeout with a parameter for a callback function. Define and pass in the callback to be executed when the timer expires.
const getUsers = (callback) => { const users = ['Joey', 'Sheena', 'Johnny', 'Judy'];
setTimeout(() => callback(users), 1000); }; const logUsers = (users) => console.log(users); // Callback function.
getUsers(logUsers);
Promise (ES2015)
- Promises are an alternative to using callbacks to handle asynchronous functions.
- A Promise is an object representing the eventual completion or failure of an asynchronous operation. Created when an asynchronous statement is first executed, it waits until a result is returned, then executes its own callback statements.
Promise global object
- Ref: MDN Global_Objects/Promise
- Promise is a JavaScript standard built-in object in the global scope.
- Promise includes a constructor function, static and instance properties and methods.
More info
Promise global object
- Promise is a JavaScript standard built-in object. It is also called a global object because it is attached to the global object (window or global):
Promise === window.Promise; // returns true in the browser environment Promise === global.Promise; // returns true in the Node.js environment
- Promise is a constructor function (functions are a type of object).
typeof Promise; // returns 'function'
- When called with the new keyword, it instantiates a Promise object.
const prom = new Promise((resolve, reject) => { resolve(value); reject(reason) });
typeof prom; // returns 'object'
Promise static properties and methods:
Object.getOwnPropertyNames(Promise); // returns: length, name, prototype, all, allSettled, any, race, resolve, reject
Promise Instance properties and methods:
- There is no Promise literal syntax.
- Promise.prototype contains properties and methods you can call on a Promise instance.
Object.getOwnPropertyNames(Promise.prototype); // Returns: constructor, then, catch, finally
- constructor is a reference to the Promise() constructor function.
Promise constructor
Create a promise object by calling the Promise constructor function
const prom = new Promise((resolve, reject) => {
// Execute a task that resolves to a value or a reject reason.
if (success) return resolve(value);
else return reject(reason);
});
- Parameter: Takes a function as the parameter called the executor function.
- Executor function passes in two built-in functions as parameters: resolve and optional reject. Call them with a value to resolve to, or the reason to reject.
Example and explanation
Create a promise object, passing in resolve and reject callback functions.
Explanation:
const prom = new Promise((resolve, reject) => { setTimeout(() => { console.log('Processing the database query'); const success = Math.round(Math.random()) === 1; //Random true or False if (success) { const value = ['Joey', 'Sheena', 'Johnny', 'Judy']; resolve(value); } else { const reason = 'There was a problem'; reject(reason); } }, 1000); });
Explanation:
- When creating a new Promise object you pass in a function (called the executor) as the argument.
- The executor function itself passes in two built-in functions as parameters. The resolve function and the optional reject function.
- SetTimeout is an asynchronous function from the Web API. The first argument is the function to be executed when the timer expires. The second argument is the timer set to 1000 milliseconds (i.e., 1 second).
Promise States - (Internal) Instance Properties
- Internal properties are used internally by JS, but can't be accessed by your code.
- Can be viewed in Chrome Dev tools, surrounded by double square brackets [[]].
[[PromiseState]]
//A promise can be in one of three states: pending, fulfilled, or rejected. When the promise is fulfilled or rejected it is said to be settled.
[[PromiseResult]]
//Initially undefined. When settled: resolved value or rejected reason. Example
Create a promise object, passing in resolve and reject callback functions.
Explanation:
const prom = new Promise((resolve, reject) => { setTimeout(() => { if (Math.round(Math.random()) === 1) { const value = ['Joey', 'Sheena', 'Johnny', 'Judy']; resolve(value); } else { const reason = 'There was a problem'; reject(reason); } }, 1000); }); prom; //Returns {[[PromiseState]]: "pending", [[PromiseResult]]: undefined} // Wait at least one second. prom; //Returns {[[PromiseState]]: "fulfilled", [[PromiseResult]]: Array(4)}
Explanation:
- When creating a new Promise object you pass in a function (called the executor) as the argument.
- The executor function itself takes two functions as parameters. A resolve function and an optional reject function.
- SetTimeout is an asynchronous function from the Web API. The first argument is the function to be executed when the timer expires. The second argument is the timer set to 1000 milliseconds (i.e., 1 second).
- Promise object internal properties:
- Initial values:
{[[PromiseState]]: "pending", [[PromiseResult]]: undefined}
- Settled values if resolved:
{[[PromiseState]]: "fulfilled", [[PromiseResult]]: ['Joey', 'Sheena', 'Johnny', 'Judy']}
- Settled values if rejected:
{[[PromiseState]]: "rejected", [[PromiseResult]]: 'There was a problem'}
Thenables - Instance Methods
Thenables: The below instance methods execute when the promise is settled.
prom.then((value) => /*handle resolved*/);
//When promise resolves, calls handler function.prom.catch((err) => /*handle rejected*/);
//When promise rejects, calls handler function.prom.finally(callback);
//Executes callback when promise settles (fulfilled or rejected).Example with explanation
- Create a promise object, passing in resolve and reject callback functions.
- Call then(callback), catch(callback), and optional finally(callback) when promise settles.
const prom = new Promise((resolve, reject) => { setTimeout(() => { if (Math.round(Math.random()) === 1) { // true 50% of the time. const value = ['Joey', 'Sheena', 'Johnny', 'Judy']; resolve(value); } else { const reason = 'There was a problem'; reject(reason); } }, 1000); });// Execute if/when the promise resolves. prom.then((users) => console.log(users)); // Execute if/when the promise rejects. prom.catch((err) => console.log(err)); prom.finally(() => console.log('The promise has settled - resolved or rejected'));
Explanation:
- When creating a new Promise object, pass in a function (called the executor) as the argument.
- The executor function itself takes two callback functions as parameters. A resolve function and an optional reject function.
- SetTimeout is an asynchronous function from the Web API. The first argument is the function to be executed when the timer expires. The second argument is the timer in milliseconds. This timer is set to execute after 1 second.
- The Promise object immediately returns internal properties of:
[[promiseStatus]]: "pending", [[promiseValue]]: undefined
- Once settled, the prom object updates.
- If resolved:
{[[promiseStatus]]: "fulfilled", [[promiseValue]]: ['Joey', 'Sheena', 'Johnny', 'Judy']}
- If rejected:
{[[promiseStatus]]: "rejected", [[promiseValue]]: 'There was a problem'}
- Once settled, the appropriate callback function is executed:
- prom.then((users) => console.log(users)); //When promise resolves, calls handler function, parameter is the resolved value.
- prom.catch((err) => /*handle rejected*/); //When promise rejects, calls handler function, parameter is the reject reason.
- prom.finally(callback); //Executes callback function when promise settles (fulfilled or rejected).
Async-Await (ES2017)
Ref: MDN Statements/async_function
- Async/await is an alternative syntax to thenables for handling Promise results.
- Append async keyword to functions using one or more await expressions.
- await can only be used inside async functions.
- place await in front of new Promise objects or functions that return Promise objects.
- await expressions wait for the promise to settle before moving to the next statement.
- Async/await enables the use of ordinary try/catch blocks around asynchronous code.
async function parentFunction() {Async with an arrow function:
const res = await new Promise((resolve, reject) => { //Perform a task. If successful return a value. If not return a reason. if (success) resolve(value); else reject(reason); })
}
const parentFunction = async () => {...}
Example
- To use await inside a function, add async keyword to the function declaration.
- Create a promise object, passing in the resolve callback function.
- To handle the resolved callback response using an await expression rather than thenables, append keyword async to the function. This will make the executor function behave as though it's synchronous, waiting for the result before executing the next statement.
async function wrapper() { const users = await new Promise((resolve) => {or
setTimeout(() => {
const users = ['Joey', 'Sheena', 'Johnny', 'Judy'];
resolve(users);
}, 1000);
}); }
async function wrapper() { function getUsers() {
return new Promise((resolve) => {
setTimeout(() => {
const users = ['Joey', 'Sheena', 'Johnny', 'Judy'];
resolve(users);
}, 1000);
});
}
const users = await getUsers(); }
Await in Try/Catch blocks
try...catch statement marks a block of statements to try and specifies a response if an exception is thrown.
try {
const value = await new Promise((res, rej) => { res(val); rej(err); });
/* Handle value returned from fulfilled Promise object */
}
catch (err) {
/* Handle rejected promise object */
}
Examples
Example 1: The below setTimeout Web API function simulates a database pull or a website API call. It will either resolve to the users array, or reject with a message indicating a problem. Rejections are handled in the catch block.
Example 2: Call the promise-based Fetch method awaiting the result.
const getUsers = async () => { try { const users = await new Promise((resolve, reject) => { setTimeout(function() { if (Math.round(Math.random()) === 1) { const users = ['Joey', 'Sheena', 'Johnny', 'Judy']; resolve(users); } else { reject('There was a problem'); } }, 1000); }); console.log(users); } catch (err) { console.log(err); } } getUsers();
Example 2: Call the promise-based Fetch method awaiting the result.
const fetchUsers = async () => { try { const apiTestUrl = 'https://jsonplaceholder.typicode.com/users'; const res = await fetch(apiTestUrl); if (!res.ok) throw new Error(`${res.status} Path not found`); const data = await res.json(); console.log(data); } catch(err) { console.error(err.toString()); } } fetchUsers();
Immediately resolved Promises
Non-asynchronous Promises execute immediately.Example
const usersProm = new Promise((resolve) => {
let users = ['Joey', 'Sheena', 'Johnny', 'Judy'];
resolve(users);
});
usersProm.then((users) => console.log(users));
Explanation: If a non-asynchronous statement is wrapped in a Promise object:
- The executor function resolves immediately.
- The promise object internal properties are set to
{ [[PromiseStatus]]: "resolved", [[PromiseValue]]: ['Joey', 'Sheena', 'Johnny', 'Judy'] }
- The thenable callback function is placed in the callback queue.
Web APIs and Node packages that return promises
Some asynchronous Web APIs and Node package functions return promise objects:
const myFunction = async () => {To test if a method returns a promise object, call it without await:
const res = await apiCall(); //Call API function that returns a promise.
}
const res = apiCall(); res instanceof Promise; // true
Fetch Example
Fetch - Test if fetch() uses promises
Test if sessionStorage uses promises
Fetch - Thenables:
Fetch - async/await function called from try/catch:
Fetch - async/await function with conditionals called from try/catch:
const res = fetch('https://jsonplaceholder.typicode.com/users');//Returns a Promise object so it uses promises
Test if sessionStorage uses promises
const user = sessionStorage.getItem('user');//Returns undefined. Since it doesn't return a Promise object, it doesn't use promises.
Fetch - Thenables:
let isLoading = true; const apiTestUrl = 'https://jsonplaceholder.typicode.com/users'; fetch(apiTestUrl) .then((res) => res.json()) .then((data) => console.log(data)) .catch((err) => console.error(err.toString())) .finally(() => isLoading = false);
Fetch - async/await function called from try/catch:
const fetchData = async () => { let isLoading = true; try { const url = 'https://jsonplaceholder.typicode.com/users'; const res = await fetch(url); const data = await res.json(); console.log(data); } catch(err) { console.error(err.toString()); } isLoading = false; }
Fetch - async/await function with conditionals called from try/catch:
const fetchData = async () => { try { const url = 'https://jsonplaceholder.typicode.com/users'; const res = await fetch(url); if (res.ok) { const data = await res.json(); console.log(data); } else { throw new Error('API call unsuccessful'); } } catch (err) { console.error(err.toString()); } }
Static Methods
Promise.resolve(value);
//Returns a new Promise object, resolved with the given value.Promise.reject(reason);
//Returns a new Promise object, rejected with the given reason.Examples
Promise.resolve()
Promise.reject()
res = await Promise.resolve('This is a resolved promise value.');// Logs: 'This is a resolved promise value.'
console.log(res);
Promise.reject()
try {
await Promise.reject('This promise was rejected.');
}
catch (err) {
console.error('Error: ' + err);
}
// Logs: 'Error: This promise was rejected.'
Promise.any([prom1, prom2[,...]])
//Takes an iterable of Promise objects. As soon as one of them fulfills, returns a single promise that resolves with the value from that promise. Example
const prom1 = new Promise((resolve, reject) => {
setTimeout(() => resolve('Resolved after 3 secs'), 3000)
});
const prom2 = new Promise((resolve, reject) => {
setTimeout(() => reject('Rejected after 1 sec'), 1000);
});
const prom3 = new Promise((resolve, reject) => {
setTimeout(() => resolve('Resolved after 2 secs'), 2000)
});
Promise.any([prom1, prom2, prom3])
.then((values) => console.log(values))
.catch((err) => console.error('Error: ' + err));
Logs: Resolved after 2 secs
The first fulfilled promise. Ignores rejected promises.
The first fulfilled promise. Ignores rejected promises.
Promise.race([prom1, prom2[,...]]);
//Takes an iterable of Promise objects. As soon as one of them settles returns the value or reject reason of that promise.Example
const prom1 = new Promise((resolve, reject) => {
setTimeout(() => resolve('Resolved after 3 secs'), 3000)
});
const prom2 = new Promise((resolve, reject) => {
setTimeout(() => reject('Rejected after 1 sec'), 1000);
});
const prom3 = new Promise((resolve, reject) => {
setTimeout(() => resolve('Resolved after 2 secs'), 2000)
});
Promise.race([prom1, prom2, prom3])
.then((values) => console.log(values))
.catch((err) => console.error('Error: ' + err));
Logs: Error: Rejected after 1 sec
The first settled promise (fulfilled or rejected).
The first settled promise (fulfilled or rejected).
Promise.all([prom1, prom2[,...]]);
//Returns a promise that resolves when all promises resolve, returning an array of resolved values. It rejects if any promise is rejected.More details and examples
- The Promise.all() method returns a single Promise that resolves when all of the promises passed as an iterable have resolved or when the iterable contains no promises.
- If any of the underlying promises reject, then Promise.all rejects, returning the first reject message. It does not wait for the rest of the promises to complete.
- There is no implied ordering in the execution of the array of Promises given, so there must be no dependency in any Promise on the order of execution of the Promises.
- Results are returned in an array.
Example:
Returns a single promise that resolves when all the promises successfully resolve.
const p1 = 'p1 Not an actual Promise'; const p2 = Promise.resolve('p2 Immediately resolved'); const p3 = new Promise((resolve) => { setTimeout(resolve, 2000, 'p3 Resolved after 2 secs') }); Promise.all([p1, p2, p3]) .then((values) => console.log(values)) .catch((err) => console.error('Error: ' + err)); // ["p1 Not an actual Promise", "p2 Immediately resolved", "p3 Resolved after 2 secs"]
Example with a reject:
const p1 = 'p1 Not an actual Promise.'; const p2 = Promise.reject('p2 There was a problem'); const p3 = new Promise((resolve, reject) => { setTimeout(resolve, 2000, 'p3 Resolved after 2 secs') }); Promise.all([p1, p2, p3]) .then((values) => console.log(values)) .catch((err) => console.error('Error: ' + err)); // Error: p2 There was a problem
Promise.allSettled([prom1, prom2[,...]]);
//Returns promise that resolves when all promises have settled. Value is array of one object per promise with properties for status and value or reject reason.More details and example
Return a promise that resolves when all the promises have settled:
const p1 = 'p1 Not an actual Promise.'; const p2 = Promise.reject('p2 There was a problem'); const p3 = new Promise((resolve, reject) => { setTimeout(resolve, 2000, 'p3 Resolved after 2 secs') }); Promise.allSettled([p1, p2, p3]) .then((values) => console.log(values));
Resolves to an array of one object per promise containing the status and value or reject reason.
// [{status: "fulfilled", value: "p1 Not an actual Promise."} {status: "rejected", reason: "p2 There was a problem"} {status: "fulfilled", value: "p3 Resolved after 2 secs"}]
- You can iterate over the result:
.then((results) => results.forEach((res) => if (res.status === "fulfilled") console.log(res.value)));
Web APIs
Ref: MDN Web/API
Overview
- Ecma International sets the ECMAScript standards which are adopted into the JavaScript programming language.
- In addition there are a number of web APIs, collectively called the Browser Object Model (BOM), which are supported by all the major web browsers. Most of these standards are set by the W3C and WHATWG organizations, not ECMA International.
- Web APIs are part of the browser's global scope and are attached to the Window object.
- The DOM (Document Object Model), which represents a web page, is a subset of the BOM and one of the Web APIs.
- When calling properties and methods on the global scope, the window object is assumed if not provided. So
window.document
anddocument
both call the window's document object.
Console
Ref: MDN Web/API/Console
To view in Chrome Dev tools: Fn+F12
Substitutions: %s string, %i integer, %f float, %o object.
Clear:
To view in Chrome Dev tools: Fn+F12
console.log('text');
//Logs text to the console. Returns undefined. Useful for debugging.console.log(2, 'second item', '\n');
Log multiple items separated by commas. "\n" adds a line.console.info(msg);
Log information.console.warn(msg);
Log a warning.console.error(err);
Log an error.Substitutions: %s string, %i integer, %f float, %o object.
console.log('The %s goes here', 'fourth item');
Logs The fourth item goes here.Clear:
console.clear();
clears the console.Substitution examples: Integer, float, object.
- Float:
console.log('The price is %f on sale.', 2.99);
returns The price is 2.99 on sale. - Integer:
console.log('The price is %i dollars.', 2.99);
Truncates decimals. Returns The price is 2 dollars. - Object:
console.log('Item object %o', { description: 'cup', price: 2.99 });
Inserts an object which you can inspect.
Location
Ref: MDN Web/API/Location
The Location interface represents the location (URL) of the object it is linked to.
Example URL:
The Location interface represents the location (URL) of the object it is linked to.
Example URL:
https://example.com:3000/users?id=261847#address
location.href;
or location.toString();
//Returns the whole url as a string.location.origin;
//"https://example.com:3000" -- returns whole url up to the path.location.protocol;
//"https:" -- Returns protocol scheme of the url including ":"location.host;
//"example.com:3000/" -- Returns host name and port.location.hostname;
//"example.com" -- Returns hostname.location.port;
//"3000" -- Returns port number.location.pathname;
//"/users" -- Returns path. Excludes query strings, fragments.location.search;
//"?id=261847" -- Returns the query string.location.hash;
//"#address" -- Returns the fragment identifier.location.reload();
//Reloads the current URL, like browser refresh button.location.assign('url');
//Loads the resource at the URL provided in parameter.location.replace('url');
//Like assign() except current page won't be saved in session History.History
Browser session history. Ref: MDN Web/API/Historyhistory.back();
//Go to previous page in session history (like browser Back button).history.forward();
//Go to next page in session history (like browser Forward button).Web Storage API
Ref: MDN Web/API/Storage
Details
- In web applications most storage is done in a database.
- Small amounts of data can be stored in a cookie, session, or localStorage.
- Cookies are generated on the server side using methods from web frameworks like NodeJS Express. They are passed back and forth between a server and browser in the HTTP request and response objects.
- Session and LocalStorage can be managed by JS and the Web Storage API.
- Data stored in Sessions are persisted until the browser window is closed.
- Data stored in LocalStorage persists even after the browser window is closed.
SessionStorage (persists until the browser window is closed)
sessionStorage.getItem('key');
//Retrieve an item.sessionStorage.setItem('key', 'value');
//Store item as key value pairs.sessionStorage.removeItem('key');
//Remove an item.sessionStorage.clear();
//Remove all items from sessionStorage.View in browser: Chrome Dev Tools > Application tab > Storage > SessionStorage
More details and example
- SessionStorage is a global read-only property of the browser's Window object for the current origin.
- SessionStorage is similar to localStorage except the data is cleared when the page session ends.
- A page session lasts as long as the browser is open, and survives over page reloads and restores. If you open another browser tab on the same URL a separate session is created. It is destroyed when that tab is closed. Note session cookies do not create separate instances for multiple tabs.
- Session data is stored in a string of key value pairs. You can stringify objects and arrays into JSON format before storing with
JSON.stringify(JS)
and convert it back to JS withJSON.parse('JSON string')
.
let userObj = { name: 'Joey', age: 22, active: true };
sessionStorage.setItem('user', JSON.stringify(userObj));
let userObj = JSON.parse(sessionStorage.getItem('user')) || {}; // set empty obj as default.
LocalStorage (persists indefinitely)
localStorage.getItem('key');
//Retrieve an item.localStorage.setItem('key', 'value');
//Store item as key value pairs.localStorage.removeItem('key');
//Remove an item.localStorage.clear();
//Remove all items from localStorage.View in browser: Chrome Dev Tools > Application tab > Storage > LocalStorage
More details and example
- LocalStorage is a global read-only property of the browser's Window object for the current origin.
- LocalStorage is similar to sessionStorage except it has no expiration time.
- Data is stored in a string of key value pairs. You can stringify objects and arrays into JSON format before storing with
JSON.stringify(JS)
and convert it back to JS withJSON.parse('JSON string')
.
let userObj = { name: 'Joey', age: 22, active: true }
localStorage.setItem('user', JSON.stringify(userObj));
let userObj = JSON.parse(localStorage.getItem('user')) || {}; // set empty obj as default.
Timers
setTimeout()
setTimeout(callbackFunction[, delayInMilliseconds]);
//Sets a timer which executes a function when the timer expires. Returns a timeoutID number.Example
setTimeout(() => {
console.log('logs after 2 seconds');
}, 2000);
- The timer is set in milliseconds. If omitted it defaults to 0. The callback function executes asynchronously so even with a timer set to 0 milliseconds, it will still execute after any synchronous statements following it:
setTimeout(() => console.log('This logs second'), 0);
console.log('This logs first');
const timeoutID = setTimeout(callbackFunction[, delayInMilliseconds]);
//Return value is a timeoutID number which identifies the timer created by the call to setTimeout().clearTimeout(timeoutID)
Cancels the setTimeout() method before the timer expires. Pass in the timeoutID.Example
const timeoutID = setTimeout(() => { console.log('Logs after 2 seconds.'); }, 2000);
- The return value of the setTimeout() method is a timeoutID identifying the timer created by the call to setTimeout(). It is used by the clearTimeout() to cancel the setTimeout before it executes.
- Call the clearTimeout method:
clearTimeout(timeoutID);
- This could be triggered by clicking a button on a web page:
<button onclick="() => clearTimeout(timeoutID);">Cancel Timeout</button>
SetInterval()
setInterval(callbackFunction, delayInMilliseconds);
//Executes the callback function every time a given number of milliseconds elapses.Example
- Log the number of seconds every second.
let i = 0;
setInterval(() => {
console.log(++i);
}, 1000);
const intervalID = setInterval(callbackFunction, delayInMilliseconds);
//Return value is an intervalID number identifying the timer created by the call to setInterval(). It can be used by the clearInteval() method to cancel it.clearInterval(intervalID)
Cancels the setInterval() method identified by the timeoutID.Example
- Log the seconds count every second, cancelling after 10.
let i = 0;
const intervalID = setInterval(() => {
i++;
console.log(i);
if (i >= 10) {
console.log('10 seconds have elapsed');
clearInterval(intervalID);
}
}, 1000);
Fetch API
Details
- Fetch API: provides an interface for fetching resources.
- It can be used to make Ajax requests for data from a client browser to a server. The data can be taken from the response object and displayed on a web page with JS manipulation of the DOM, all without a full-page refresh.
- Fetch is meant as a replacement for XMLHttpRequest.
- Browser Support: Edge 14 (Aug'16), not supported by IE, Chrome 42 (Apr'15), Mozilla 39 (Jul'15), Safari 10.1 (Mar'17).
fetch(url[, {options}]);
//Sends HTTP request to the designated URL, returns a promise. More details
- Fetch provides the fetch() method, which sends an HTTP request (GET, POST, PUT, PATCH, DELETE) to the designated URL.
- Full list of options: MDN fetch. Includes HTTP method, headers, body (for form data), and more.
- It returns a Promise object that resolves to the Response to that request, whether it is successful or not.
- It won't reject on HTTP error statuses like 404 or 500. It will only reject on network failure or anything preventing the request from completing.
const fetchData = async () => { try { const res = await fetch('url'); if (!res.ok) throw new Error(`${res.status} Path not found`); const data = await res.json(); return data; } catch(err) { console.error(err.toString()); } } const data = await fetchData();
response.json()
is part of the Fetch API. It first returns a Promise. Resolves after parsing the response body converting JSON to JS.
More details and example
Send a GET request to the below fake API:
const fetchUsers = async () => {
try {
const res = await fetch('https://jsonplaceholder.typicode.com/users'); if (!res.ok) throw new Error(`${res.status} Path not found`);
const data = await res.json();
return data;
} catch(err) {
console.error(err.toString());
}
}
const users = await fetchUsers();
- GET is the default HTTP request method. The above example fetches an array of fake users from the API.
- Once the asynchronous Promise is resolved and the response received you can apply then or async await to handle the asynchronous response.
- The .json() method of the Body mixin takes the response stream and reads it to completion. Returns a promise that resolves with the result of parsing the body text as JSON.
Post Request:
const jsonData = JSON.stringify({ prop1: val, prop2: val });
fetch('url', { method: 'POST', body: jsonData });
More details and example
- This example sends a post request to an API.
- The method option specifies this is a POST request.
- The body option contains the POST data, which is an object converted to JSON text.
const jsonData = JSON.stringify({ title: 'JavaScript', content: 'article' });
fetch('http://example.com/articles/api', {method: 'POST', body: jsonData});
DOM
Terms - DOM, element, node, window, document
- Document Object Model: (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, SVG, and XML documents. All browsers build a DOM of the web page when opened, which is an object oriented model of its logical structure. The DOM is like an inverted tree with the HTML container at the root (top) of the tree. Nodes are the tags and the content between them. They form branches extending downward from that root.
- HTML Elements: consist of a tag name and a set of name=value pairs known as attributes (e.g., id, class, src). They generally contain content.
- Nodes: Everything in the DOM is a node starting with the document object itself (the document node). HTML elements are called element nodes and represent containers. HTML attributes (e.g., class, id, href, style) are attribute nodes. You can access the HTML attribute values of a given element with JS through corresponding properties defined on the DOM element. Text inside HTML elements are text nodes. Each node has one parent node, and may have child and sibling nodes. Both CSS and JS scripts access the content of the page in this way. JS can be used to manipulate the DOM of a page dynamically to add, delete, and modify elements.
- Window object: is the first thing that gets loaded into the browser and is the root of the DOM. For JS it is the global object and can be accessed with
window.property
orwindow.method
, or you can leave out window and access the property or method directly. All global JS objects, function declarations, and variables declared with var automatically become members of the window object. Global variables declared with const or let do not become members of the window object. - Document object: is the HTML document that gets loaded into the browser. It is the root of all objects on a webpage. To access properties and methods on an HTML page start with accessing the document object:
document.property
ordocument.method
. Document is a property of the window object. The window namespace is implicit so it can be included or left out:window.document.property
. Examples: - Document property: Body is an element of the DOM. Change its HTML content with:
document.body.innerHTML = '<h1>Hello world</h1>';
- Document method: The write method will display it's argument as the document's content:
document.write('<h1>Hello world</h1>');
DOM Tree
Example HTML document, DOM Tree diagram, DOM tree definition
HTML Document:

<!DOCTYPE html> <html> <head> <title>Learn DOM</title> </head> <body> <h1 class="text-center">Learn DOM</h1> <p>Blah blah.</p> <img src="dom.png" alt="DOM Diagram"> </body> </html>
- DOM Tree: When the browser loads an HTML document it translates it into an object model and places it in memory. It represents the document as an inverted node tree with the HTML container at the root (top) of the tree. Each node is an object that represents part of the document (e.g., an element, text string, or comment). They form branches extending downward from that root.
- The DOM is an API that allows JavaScript to access and interact with every node in the document. Nodes can be created, moved and changed. Event listeners can be added to nodes and triggered when a given event occurs.
DOM API
- Ref: MDN_Web/API/HTML_DOM_API
- DOM Tree nodes can be accessed through the DOM API.
- The DOM API consists of a series of Interfaces depending on its nodeType and, for elements, its tagName.
DOM API partial list
DOM APIs partial list including commonly used properties and methods.
Indentation indicates inheritance.
Indentation indicates inheritance.
- EventTarget: addEventListener()
- Node: nodeName, nodeType, nodeValue, parentNode, childNodes, previousSibling, nextSibling - Document: getElementById(), querySelector(), createElement(), body, title, URL - Element: id, tagName, innerHTML, textContent, getAttribute, setAttribute, removeAttribute, className, classList, previousElementSibling, children, firstChildElement, prepend(), append(), insertAdjacentElement(), replaceChild(), remove()- HTMLElement: innerText, style, Events: copy, cut, paste- HTMLTableElement: caption, tHead, tFoot, rows, tBodies, insertRow(), deleteRow(), createTHead() - HTMLFormElement: submit(), reset(), action - HTMLAnchorElement: href, origin, host, hostname, pathname- HTMLImageElement: src, alt, width, height- HTMLMediaElement: src, autoplay, play(), pause()
Script Element
<script src="fileName.js" defer></script>
//Place script element in the document head elem. Defer/async attributes load the file in parallel with the HTML document being parsed.
- Async: executes the script or scripts as soon as they are loaded.
- Defer: executes scripts in order after doc is parsed, before firing DOMContentLoaded.
More details
- Leave out the type attribute because "text/javascript" is already the default.
- Include the async or defer attribute. Both load the script file asynchronously (i.e., in parallel) with parsing the HTML document, thus speeding up the process. These are boolean attributes. Their presence sets the value to true. Their absence sets it to false. The difference is:
- Async executes the script or scripts as soon as they are loaded.
- Defer executes the script after the HTML document has been parsed, but before firing DOMContentLoaded. Multiple scripts will execute in the order they appear in the document.
- Use defer if there are multiple scripts that must be executed in order, or if the HTML document needs to be parsed before executing. Otherwise use async as it will be slightly more performant.
- In development you can put JS directly in the HTML file in the script element just above the closing body tag. This placement allows the HTML document to load before loading the JS:
<script>
alert('This alert function is in the HTML document');
</script>
The Document Interface
Ref: MDN_Web/API/Documentdocument;
//Selects the whole HTML document.document.body;
//Selects the document's body element.Term: getter methods
Getter Methods: are the document object methods to select the target elements.
JS single element selectors (getElementById and querySelector) return the first matching DOM element found. JS multiple element selectors like getElementsByTagName and querySelectorAll return an array-like object.
JS single element selectors (getElementById and querySelector) return the first matching DOM element found. JS multiple element selectors like getElementsByTagName and querySelectorAll return an array-like object.
Get Single Element using Selectors
Selectors: used by CSS/JS to select HTML elements by id, tag, class, or other attribute.
const elem = document.getElementById('id');
//Get first elem with the given id.const elem = document.querySelector('selector');
//'#id', '.class', 'tag', '[attribute="value"]' Examples
- Find the first element with id "heading".
const heading = document.getElementById('heading');
const heading = document.querySelector('#heading');
- Find the first element with tag "li".
const li = document.querySelector('li');
- Find the first element with class "list".
const list = document.querySelector('.list');
- Find the first element with the href attribute set to "http://example.com"
- For example: <a href="http://example.com">example</a>.
const exampleLink = document.querySelector('[href = "http://example.com"]');
- Find the first element with the data-category attribute set to "technology".
- For example: <h2 data-category="technology">Learn JavaScript</h2>
const techElem = document.querySelector('[data-category = "technology"]');
Get Multiple Elements with Selectors
GetElementsBy
document.getElementsByTagName('tag');
document.getElementsByClassName('className');
document.getElementsByName('name');
//Name attribute is used with form fields.- These return an array-like object of all matching nodes called HTMLCollection.
const elems = document.getElementsByTagName('tag'); Array.from(elems).forEach((elem) => /* Handle element */);
Examples
- Find all elements with tag "li".
document.getElementsByTagName('li');
- Find all elements with class "list-group-item".
document.getElementsByClassName('list-group-item');
You can access by index.
document.getElementsByTagName('button')[0];
// returns the first match.Iterate over the result:
- Find all elements with tag "button" using getElementsByTagName. Then iterate over the result.
- GetElementsBy returns an array-like object of all matching nodes called HTMLCollection. ForEach does not work on it so you have to convert it to an array first.
const buttons = document.getElementsByTagName('button');
Array.from(buttons).forEach((button) => { button.classList.add('btn-sm'); }
QuerySelectorAll
document.querySelectorAll('selector');
//'tag', '.className', '[attributeName="value"]'- Returns an array-like object of all the matching nodes called NodeList.
const elems = document.querySelectorAll('selector'); elems.forEach((elem) => /* Handle element */);
Examples
- Find all elements with tag "li".
document.querySelectorAll('li');
- Find all elements with class "list-group-item".
document.querySelectorAll('.list-group-item');
- Find all elements with tag "li" inside an element with id "articles".
document.querySelectorAll('#articles li');
- Find all elements with the href attribute set to "http://example.com"
- For example: <a href="http://example.com">example</a>.
document.querySelectorAll('[href = "http://example.com"]');
- Find all elements with the data-category attribute set to "technology".
- For example: <h2 data-category="technology">Learn JavaScript</h2>
document.querySelectorAll('[data-category = "technology"]');
Iterate over the result:
- Find all elements with tag "li" using querySelectorAll. Then iterate over the result.
- Returns an array-like object of all matching nodes called NodeList.
const elems = document.querySelectorAll('li'); elems.forEach((elem) => console.log(elem));
- Find all button elements and add a class to them:
document.querySelectorAll('button').forEach((elem) => { elem.classList.add('btn-sm'); });
The Element Interface
Ref: MDN_Web/API/Element
Get an Element Object:
Get an Element Object:
const elem = document.getElementById('id');
//Assign element to a variable.Example
<h1 id="heading">Learn JavaScript</h1>
//HTML element in the HTML document.const heading = document.getElementById('heading');
Terms - elements, attributes, properties
The browser parses an HTML document into the DOM. The DOM is an API that represents a document as a logical tree. Each branch of the tree ends in a node, and each node contains objects. DOM methods allow programmatic access to the tree. With them, you can change the document's structure, style, or content.
HTML Element Structure:
HTML Element Structure:
- HTML element consist of tags that may contain content:
<p>Some content</p>
- Tags:
- Elements have opening and closing tags. The opening tag starts with the tag name.
- Tags may contain text or HTML content between the opening and closing tags.
- Examples: body, h1-h7, p, div, a.
- Void elements: Do not have a closing tag and do not contain content. Examples: img, input, hr.
- Attributes:
- Attributes are name value pairs in the opening tag of an element. They contain information about an element.
- In terms of the DOM, attributes are nodes attached to an element.
- Properties: The browser converts the HTML into a document object. Each element becomes an object and the element content and attributes become its properties.
Examples of attributes/properties:
Applicable to all elements: id, class, style.
Applicable to image elements: src, alt, width, height.
Applicable to link elements: href, target.
Applicable to input elements: type, name, value, placeholder, autofocus, required, max, min, maxlength.
Applicable to all elements: id, class, style.
<h3 id="dom-topic" class="card-header" style="margin-top: 15px">Learn DOM</h3>
Applicable to image elements: src, alt, width, height.
<img src="diagram.png" alt="element diagram" width="200">
Applicable to link elements: href, target.
<a href="https://www.example.com" target="_blank">example</a>
Applicable to input elements: type, name, value, placeholder, autofocus, required, max, min, maxlength.
<input type="text" name="title" placeholder="Enter title" class="form-control" required>
Element Content - Get/Set/Remove/Compare
elem.outerHTML;
//Gets the element's outer HTML content.elem.outerHTML = 'New HTML element';
//Sets new outer HTML content.elem.outerHTML === 'value';
//Returns true/false.Examples and more details
- The outerHTML property includes the element's HTML tags with attributes and their and content.
- Includes all descendent elements, if any.
Example HTML document:
<h1 id="heading">Learn JavaScript</h1>
//HTML element in the HTML document.JavaScript file:
const heading = document.getElementById('heading');
//Assign heading element to variable.heading.outerHTML;
//Returns '<h1 id="heading">Learn JavaScript</h1>'heading.outerHTML = '<h2 id="heading">New Heading</h2>';
// Sets new HTML content.heading.outerHTML === '<h2 id="heading">New Heading</h2>';
//Returns true.elem.innerHTML;
//Gets the element's inner HTML content.elem.innerHTML = 'New HTML content';
//Sets new inner HTML content.elem.innerHTML += '<p>New Content</p>';
//Append content to element end.elem.innerHTML = '<p>New Content</p>' + elem.innerHTML;
//Prepend content to elem.elem.innerHTML === 'value';
//Returns true/falseelem.innerHTML = '';
//Clears the element's inner HTML content.Examples including inserting a list, and more details
- The innerHTML property includes text content and descendent HTML elements.
- Using the innerHTML property with user provided input is a potential security risk for web pages since html tags can be passed.
Example HTML document:
<h1 id="heading">Learn JavaScript <small>Intermediate Level</small></h1>
JavaScript file:
const heading = document.getElementById('heading');
//Assign heading element to variable.heading.innerHTML;
//Returns 'Learn JavaScript <small>Intermediate Level</small>'heading.innerHTML = 'Learn JavaScript <small>Advanced Level</small>';
//Sets new content.heading.innerHTML === 'Learn JavaScript <small>Advanced Level</small>';
//Returns true.heading.innerHTML = '';
//Clears the element's inner HTML content.Insert a list:
Empty HTML element:
<ul id="list"></ul>
In the JS file set an empty string variable, iterator over an array and inserting each item into an li element. Then use the innerHTML property to assign the completed list HTML string into the document.
const listElem = document.getElementById('list');
const listArray = ['Item 1', 'Item 2', 'Item 3'];
let listItems = '';
listArray.forEach((item) => {
listItems += `<li>${item}</li>`;
});
listElem.innerHTML = listItems;
elem.textContent;
//Gets the text content of the element.elem.textContent = 'New text content';
//Sets new text content.elem.textContent === 'value';
//Returns true/falseelem.textContent = '';
//Clears the element's text content.More details and examples
- The textContent property excludes HTML tags. Be aware that <br> tags are ignored.
- When setting element content, if you include any HTML tags, they will be treated as text.
- Includes all descendent elements, if any.
- The innerText property is similar with some differences. It creates new lines for <br> tags and does not include text in tags where the css visibility is set to none. Because it has to parse the HTML to find these, it is less performant. It has had support in all the major browsers for over 10 years except for Firefox which added support in 2016.
Example HTML document:
<h1 id="heading">Learn JavaScript</h1>
//HTML element in the HTML document.JavaScript file:
const heading = document.getElementById('heading');
//Assign heading element to variable.heading.textContent;
//Returns 'Learn JavaScript'.heading.textContent = 'New Heading';
// Sets new text content.heading.textContent === 'New Heading';
//Returns trueheading.textContent = '';
// Clears the text content of the target element.InnerText is like textContent, but it converts any line breaks into <br> elements.
elem.innerText;
//Gets the text content of the element. Line breaks convert to <br>.elem.innerText = 'Line 1.\nline 2';
//Sets new text content. Line breaks convert to <br>. More details and examples
- The innerText property is similar to textContent with some differences.
- It creates new lines for <br> tags and does not include text in tags where the css visibility is set to none.
- Because it has to parse the HTML to find these, it is slightly less performant.
Example HTML Document element:
<div id="article-1"> Line 1 of article.<br> line 2 of article. </div>
JavaScript file:
const article1 = document.getElementById('article-1');
//Assign element to variable.article1.innerText;
//Returns 'Learn JavaScript'.article1.innerText = 'Line A\nLine B';
//Sets new text content including line breaks.article1.innerText = '';
//Clears the text content of the target element.Element Properties/Attributes
elem.tagName;
//Returns the element's tag name in capital letters. Example
<h1 id="heading">Learn JavaScript</h1>
//HTML element in the HTML document.const elem = document.getElementById('heading');
elem.tagName;
// 'H1'Properties - get/set/check
Get and set element attributes as properties of the DOM element object:
Multiple target elements:
elem.propertyName;
//Returns the property value.elem.propertyName = 'value';
//Sets a new property value.elem.propertyName === 'value';
//Returns true/false.Multiple target elements:
document.querySelectorAll('tag').forEach((elem) => {
elem.propertyName = 'value';
});
Examples
Get and set the source property value from the element with id "image1":
Get all the input elements in the document, then set the disabled property to "true":
document.getElementById('image1').src;
document.getElementById('image1').src = 'img/some-img.png';
Get all the input elements in the document, then set the disabled property to "true":
document.querySelectorAll('input').forEach((elem) => {
elem.disabled = true;
});
Attributes - get/set/remove
elem.getAttribute('attrName');
//Returns the attribute value as a string.elem.setAttribute('attrName', 'value');
//Sets the attribute value.elem.removeAttribute('attrName');
//Removes the attribute.elem.hasAttribute('attrName');
//Checks if elem has attribute. Returns true/false. elem.hasAttributes();
//Returns true if the element has any attributes.Multiple target elements:
document.querySelectorAll('tag').forEach((elem) => { elem.setAttribute('attrName', 'value'); });
Examples
Return the src attribute of the image:
Set the src attribute:
Remove the alt attribute:
Set the disabled attribute value to true for all input elements:
document.getElementById('image1').getAttribute('src');
Set the src attribute:
document.getElementById('image1').setAttribute('src', 'img/some-img.png');
Remove the alt attribute:
document.getElementById('image1').removeAttribute('alt');
Set the disabled attribute value to true for all input elements:
document.querySelectorAll('input').forEach((elem) => {
elem.setAttribute('disabled', true);
});
Remove all disabled attributes from input elements:
Check if the image1 element has an "alt" attribute:
document.querySelectorAll('input').forEach((elem) => {
elem.removeAttribute('disabled');
});
Check if the image1 element has an "alt" attribute:
document.getElementById('image1').hasAttribute('alt');
Data Attributes: are user defined attributes prefixed with data-
document.querySelector('[data-name = "value"]');
//Get elem by its data attribute.elem.setAttribute('data-name', 'value');
// Set data attribute value. Example
- Unordered list of article titles. Each list item has a data-category attribute set to the article's category.
<ul id="articles"> <li data-category="technology">Learn JavaScript</li> <li data-category="finance">Learn HTML</li>
<li data-category="technology">Learn Unix</li> </ul>
- Find the first element with the data-category attribute set to "finance" and change it to "technology".
const elem = document.querySelector('[data-category = "finance"]');
elem.setAttribute('data-category', 'technology');
Classes
elem.className;
//Returns a string of all the element's class names.elem.className = 'className1 className2...';
//Set all classes for the element.elem.classList;
//Returns an array-like object with the element's class names.elem.classList.contains('className');
//Check if elem contains the class. Returns true/false.elem.classList.add('className1', 'name2');
//Add class(es) to an element.elem.classList.remove('className1', 'name2');
//Remove class(es). elem.classList.replace('oldClassName', 'newClassName');
//Replace a class. elem.classList.toggle('className1');
//Toggle remove/add a class. Returns false when removed, true when added back.Multiple Target Elements:
document.querySelectorAll('tag').forEach((elem) => {
elem.classList.add('className');
});
Examples
Example HTML Document element:
JavaScript file:
Multiple target elements:
<button id="calc-btn">Calculate</button>
JavaScript file:
const calcBtn = document.getElementById('calc-btn').classList;
calcBtn.classList.add('btn', 'btn-sm');
calcBtn.classList.remove('btn', 'btn-sm'); calcBtn.classList.replace('btn-sm', 'btn-lg');
calcBtn.classList.toggle('btn'); // Using ClassName: calcBtn.className = 'btn btn-sm';
Multiple target elements:
document.querySelectorAll('button').forEach((elem) => {
elem.classList.add('btn', 'btn-sm');
});
The Style Property
elem.style;
//Returns an object called CSSStyleDeclaration with style rule properties.elem.style.cssText;
//Returns the style attribute value as a string.elem.style.cssText = 'cssProp1: value; cssProp2: value;';
//Overwrite the entire style property.elem.style.cssPropertyName;
//Returns the value of the specified css property.elem.style.cssPropertyName = 'value';
//Add new or change existing cssProperty. If CSS property name contains dashes, replace with camelCase.elem.style.cssPropertyName === 'value';
//Check if prop is specified value. Returns boolean.Get the owned or inherited value of the specified css property that applies to an element:
getComputedStyle(elem).cssPropertyName;
//Returns the property value.Multiple target elements:
document.querySelectorAll('tag').forEach((elem) => {
elem.style.cssPropertyName = 'value';
});
More details, examples
- Generally you would set CSS styles in a separate stylesheet using CSS classes. But you can set styles directly on an element using the style attribute. These inline styles override CSS classes if there is a conflict.
- In this case we are accessing the style attribute as a property of the DOM element object.
- For multiple-word CSS properties replace dashes with lowerCamelCase:
style.backgroundColor
- or use bracket notation:
style['background-color']
Example HTML Document element:
<input id="input1" style="background-color: #d3d3d3;">
JavaScript File:
const input1 = document.getElementById('input1');
input1.getAttribute('style');
//"background-color: #d3d3d3;"input1.style.backgroundColor;
//"rgb(211, 211, 211)" Chrome returns color in rgb format.getComputedStyle(input1).fontSize;
//"16px"input1.style.backgroundColor = 'ghostWhite';
input1.style.fontSize = '12px';
//Adds a second style CSS property.input1.style.cssText = 'background-color: #d3d3d3; font-size: 12px;';
//Overwrites style prop.Change the background color of all input tags to maroon.
document.querySelectorAll('input').forEach((elem) => {
elem.style.backgroundColor = 'maroon';
});
Traversing the DOM (Elements)
elem.parentElement;
//Returns the parent element. elem.previousElementSibling;
//Previous element same level. elem.nextElementSibling;
//Next element at the same tree level. Returns null if none.elem.childElementCount;
//Returns the number of child elements. Returns null if none.elem.children;
//Returns an array-like object of the element's child elements.elem.children[n];
//Returns the child element at index n.elem.firstElementChild;
//Returns the first child element.elem.lastElementChild;
//Returns the last child element.elem.closest('selector');
//Returns the first ancestor element matching the selector or null.elem.scrollIntoView();
// Scrolls the web page until the element is in view.Example
HTML Document:
<!DOCTYPE html>
<html>
<head>
<title>Learn DOM</title>
</head>
<body>
<div class="container">
<h1>Learn DOM</h1>
<ul id="list">
<li id="li-1">Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<img src="images/dom.jpg">
</div>
</body>
</html>
Traverse the DOM: (return values follow two forward slashes //)
const list = document.getElementById('list');
const li1 = document.getElementById('li-1');
list.parentElement; // <div class="container"></div>
list.previousElementSibling; // <h1>Traverse the DOM</h1>
list.nextElementSibling; // <img src="images/traverse.png">
list.childElementCount; // 3
list.firstElementChild; // <li id="li-1">Item 1</li>
list.lastElementChild; // <li>Item 3</li>
list.children[1]; // <li>Item 2</li>
li1.closest('div'); // <div class="container"></div>
Elements - Create/Insert/Replace/Remove
Create Element
const elem = document.createElement('tagName');
//Creates a new element node.elem.className = 'class1[ class2 ...]';
//Add class names separated by spaces.elem.attributeName = 'value';
//Add attribute name (e.g., id, src, href, etc.) and value.elem.textContent = 'text';
//Add text content.elem.innerHTML = 'HTML elements and/or text';
//Alternatively add innerHTML.More details, example
InnerHTML() and innerText() work with existing elements. To add an element you need to first create an element node.
Example:
Or instead of just adding text content, add text and a child HTML element:
Example:
const li = document.createElement('li');
// Create a new list item element.li.className = 'list-group-item list-group-item-dark';
// Add one or more classes.li.id = 'todo5';
// Add the id attribute.li.textContent = 'Learn Databases';
// Add text content.Or instead of just adding text content, add text and a child HTML element:
li.innerHTML = 'Learn Databases <small>SQL and NoSQL</small>';
// Add innerHTML.Prepend/Append Child Element
elem.prepend(newElem[, newElem2,...]);
//Add one or more elems as the first child(ren).elem.append(newElem[, newElem2,...]);
//Add one or more elems as the last child(ren). Example
HTML Document contains an empty unordered list element:
// JavaScript file gets the ul#articles element.
// Create a list item element adding a class and id attribute.
// Add textContent or innerHTML to the element.
Append the new element to the end of the specified target element.
<ul id="articles"></ul>
// JavaScript file gets the ul#articles element.
const list = document.getElementById('articles');
// Create a list item element adding a class and id attribute.
const li = document.createElement('li');
li.className = 'list-group-item';
li.id = 'todo6';
// Add textContent or innerHTML to the element.
li.textContent = 'Learn Unix';
li.innerHTML = 'Learn Unix <small>and Linux</small>';
Append the new element to the end of the specified target element.
list.append(li);
Insert Sibling Element
elem.insertAdjacentElement(where, newElem)
//Inserts newElem next to target elem. elem.insertAdjacentHTML(where, 'html')
//Inserts HTML string next to target elem. elem.insertAdjacentText(where, 'text')
//Inserts text string next to target elem. The where argument indicates where adjacent to the target elem to insert:
- 'beforebegin': Before the element itself.
- 'afterbegin': Just inside the element, before its first child.
- 'beforeend': Just inside the element, after its last child.
- 'afterend': After the element itself.
Examples
Insert Before:
Insert After:
- Create a li element. Insert it before element id 'todo-8'
const todo8 = document.getElementById('todo-8'); const li = document.createElement('li'); li.id = 'todo-7'; li.textContent = 'Learn Design Patterns'; todo8.insertAdjacentElement('beforebegin', li)
Insert After:
- Create a li element. Insert it after element id 'todo-6'
const todo6 = document.getElementById('todo-6'); const li = document.createElement('li'); li.id = 'todo-7'; li.textContent = 'Learn Data Structures'; todo6.insertAdjacentElement('afterend', li);
Replace or Remove Element
parentElem.replaceChild(newElem, oldElem);
//Replace element.elem.remove();
//Remove element. More details
- Remove breaks the relationship between a child and its parent. It doesn't actually delete the element, but you won't see it on the page.
The Node Interface
Ref: MDN_Web/API/Node
Node instance properties
node.nodeName;
//Returns the element tagName, #text, #comment, or #document.node.nodeType;
//Returns number identifying what the node is. Ref: MDN_nodeTypeNodeType: 1 Element, 2 Attribute, 3 Text, 8 Comment, 9 Document, 10 DocumentDoctype, 11 DocumentFragment.
node.nodeValue;
//Returns or sets the value of the current node. Document and element value is null. Example HTML document, DOM node tree diagram
HTML document:

<!DOCTYPE html> <html> <head> <title>DOM Nodes</title> </head> <body> <h1>DOM Nodes</h1> <p id="p-element-node"> <!-- this is a comment node --> <b>This is a text node inside a bold element node.</b> This is a text node. </p> <img src="images/dom-node-tree.jpg" alt="DOM Nodes"> </body> </html>
Traversing the DOM (Nodes)
elem.parentNode;
//Returns the parent node.elem.previousSibling;
//Previous node same level. Returns null if none.elem.nextSibling;
//Next node at the same tree level. Returns null if none.elem.childNodes;
//Returns an array-like object of the element's child nodes.elem.childNodes.length;
//Returns the number of child nodes.elem.childNodes[n];
//Returns the child node at index n.elem.firstChild;
//Returns the first child node. elem.lastChild;
//Returns the last child node. More details and example
- When traversing the DOM vertically, node and element will be the same except at the top and bottom of the DOM tree.
- At the top of the DOM tree is the document object.
- At the bottom of the DOM tree, the text inside an element is a text node.
- Elements can contain text, element, and comment child nodes.
- Whitespace between elements are text nodes.
Example:
The below element contains two nodes. A text node containing "Learn React ", and an element node.
<li id="todo3">Learn React <small>With Redux</small></li>
Create Text Node
const text = document.createTextNode('text');
//Creates a new text node.Instance methods
elem.hasChildNodes();
//True if the elem has child nodes.node.isSameNode(otherNode);
//True if they are the same node.node.isEqualNode(otherNode);
//True if values are equal.elem.contains(node);
//True if node is descendant of the given elem.node.insertBefore(newNode, referenceNode);
//Inserts a node before the reference node.elem.appendChild(newNode);
//Appends a node as the last child of the elem.elem.replaceChild(newChild, oldChild);
//Replaces a child node.elem.removeChild(childNode);
//Removes a child node.Events
Terms (events, event-driven)
- HTML events: Actions or occurrences that happen to HTML elements. They can be user actions such as clicking a mouse button, or network or browser state changes like a web page load completing.
- Event-driven: Most applications are event-driven. They sit around and wait for events to happen, then respond to them. In JS, the events are normally used in combination with functions, and the function will not be executed until the event occurs.
Event Types
Full list: MDN Events | Common Events:
Mouse click events: click, dblclick, mousedown, mouseup.
Mouse hover events: mouseenter, mousemove, mouseleave, mouseover. Does not include children elements.
Keyboard events: keydown, keyup.
Form events: focus, blur, change, submit, reset.
Media events: video is played, paused, ends.
Window events: DOMContentLoaded, load, unload, visibilitychange, scroll, resize, error.
Mouse click events: click, dblclick, mousedown, mouseup.
Mouse hover events: mouseenter, mousemove, mouseleave, mouseover. Does not include children elements.
Keyboard events: keydown, keyup.
Form events: focus, blur, change, submit, reset.
Media events: video is played, paused, ends.
Window events: DOMContentLoaded, load, unload, visibilitychange, scroll, resize, error.
DOMContentLoaded vs load, and Example
- DOMContentLoaded event is triggered when the document is parsed and the DOM is ready to be manipulated. Images, stylesheets and associated resources may not have been loaded yet. Generally, use this event instead of load.
- load event is triggered when the document and all dependent resources (e.g., images, stylesheets) have finished loading.
ToDo List Example: ToDo list items needs to be fetched from an external source like a database or API URL.
HTML Document elements:
<ul id="todoList"></ul>JavaScript file:
const todoList = document.getElementById('todoList'); document.addEventListener('DOMContentLoaded', () => { const todos = /* get To Do list data */; let listItems = ''; todos.forEach((todo) => { listItems += `<li>${todo}</li>`; }); todoList.innerHTML = listItems; });
EventTarget Interface: addEventListener()
const target = document.getElementById('id');
//Assign variable to target element.target.addEventListener('eventType', handlerFunction[, optionsOrCapture]);
//Listen on the target for the event, then execute the handler function.Terms (target, listener function, handler function) and examples (toggle show/hide)
- Target: is the object on which a DOM event happens. This can be an element in a document. When a user clicks on a button, for example, the target is that button. When the user enters text in an input field, the target is that input element. The target can also be the document itself or the window object.
- AddEventLister (i.e., the listener function) acts on the target element.
- It listens for the event in the first argument to occur.
- When the event occurs, it executes the handler function in the second argument.
Example
HTML Document - button element:
<button id="button">Click Me</button>JavaScript file:
const button = document.getElementById('button');JavaScript file: separate the handler callback function.
button.addEventListener('click', () => { console.log('Button clicked'); });
const button = document.getElementById('button'); const handleClick = () => { console.log('Button clicked'); }); button.addEventListener('click', handleClick);
Show/Hide Example
HTML Document elements:
<button id='toggle-button'>show</button>JavaScript file:
<div id="hidden-item" style="display: none">Some hidden content.</div>
const button = document.getElementById('toggle-button'); const item = document.getElementById('hidden-item');
button.addEventListener('click', () => { if (item.style.display === 'none') { button.textContent = 'hide'; item.style.display = 'block'; } else { button.textContent = 'show'; item.style.display = 'none'; } });
Event object
Ref: MDN_Web/API/Event
event argument: The first argument in the handler function is the event object by default.
event.target is the object to which the event was originally dispatched.
event.preventDefault() prevents the default behavior.
target.addEventListener('eventType', (event) => { /* handler function */ });
event argument: The first argument in the handler function is the event object by default.
event.target is the object to which the event was originally dispatched.
event.preventDefault() prevents the default behavior.
Example
HTML Document - button element for submitting a form:
<button id="btn" type="submit">Submit Form</button>JavaScript file: event target is the button element that was clicked.
const btn = document.getElementById('btn');Note: you can use any name for the event argument, such as "event", "evt", or "e".
btn.addEventListener('click', (event) => { event.preventDefault(); // prevents form from being submitted console.log(event.target === btn); // logs true });
Options: Event Propagation - Bubbling vs Capturing
When an event is triggered, there are two types of propagation:Bubbling (default): Event first triggers on the innermost target element, then successively triggers on its ancestors till it reaches the outermost DOM element or document object.
Capturing: Starts at the outermost element and propagates down.
target.addEventListener(eventType, handlerFunction, {capture: true});
Examples
HTML elements:
JavaScript: Event Bubbling (default)
JavaScript: Event Capturing (set capture option to true)
<span id="parent">
<button id="child">Click Me</button>
</span>
JavaScript: Event Bubbling (default)
parent.addEventListener('click', () => console.log('Parent'));// Logs "child" then "parent".
child.addEventListener('click', () => console.log('Child'));
JavaScript: Event Capturing (set capture option to true)
parent.addEventListener('click', () => console.log('Parent'));// Logs "parent" then "child".
child.addEventListener('click', () => console.log('Child'), { capture: true });
Options: once
If true, the listener would be automatically removed when invoked. Default is false.
target.addEventListener(eventType, handlerFunction, {once: true});
Example
const btn = document.getElementById('click');
btn.addEventListener('click', () => {
console.log('Clicked once.');
}, { once: true });
Inline Event Handlers
You can add global event handlers directly to the HTML element as an attribute.
Partial list: onclick, onload, onunload, onmouseover, onmouseout, onmousedown, onmouseup, onblur, onfucus, onchange. Full list: MDN GlobalEventHandlers
Partial list: onclick, onload, onunload, onmouseover, onmouseout, onmousedown, onmouseup, onblur, onfucus, onchange. Full list: MDN GlobalEventHandlers
<button onclick="handlerFunction">text</button>
//Inline event handler.More info and examples
- AddEventListener is generally preferred over inline handlers to keep JS code separate from the HTML markup. The same is true about inline CSS.
- However, inline event handlers are frequently used in React apps.
- The handler function can be defined directly in the attribute:
<button onclick="() => someAction">text</button>
- or it can be defined elsewhere and called by the event handler attribute:
<button onclick="funcName()">text</button>
Example - function defined in attribute:
Button that removes it's parent element. The onclick event target is the element that the attribute belongs to. Either event.target or the keyword this can be used to represent the target element.
<li> List item text. <button onclick="this.parentElement.remove()">Delete</button> </li>
Example - function called from attribute:
Alternatively, the handler function can be defined in a script that is loaded before the HTML document, then called in button element's onclick attribute:
<li> List item text. <button onclick="removeItem(event)">Delete</button> </li>JavaScript file:
const removeItem = (event) => { event.target.parentElement.remove(); }
Forms
Web Form - Submit without JavaScript
<form action="urlOrPath" method="POST"> <label for="fieldId">Field Name</label><br>
<input id="fieldId" type="text" name="fieldName"><br>
<!-- Place additional form fields here -->
<button type="submit">Save</button>
</form>
More details and example
- Traditional web forms submit the form data to the URL indicated in the form element's action attribute.
- When the form data is received by the server it either redirects the user to a different web page, or if there are errors, refreshes the form page with error data.
- Each form field must have a "name" property to identify the field name.
Example:
<form action="https://www.example.com/todos/add" method="POST"> <label for="task">Task</label><br> <input id="task" type="text" name="task"><br> <label for="due">Due Date</label><br> <input id="due" type="date" name="due"><br> <label for="details">Details</label> <textarea id="details" name="details" rows="2"></textarea> <button type="submit">Save</button> </form>
Handle form on the Front End
HTML form:
<form id="formID"> <label for="fieldId">Field Name</label><br>Handle the form in the JavaScript file:
<input id="fieldId" type="text"><br>
/* Place additional form fields here */
<button type="submit">Save</button>
</div>
const form = document.getElementById('formId');
const field1 = document.getElementById('fieldId');
form.addEventListener('submit', (event) => { event.preventDefault(); //Prevent data from being sent to the server. const data = { field1: field1.value[, field2: field2.value, ...] }; const jsonData = JSON.stringify(data); fetch('API_endpoint_URL', { method: 'POST', body: jsonData, headers: {'Content-type': 'application/json; charset=UTF-8' }, }) .then((response) => response.json()) .then((json) => /* handle response data */); field1.value = ''; //Clear the form field (or redirect). });
More details and examples
Form:
Example Form:
- Modern front-end libraries like React submit form data using AJAX, without refreshing the page.
- The form data must be grabbed on submission using JavaScript.
- Remove the action attribute since you won't be sending the data to a separate URL.
- Add an id to the form tag.
- On the form fields, add an id and leave out the name attribute.
- Set an event listener on the form and listen for the "submit" event.
- Add the event.preventDefault property at the top of the handler function to prevent the form from being submitted to a URL in the form field's action attribute.
- Grab and handle the form field values.
- Clear the form fields (by setting the values to an empty strings), or redirect to another page.
Example Form:
<form id="my-form"> <label for="task">Task</label><br> <input id="task" type="text" name="task" placeholder="Task"><br> <label for="due">Due Date</label><br> <input id="due" type="date" name="due"><br> <label for="details">Details</label> <textarea id="details" name="details" rows="2"></textarea> <button type="submit">Save</button> </div>
JavaScript file:
const form = document.getElementById('my-form');
const task = document.getElementById('task');
const due = document.getElementById('due');
const details = document.getElementById('details');
form.addEventListener('submit', (event) => { event.preventDefault(); // Handle the form data. // Put it in an object, convert it to JSON, send it to the server.
const data = { task: task.value, due: due.value, details: details.value }; const jsonData = JSON.stringify(data); fetch('http://example.com/todos/api', {method: 'POST', body: jsonData}); // Clear form fields.
task.value = '';
due.value = '';
details.value = '';
});
<textarea id="id" rows="n"></textarea>
Example
Form field:
JavaScript file:
<textarea id="details" rows="2"></textarea>
JavaScript file:
const details = document.getElementById('details');
details.value;
//Returns the text.Label: <input type="checkbox" id="id" value="value" checked>
More details and example
- Adding the checked attribute makes the checkbox checked by default. Removing the checked attribute makes the checkbox unchecked by default.
- For forms submitted in a post request, the name property indicates the proper form field. This is not required for locally handled forms.
Form field:
Status: <input type="checkbox" id="status" value="Done" checked>
JavaScript file:
const status = document.getElementById('status');
status.value;
//Returns 'Done'.<label>FieldName</label>
<select id="id">
<option>value1</option>
<option>value2</option>
</select>
More details and example
- You can add an unselectable first value. Can be blank or with text:
<option value="" style="display:none"></option>
<option value="" style="display:none">Choose One</option>
- The selected attribute will select an option as the default:
<option selected>value2</option>
- If option text differs from the value, add a value attribute.
<option value="val1">Value1</option>
Form field Example:
<label>Status</label>JavaScript file:
<select id="status"> <option value="" style="display:none">Choose One</option>
<option>Not Started</option>
<option>In Progress</option>
<option>Done</option>
</select>
const status = document.getElementById('status');
status.value;
//Returns the selected option value.Select box - populate dynamically:
<label>FieldName</label>JavaScript file:
<select id="fieldName"></select>
const fieldName = document.getElementById('fieldName'); document.addEventListener('DOMContentLoaded', () => { const data = /* Fetch data */; let options = ''; data.forEach((item) => { options += `<option>${item}</option>`; }); fieldName.innerHTML = options; });
More details and example
- You may want to populate select form field options from a database.
- In that case, you can add an event listener for when the DOM content is loaded. DOMContentLoaded fires when the HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
- Pull the values, then loop through them adding them to an options string.
- Chain the innerHTML property to the select element and set it to the options HTML string.
Example form field:
<label>Category</label>JavaScript file:
<select id="category"></select>
const categoryField = document.getElementById('category'); document.addEventListener('DOMContentLoaded', () => { const categories = ['tech', 'medical', 'finance', 'entertainment']; let options = ''; categories.forEach((category) => { options += `<option>${category}</option>`; }); categoryField.innerHTML = options; });
Form Field values - get, set, and clear
elem.value;
//Gets the value from a form field element.elem.value = 'Some value';
//Sets the value of a form field element.elem.value = '';
//Clears the value of a form field element. More details and examples
- If you are using JavaScript to submit the form data to the server then you need to get the value property from the form fields.
- If it is an edit form, you need to populate the form with the existing values.
- After the form is submitted you need to clear the form field values.
Example HTML document:
<input id="title" type="text">
//HTML element in the HTML document.JavaScript file:
const title = document.getElementById('title');
//Assign the form field element to a variable.title.value
//Gets the form field value.title.value = 'Title';
// Sets the form field value.title.value = '';
// Clears the form field value.JSON
Overview
- JSON (JavaScript object notation) is used to store and transmit data as text in a format closely resembling JS objects and arrays (but it is not actually JS).
- Most APIs transmit data over the internet using JSON syntax. NoSQL databases like MongoDB and Firebase's Firestore use JSON syntax.
- The file name extension for JSON files is ".json"
- The MIME type for JSON text is "application/json"
JSON Syntax (differences from JavaScript)
- Only double quotes are allowed.
- Property names must be in quotes.
- Trailing commas at the end of arrays or object properties are not allowed.
{
"name": "Joey R",
"age": 29,
"active": true,
"articles": ["Learn Javascript", "Learn NodeJS", "Learn React"],
"address": { "street": "123 Main St", "city": "New York", "state": "NY", "zip": "20001" }
}
[
{ "id": 5362, "title": "Learn JavaScript", "author": "Joey R.", "content": "Lorem Ipsum"},
{ "id": 5363, "title": "Learn NodeJS", "author": "Joey R.", "content": "Lorem Ipsum"},
{ "id": 5364, "title": "Learn React", "author": "Joey R.", "content": "Lorem Ipsum"}
]
JSON global object
- Ref: MDN Global_Objects/JSON
- JSON is a JavaScript standard built-in object in the global scope.
- It can't be called or constructed. It contains only two methods. JSON.stringify() to convert JS into a JSON string, and JSON.parse() to convert a JSON string into JS.
More info
JSON is not a constructor function:
typeof JSON; // returns 'object'JSON only has two methods and no properties:
Object.getOwnPropertyNames(JSON); // returns parse, stringify
JSON.stringify(JS);
//Converts JS into a JSON string. More details
JSON data types:
- The following data types will stringify as JSON: string, number, object (containing valid JSON values), array, boolean, null.
- null, NaN, Infinity will stringify as null.
- JSON values cannot be: Function, Date, Symbol, Set, Error, Regular Expression, Promise, and undefined.
- If you attempt to stringify undefined, a function, or a Symbol in an object it will be omitted, in an array it will be converted to null.
JSON.stringify('Joey'); // '"Joey"'
JSON.stringify(29); // '29'
JSON.stringify(true); // 'true'
JSON.stringify([1, 'false', false]); // '[1,"false",false]'
JSON.stringify([NaN, null, Infinity]); // '[null,null,null]'
JSON.stringify({}); // '{}'
JSON.stringify({ x: 5, y: 6 }); // '{"x":5,"y":6}'
JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] }); // '{"x":[10,null,null,null]}'
const userObj = { name: "Joey", age: 29, city: "New York" };
const userJSON = JSON.stringify(userObj);
userJSON; // "{"name":"Joey","age":29,"city":"New York"}"
<pre>{JSON.stringify(ObjectOrArray, null, 2)}</pre>
Example
<pre>{JSON.stringify({id: 1, username: "Joey"}, null, 2)}</pre>
Displays as:
{ "id": 1, "username": "Joey" }
JSON.parse('jsonString');
//Converts a JSON string into JS. Example
const user = JSON.parse('{ "name": "Joey", "age": 29, "active": true }'); user; // returns {name: 'Joey', age: 29, active: true}
Use either a JavaScript timestamp number or a date string:
JSON.stringify({birthDate: '1996-05-19'});
// '{"birthDate":"1996-05-19"}'More details
- Like JS, JSON does not have a data type for date.
- Date objects are converted to JSON strings:
JSON.stringify({birthDate: new Date('May 19, 1996')});
// '{"birthDate":"1996-05-19T07:00:00.000Z"}'
Import JSON file data into JavaScript.
JS file must be module type.import data from './filename.json' assert {type: 'json'};
//data is imported and converted to JS. Example
ToDo list application imports todos from a JSON file:
Web App:
In the HTML file, when importing the JavaScript file, set type to "module"
Node App:
In the package.json file, set type to "module"
Web App:
In the HTML file, when importing the JavaScript file, set type to "module"
<script type="module" src="todos.js"></script>In the JS module file todos.js, import the JSON data from the file. Set type to 'json':
import todos from './todos.json' assert {type: 'json'}; ... todos[0].task; // returns "Learn JSON"The todos.json file contains only JSON data:
[{ "task": "Learn JSON" }]
Node App:
In the package.json file, set type to "module"
{ "type": "module", ... }In the JS module file todos.js, import the JSON data from the file. Set type to 'json':
import todos from './todos.json' assert {type: 'json'}; ... todos[0].task; // returns "Learn JSON"The todos.json file contains only JSON data:
[{ "task": "Learn JSON" }]
Error
- Ref: MDN Guide/Control_flow_and_error_handling | MDN Global_Objects/Error
- Errors are violations of the language rules detected by the JS engine at runtime.
- Error objects are created and thrown when runtime errors occur.
- The Error object can also be used as a base object for user-defined exceptions.
Handle Errors
Try...Catch statement
- If the try block contains errors or throws user-defined exceptions, handle them in the catch block.
try {
/* statements to execute that may throw errors/exceptions */
}
catch (err) { // parameter can be any name.
/* statements to handle any errors/exceptions */
}
Example
function checkNum(num) {
if (!Number.isFinite(num) || num < 1 || num > 10) {
throw `${num} IS NOT a finite number between 1 and 10.`;
} return 'ok';
} try { let num = -10; checkNum(num); console.log(`${num} is a finite number between 1 and 10.`); } catch (exception) { console.log(exception); }
} finally {
/* Block of code to run after try/catch completes */
}
Example
openMyFile();
try {
writeMyFile(data); // This may throw an error
} catch(err) {
handleError(err); // If an error occurred, handle it
} finally {
closeMyFile(); // Always close the resource
}
Error instance properties and methods
console.error(err);
Logs a string with the error name, message and stack. err.name
Error type name: e.g., Error, InternalError, RangeError, etc.err.message
Error message.err.toString()
Returns`${err.name}: ${err.message}`
err.stack
Stack trace starting with the file:line:column where error occurred. This property is non-standard.
Example
function checkNum(num) { if (!Number.isFinite(num)) { throw new TypeError('Argument must be a number.'); } if(num < 1 || num > 10) { throw new RangeError('Number Must be between 1 and 10.'); } return 'ok'; } try { let num = -10; checkNum(num); console.log(`${num} is a finite number between 1 and 10.`); } catch (err) { console.log(`Ooops, the below error occurred:\n${err.stack}`); }
Error global objects
- Ref: MDN Global_Objects/Error
- JS has a standard built in object on the global scope named Error.
- Plus several constructors for specific error types (listed below) that inherit from Error.
- At runtime the JS engine parses the code, converts it to machine code, and executes it. It checks for errors while parsing. If one is detected it instantiates an error object from the appropriate constructor and throws it.
More info
Error global object
- Error is a JavaScript standard built-in object. It is a global object since it is attached to the global object (window in the browser or global in Node.js):
Error === window.Error; // returns true in the browser environment Error === global.Error; // returns true in the Node.js environment
- Error is a constructor function (functions are a type of object).
typeof Error; // returns 'function'
- When called with the new keyword, it instantiates an Error object.
const err = new Error(); // instantiates a new Error object
typeof err; // returns 'object'
Error static properties and methods:
- Error static properties and methods are called on the Error object (e.g., Error.length)
Object.getOwnPropertyNames(Error); // returns length, name, prototype, captureStackTrace, stackTraceLimit
Error Instance properties and methods:
- There are no error literals, only error objects.
- The prototype of an error object is Error.prototype:
Object.getPrototypeOf(new Error() === Error.prototype); // returns true
- Error.prototype contains properties and methods that can be called on an Error instance object. They are listed below:
Object.getOwnPropertyNames(Error.prototype); // Returns: constructor, name, message, toString. // There is also a non-standard property called stack.
- constructor is a reference to the Error() constructor function.
SyntaxError
SyntaxError object thrown when trying to interpret syntactically invalid code.
Examples
lett y = 9; Uncaught SyntaxError: Unexpected identifier
function { x + 2; } Uncaught SyntaxError: Unexpected token '{'
ReferenceError
ReferenceError object thrown when a non-existent variable is referenced.
Examples
let x = 3;
x + y; Uncaught ReferenceError: y is not defined at file:line
y(); Uncaught ReferenceError: y is not defined at file:line
y; Uncaught ReferenceError: y is not defined at file:line
TypeError
TypeError object thrown when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type.
Examples
const x = 7;
x = 9; Uncaught TypeError: Assignment to constant variable at file:line
x(); Uncaught TypeError: x is not a function at file:line
RangeError
RangeError object thrown when a value is not in the set or range of allowed values.
Example
Infinite recursive function:
function addOne(num) {
addOne(++num);
}
addOne(0);
Uncaught RangeError: Maximum call stack size exceeded filename:line
User-defined Exceptions
- Errors are clear violations of language rules. Exceptions are violations of conditions.
- E.g., A statement accessing the data returned by a fetch API request is valid JS.
- But executing it before the data is returned causes an exception.
- Your code should anticipate exceptions and handle them if they occur.
- You can handle an exception in the normal flow of your code
if (undesired condition) { /* code to deal with it */ }
- Or throw the exception.
Throw statement
- The throw statement throws (generates) a user-defined exception.
- Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack.
- If no catch block exists among caller functions, the program will terminate.
Throw an exception with a string message.
if (undesired condition) { throw 'Error message'; }
Example
Check that the argument is a finite number. Throw exception with message if not.
function checkNum(num) { if (!Number.isFinite(num)) { throw 'Argument must be a finite number.'; } return 'ok'; } checkNum(10); // Returns "ok" checkNum(Infinity); // Uncaught Argument must be a finite number.
Throws exception with text message: "Argument must be a finite number."
Throw a built-in error object
You can throw an error object using one of the standard error types.if (undesired condition) { throw new RangeError('Error message'); }
Example
Check the argument only contains a number between 1 and 10. Throw specific type errors.
function checkNum(num) {
if (!Number.isFinite(num)) {
throw new TypeError("Argument must be a number.");
}
if(num < 1 || num > 10) {
throw new RangeError("Number Must be between 1 and 10.");
}
return 'ok'; } checkNum(10); // Returns "ok" checkNum(100); // Uncaught RangeError: Number Must be between 1 and 10. checkNum(NaN); // Uncaught TypeError: Argument must be a number.
Throw Error Object
JS also has a generic Error constructor for user-defined exceptions.
if (undesired condition) { throw new Error('Error message'); }
Example
Check if argument is a finite number between 1 and 10.
function checkNum(num) { if (!Number.isFinite(num) || num < 1 || num > 10) { throw new Error('Argument must be a number between 1 and 10.'); } return 'ok'; } checkNum(10); // Returns "ok" checkNum(100); // Uncaught Error: Argument must be a number between 1 and 10. checkNum(NaN); // Uncaught Error: Argument must be a number between 1 and 10.