JavaScript

date
Aug 10, 2022
type
KnowledgeBase
year
slug
javascript
status
Published
tags
JavaScript
summary
The essence of everything you need to know about JavaScript (and TypeScript)
TypeScript
TypeScript

Variables

It’s all dynamically typed!
let - variable values const - constant values var - don’t use this anymore, use let instead
👉
If you want to use static typing, look at TypeScript

Functions

can also be stored in a variable:
could be written as an arrow function:
When it has no arguments, use empty braces
Return a value
If an arrow function does nothing but returns a value, it can be shortened to:

Async Functions

Strings ⌨️

Template strings (use backtick `) - allow you to use variables inside ${}

Equality

Strict equality

Loops and iteration ⚙️

for
for .. in, for .. of
Also note that Array has a forEach()!
while
do while
break, continue

Modules 📦

To access functionality in another file you need to export it from File A and import it into File B

Objects

ℹ️
An object is a collection of properties (a property is an association between a name/key and a value - value can be a function!)
But usually you’d write this as an object initializer:
Unassigned properties of an object are undefined (and not null)
An Object’s properties can contain other Objects, as well as functions:
Properties can be identifiers, numbers or strings:
Properties can be accessed in different ways:
You can also create objects through a constructor function
All objects inherit from at least one other object. The object being inherited from is known as the prototype.
 
📘
If you want to learn a lot more about the weirdness of prototypes → read The Joy of JavaScript
You can add properties to previously defined object types through the prototype property.
Object.create() can be useful because it allows you to choose the prototype object for the object you create.

Duplicating Objects

Classes

ℹ️
First and foremost: You don’t really need classes in JS. You can do everything and more with Objects and prototypes.
🤔
Did you know? Classes were introduced to distract you from the craziness that’s going on under the hood (objects + prototypes).
old syntax:
New syntax for defining class properties:
Add functions:
or like this (arrow function has the advantage of the this keyword not changing its reference)
Inheritance
Private fields and methods: #

Spread and Rest Operator

3 dots:
The spread operator allows you to pull elements out of an array (to split the array into a list of its elements.
Spread operator used on an object:
The rest operator allows us to create variadic functions and place any number of arguments into an array (can be used like params int[] args in C#):

Destructuring

Allows easy access to values of arrays or objects and assigning them to variables.
Destructuring is very useful when working with function arguments:
Watch how we can change this:
into this:
we can even add defaults:

True and False

ℹ️
Truthy values translate to true when evaluated as a Boolean. A value is truthy if it’s not falsy. (Yep, that is the official definition)
There are only six falsy values:
  • false
  • 0
  • “” (empty string)
  • null
  • Undefined
  • NaN (not a number)

Promises 🙏

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
Promise is in one of these states:
  • pending: initial state, neither fulfilled nor rejected.
  • fulfilled: meaning that the operation was completed successfully.
  • rejected: meaning that the operation failed.
A promise is said to be settled if it is either fulfilled or rejected, but not pending.

Guarantees

Unlike old-fashioned passed-in callbacks, a promise comes with some guarantees:
  • These callbacks will be invoked even if they were added after the success or failure of the asynchronous operation that the promise represents.
  • Multiple callbacks may be added by calling then() several times. They will be invoked one after another, in the order in which they were inserted.

Chaining

Execute two or more asynchronous operations back to back, where each subsequent operation starts when the previous operation succeeds.
same thing with arrow functions:
To track fallback error handling for promises (or help debug issues with promise management):

Static methods

Promise.all(iterable) - wait for all promises to be fulfilled or for any to be rejected Promise.allSettled(iterable) - wait until all promises have settled (each may fulfill or reject) Promise.any(iterable) - returns as soon as one of them fulfills Promise.race(iterable) - wait until any of the promises is fulfilled or rejected Promise.reject(reason) - returns a new Promise object that is rejected with the given reason Promise.resolve(value) - returns a new Promise object that is resolved with the given value.

Arrays

Arrays are resizable and can contain a mix of different data types.

Create ➕

Array(1, 2, 3) creates a new Array containing [1, 2, 3] Array.from('foo') creates a new Array from an array-like object or iterable object. [”f”, “o”, “o”] Array.of(7) creates a new Array instance with a given number of empty slots const arr = arr1.concat(arr2); - merge 2 or more arrays into a new array entries() returns a new Array Iterator object that contains key/value pairs for each index in the array - link

Stats 📊

Array.isArray(arr) returns true if it’s an array arr.lenth - number of elements in an array

Add and Remove ✂️

pop() - removes the last element and returns it push() - adds one or more elements to the end, returns the new length of the array shift() - remove the first element and return it unshift() - add one or more elements to the beginning of an array and return the new length of the array arr.fill(0, 2, 4) - fill arr with the value 0 from position 2 until position 4. [1, 2, 3, 4] → [1, 2, 0, 0] splice(start, deleteCount, item1, item2, itemN) - changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

Find, Filter and Sort 🔍

arr.at(2) - gives us the 3rd item in the list, same as arr[2], but here negative values count from the rear forward, so arr.at(-1) gives us the last item in the list (same as arr[arr.length - 1]) arr.every((el) => { el < 40 }) tests whether all elements in the array pass a test implemented by a provided function. arr.filter((el) => { el.length > 6 }) - returns a shallow copy of the array with only the elements that pass the test implemented by the provided function arr.find((el) => el.length > 6) - returns the first element that satisfies the provided testing function arr.findLast() - same as above, but from the back arr.findIndex() and arr.findLastIndex - same as above, but only returns the index. returns -1 if nothing was found. arr.forEach(el => console.log(el)) - execute provided function once for each array element pets.includes('cat') - whether an array includes a certain value arr.indexOf('blah') - returns the first index at which a given element can be found arr.lastIndexOf('blah') - same as above, but from the rear some() - returns true if at least one element in the calling array satisfies the provided testing function sort() - sorts in place according to UTF-16 values ['Monkey', 'Cat', 'Dog'].sort()['Cat', 'Dog', 'Monkey'] - you can also supply a compare Function: sort(function compareFn(a, b) { /* ... */ }) reverse() - reverse the order of the elements

Convert and Process 🔨

map() - creates a new array populated with the results of calling a provided function on every element in the calling array [1, 4, 9, 16].map(x => x * 2) → [2, 8, 18, 32] [0, 1, 2, [3, 4]].flat() - creates a new array with all sub-array elements concatenated into it recursively. → [0, 1, 2, 3, 4] flatMap() - identical to a map() followed by a flat() of depth 1, but slightly more efficient reduce() - executes a user-supplied reducer callback function on each element, passing in the return value from the preceding call. [1, 2, 3, 4].reduce((prev, curr) => prev + curr, 0)10 reduceRight() - same as above, but from the rear arr.copyWithin(target, start, end) - copies part of an array to another location in that same array and returns it values() - returns a new array iterator object that iterates the value of each index in the array slice() - extract a section of the array and return it as a new array ['Fire', 'Air', 'Water'].join('-') - returns a new string by concatenating all elements, separated by commas (default) or a specified separator string. → “Fire-Air-Water”

Leave a comment