Objects
Basic Usage
const myObject = {
name: 'Mark',
favoriteManufacturer: 'Porsche'
}
myObject.hasOwnProperty('favoriteManufacturer'); // true
Object.keys(myObject); // ['name', 'favoriteManufacturer']
Object.values(myObject); // ['Mark', 'Porsche']
Object.entries(myObject); // [ ['name', 'Mark'], ['favoriteManufacturer', 'Porsche'] ]
Object.assign(myObject, { favoriteModel: 'F40' }); // {name: 'Mark', favoriteManufacturer: 'Porsche', favoriteModel: 'F40'}
Object.freeze(myObject); // top level object properties cannot be changed now
Object.isFrozen(myObject); // true
Destructuring
const { name, favoriteManufacturer } = myObject;
Manipulation
delete myObject.age;
console.log(myObject); // { name: 'Mark' }
Merging
const objectA = { manufacturer: 'Toyota' };
const objectB = { model: 'Supra' };
const finalCar = { ...objectA, ...objectB }; // { manufacturer: 'Toyota', model: 'Supra' }
const finalCar = Object.assign({}, objectA, objectB); // { manufacturer: 'Toyota', model: 'Supra' }
Functions
Arrow Functions
Note: cannot be used as constructors
const myFunction1 = (a, b) => a + b;
const myFunction2 = a => a * 10; // parens not needed when 1 param
const myFunction3 = () => {}; // no params
Promises
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 500, 'one');
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'two');
});
// run 1
promise1.then((value) => console.log(value)); // 'one'
// run all
Promise.all([promise1, promise2]).then((result) => {
console.log(result);
}).catch((error) => {
console.log('Error', error);
});
// race (return firstly resolved or rejected)
Promise.race([promise1, promise2]).then((value) => {
console.log(value); // 'two' will resolve faster since it is only 100 vs 500
});
Call/Apply/Bind (Call=Comma, Apply=Array)
Call invokes function with a given value and arguments comma separated.
const person1 = { firstName: 'Dom' };
const person2 = { firstName: 'Brian' };
function invite(greeting) {
const greetingText = greeting + ", " + this.firstName + " " + this.lastName;
console.log(greetingText)
}
invite.call(person1, 'Dude I almost had you'); // Dude I almost had you, Dom
invite.call(person2, 'You owe me a 10 second car'); // You owe me a 10 second car, Brian
Apply invokes with value and allows arguments via array.
const person1 = { firstName: 'Dom' };
const person2 = { firstName: 'Brian' };
function invite(greeting) {
const greetingText = greeting + ", " + this.firstName + " " + this.lastName;
console.log(greetingText)
}
invite.apply(person1, ['Dude I almost had you']); // Dude I almost had you, Dom
invite.apply(person2, ['You owe me a 10 second car']); // You owe me a 10 second car, Brian
Bind returns new function allowing arguments to be passed through that
const person1 = { firstName: 'Dom' };
const person2 = { firstName: 'Brian' };
function invite(greeting) {
const greetingText = greeting + ", " + this.firstName + " " + this.lastName;
console.log(greetingText)
}
const talkToDom = invite.bind(person1);
const talkToBrian = invite.bind(person2);
talkToDom('Dude I almost had you'); // Dude I almost had you, Dom
talkToBrian('You owe me a 10 second car'); // You owe me a 10 second car, Brian
Callbacks
function callbackFn(name) {
console.log('Hello' + name);
}
function outerFn(callback) {
const name = prompt('Please enter your name.');
}
outerFn(callbackFn);
Arrays
Common Methods
const brandsArray = ['Mercedes', 'Audi', 'BMW', 'Porsche'];
const numbersArray = [1, 2, 3, 4, 5];
const objectsArray = [
{exterior: 'Nardo Gray', interior: 'Oyster' },
{exterior: 'Nogaro Blue', interior: 'Black/Blue'},
{exterior: 'Meteor Gray', interior: 'Stone Gray'}
];
numbersArray.at(2); // 3, gets item at index 2
brandsArray.concat('Toyota'); // ['Mercedes', 'Audi', 'BMW', 'Porsche', 'Toyota']
numbersArray.every((element) => element < 6); // true, every element is less than 6
brandsArray.filter((brand) => brand === 'BMW'); // 'BMW'
numbersArray.findIndex((element) => element > 3); // 3, returns first index matching condition
numbersArray.find((element) => element > 3); // 4, returns first value matching condition
numbersArray.includes(3); // true
brandsArray.join(', '); // 'Mercedes, Audi, BMW, Porsche'
numbersArray.map((element) => element * 10); // [10, 20, 30, 40, 50]
numbersArray.pop(); // 5, returns removed element, modifying original array to [1,2,3,4]
numbersArray.push(6); // 6, returns the element added, modifying the original array
numbersArray.some((element) => element % 2 !== 0); // true (at least 1 odd element exists)
numbersArray.toString(); // '1,2,3,4,5'
Instance Methods
Array.from('Porsche'); // ['P', 'o', 'r', 's', 'c', 'h', 'e']
Array.isArray(numbersArray); // true
Sorting
Note: sort() and reverse() mutate the original array. Best practice is using spread ([...myArr]) to make a copy first.
const unsortedNumbersArray = [1,3,5,2,4];
brandsArray.sort(); // ['Audi', 'BMW', 'Mercedes', 'Porsche'], strings default sort is ABC order
unsortedNumbersArray.sort((a, b) => a - b); // [1,2,3,4,5]
unsortedNumbersArray.sort((a, b) => b - a); // [5,4,3,2,1]
unsortedNumbersArray.reverse(); // back to [1,2,3,4,5]
Slice/Splice
Slice returns selected elements in an array as a new array. Selects using start and optional end argument (without including last element). Negative index counts back from end of array. Avoid using array.splice() as it mutates the original array.
const numbersArray = [1, 2, 3, 4, 5];
const arr1 = numbersArray.slice(0,2); // returns [1,2]
const arr2 = numbersArray.slice(2,3); // returns [3]
const arr3 = numbersArray.slice(4); // returns [5]
const arr4 = numbersArray.slice(-3, -1); // returns [3,4]
Loops
for (let value of numbersArray) {
value++;
console.log(value); // 2, 3, 4, 5, 6
}
for (let key in numbersArray) {
console.log(key); // 0, 1, 2, 3, 4
}
numbersArray.forEach((item) => {
console.log(item); // 1, 2, 5, 3, 4
})
Values & Variables
==/===
Understanding value equality with and without coercion.
0 == false; // true
0 === false; // false
1 == '1'; // true
1 === '1'; // false
null == undefined; // true
null === undefined; // false
'0' == false; // true
'0' === false; // false
NaN == NaN || NaN === NaN; // false, NaN is not equal to anything, even itself
[] == [] || [] === []; // false, different object in memory, same as object
let/var/const
var is hoisted and initialized, whereas let is hoisted but not initialized.
let counter = 30;
if (counter === 30) {
let counter = 31;
console.log(counter); // 31
}
console.log(counter); // 30
enum
enum Color {
RED, GREEN, BLUE
}
Utilities
Spread Operator
const myArr = [1, 2, 3];
const myObj = {name: 'Mark', car: '911 Turbo'};
const allNumbers = [...myArr, 4, 5]; // [1, 2, 3, 4, 5]
const myProfile = {...myObj, theme: 'dark'} // {name: 'Mark', car: '911 Turbo', theme: 'dark'}
setTimeout
const myTimeout = setTimeout(() => {
console.log('Hi after 2 seconds');
}, 2000);
const stopTimeout = () => {
clearTimeout(myTimeout);
}
setInterval
const myInterval = setInterval(() => {
console.log('Hi every 2 seconds');
}, 2000);
const stopInterval = () => {
clearInterval(myInterval);
}
Cookies/Local Storage/Session Storage
Cookies are available both server and client-side, whereas local and session storage are client-side only.
document.cookie = 'username=Mark; expires=Mon, 10 Apr 2025 12:00:00 UTC';
document.cookie = 'username=Mark; path=/cards';
localStorage.setItem('username', 'Mark');
localStorage.getItem('username');
localStorage.removeItem('username');
sessionStorage.setItem('username', 'Mark');
sessionStorage.getItem('username');
sessionStorage.removeItem('username');
Eval
This method is not recommended and likely never used. One use-case would be to evaluate functions defined in JSON.
console.log(eval("1 + 2")); // 3
Document
document.getElementById('title').style.fontSize = '20px';
document.getElementById('title').className = 'custom-title';
Navigator
navigator.language; // 'en-US'
navigator.userAgent; // 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) ... '
navigator.userAgent.match(/Android/i); // Android
navigator.userAgent.match(/webOS/i); // webkit
navigator.userAgent.match(/iPhone/i); // iPhone
navigator.userAgent.match(/iPad/i); // iPad
Window
window.location.href; // returns full URL
window.history.back(); // browser back button
window.history.forward(); // browser forward button
window.history.pushState('page2', 'Title', '/page-2'); // add history entry
window.print(); // print page
URLSearchParams
const carSearchParams = "make=Porsche&model=911";
const urlParams = new URLSearchParams(carSearchParams);
urlParams.append('color', 'blue'); // "make=Porsche&model=911&color=blue"
urlParams.delete('make'); // "model=911&color=blue"
urlParams.delete('make', 'Porsche'); // "model=911&color=blue"
urlParams.get('make'); // 'Porsche'
urlParams.has('make'); // true
urlParams.has('make', 'Audi'); // false
urlParams.set('color', 'black'); // "make=Porsche&model=911&color=black"
urlParams.size; // 2
urlParams.toString(); // 'make=Porsche&model=911'
Date
const today = new Date();
try/catch
try {
console.log('try');
} catch (err) {
console.log(err.name, err.message);
}
typeof
const myValue = 'Hello';
typeof myValue; // 'string'
typeof myValue === 'string'; // true
typeof myValue === 'number'; // false
typeof myValue === 'boolean'; // false
typeof myValue === 'function'; // false
Strings
Basic Usage
const myString = 'You never had me. You never had your car!';
const myStringWithSpaces = 'The buster brought ME back! ';
myString.charAt(0); // 'Y'
myString.concat(' You almost had ME?'); // 'You never had me. You never had your car! You almost had ME?'
myString.includes('car'); // true
myString.includes('Car'); // false, case-sensitive
myString.length; // 41
myStringWithSpaces.length; // 30, Spaces are counted, trim first
myString.replace('car', 'goat'); // 'You never had me. You never had your goat!'
myString.search('car'); // 37, returns the position of the match
myString.split(' '); // ['You', 'never', 'had', 'me.', 'You', 'never', 'had', 'your', 'car!']
myString.startsWith('You'); // true
myString.startsWith('you'); // false, case-sensitive
myString.substr(0, 9); // 'You never'
myString.toLowerCase(); // 'you never had me. you never had your car!'
myString.toUpperCase(); // 'YOU NEVER HAD ME. YOU NEVER HAD YOUR CAR!'
myStringWithSpaces.trim(); // 'The buster brought ME back!'
Regex
The match pattern should be enclosed between slashes /.../. Can be used with test(), exec(), match(), matchAll(), search(), replace(), replaceAll(), and split()
myString.match(/you/); // ['you', index: 32, input: 'You never had me. You never had your car!', groups: undefined]
myString.match(/You/g); // ['You', 'You'], 'g' searches globally
myString.match(/[Yy]ou/g); // ['You', 'You', 'you']
myString.match(/You|your/g); // ['You', 'You', 'your']
myString.match(/Yy?our/g); // ['You', 'You', 'your'], cleaner way to do the above line
myString.replace(/You/g, 'Me'); // 'Me never had me. Me never had your car!'
myString.search(/you/); // 32, returns position in string
myString.split(/[aeiou]/).join(''); // 'Y nvr hd m. Y nvr hd yr cr!'
Numbers
Math Operations
const myNumber = 1.23;
const myNumberArray = [1, 3, 2];
Math.ceil(myNumber); // 2
Math.floor(myNumber); // 1
Math.floor(Math.random() * 10) + 1; // returns random integer from 1-10
Math.max(myNumberArray); // 3
Math.min(myNumberArray); // 1
Sets
Common Methods
Set values are unique.
[...new Set([1, 2, 4, 4, 3])]; // [1, 2, 4, 3]
Glossary
A glossary of terms.
| Term | Definition |
|---|---|
| Babel | JavaScript/TypeScript transpiler to convert ES2015+ code into backwards compatible versions |
| Closure | Functions that retain access to variables from their containing scope even after parent execution |
| Cookie | Small strings of data stored directly on the client |
| DOM (Document) | Owner of all other objects on web page, child of window |
| ES6/ES2015 | Adds arrow functions, rest/spread, promises, classes, modules, etc to JavaScript |
| Hoisting | Variables, functions, classes, and imports are moved to the top of their scope before execution |
| JAM Stack | Javascript API's and Markup defines the modern approach using static site generation for full-stack frontend development |
| JSON | JavaScript Object Notation used for data interchanging |
| Local Storage | Stores data for current origin with no expiration date |
| MEAN/MERN Stack | Full-stack development using MongoDB, Express, Angular/React, and NodeJS |
| Module | Small units of independent, reusable code typically exporting an object, function, or constructor |
| NodeJS | An asynchronous event-driven JavaScript runtime |
| RxJS | Reactive Extensions for JavaScript is a library for implementing observables for callback-based code |
| Scope | The current context of your code in regards to access of functions and variables |
| Server-sent Events | Browser receives automatic updates from a server via HTTP connection without resorting to polling |
| Session Storage | Stores data until browser tab is closed |
| TypeScript | Typed superset of JavaScript created by Microsoft that adds optional typing, classes, async/await, etc. and compiles to JavaScript |
| Window | Represents window containing the DOM (document) |