Javascript Cheatsheet. This is a Javascript Cheatsheet on…
By: Jeff Yeung
Tags: Notes, JavaScript, Learning, Coding, Cheatsheet

Photo by Jaycee Xie on Unsplash

This is a Javascript Cheatsheet on Javascript language, programming paradigms, tips&tricks, etc.

Table-of-Contents

Academind Tricky Pasts

Datatypes Hoisting Immutable Primitive & Reference values Callbacks Promises this Prototypes Fallback object

1. What is Javascript

Javascript is an interpreted language so it is interpreted line-by-line at run-time. Many browsers nowadays have Just-In-Time (JIT) compiliation which compiles Javascript into executable bytecode. This contrasts to compiled language such as C++, Java and Rust which must be compiled to machine code first before it’s run.

2. Client-side vs Server-side

Javascript is a high-level programming language that focuses on running client-side code on the web browser. Client-side means that the code runs through the browser on the client or user’s device when they open the website or such. This contrast to server-side which means that the action takes place on the web server instead of a user’s computer.

Javascript can do the following on the client-side such as.

Render — Change the display or view on the browser Post — Send data to a server Get— Fetch more data from the server

However, with the advent of NodeJS, JS can be written on the server-side which means that it can now

Write to APIs Talk to Databases Talk to Servers

2.1. Javascript Engine

Parser Abstract Syntax Tree (AST) Intepreter Profiler Compiler Optimized Code

Sources:

2.2. Chrome V8 Engine

V8 introduced Ignition, new interpreter, that compiles Javascript functions to a short bytecode. The byecode is then excuted by a high-performance interpreter which produces execution speeds similar to v8 baseline compiler.

Interpreter reads the code line-by-line and then translates it on the fly into machine code. Compiler on the other compiles the code into machine code ahead of time.

2.2.3. Just-In-Time Compilation

There’s a new part of the Javascript engine called a monitor/profiler. The profiler watches the code as it runs and records the times it runs and the types used. When a function starts getting warm (gets called often), the JIT sends it off to be compiled.

There’s two steps to compilation

Baseline compiler Optimizing

Sources:

3. Front-End Frameworks

Front-end frameworks such as React, Angular and Vue enable client-side code to be easier and maintainable. There are strengths and caveats to each of the frameworks depending on use cases, project complexity and size etc.

Edit 1: I am using React right now. There’s quite a learning curve but worthwhile as React is very powerful and useful.

4. Javascript Data Types

Javascript is a loosely typed or dynamic language. This means that variables are not directly declared it’s typing compared to staticly typed languages such as C++. However, Typescript address this issues.

Data Types are split into two categories: Primitives or single celled data types and Objects or a group of data.

Note: Primitives are immmutable so variables can only be reassigned data.

4.1. Primitives

Boolean — true or false / 1 or 0 Null — user-assigned data type that says data has no value Undefined — no datatype has been assigned to the variable or data is empty Number — JS has number type as float data-types. This includes +/- infinity and NaN. BigInt can represent intergers beyond the safe integer limit for Nubmers with arbitrary preision. String — sequence of characters with indices Symbol — unique and immutable primitive type and can be used as a key for an Object

4.2. Objects

Objects include Arrays and Objects or commonly known as Hash Tables. Arrays are instatiated using [] and Objects are declared using {}. Each array value has an index and a value. Each object has a key and a value.

ES6+ Declarations of Variables

Declare your variables with either const or let. Var can cause variables to leek out of it’s block scope into outer scope. This can cause unpredictable and undesirable behavior.

Declaring Variables

4.3 Array Methods

Javascript has a couple array methods that can alter the elements of an array.

pop() - Remove the last element of an array push() - Add an item to the end of the array shift() - Remove the first element of an array unshift() - Add an item to the beginning of an array

4.4 String Methods

4.5 Objects Methods

4.6 Type Coercion

Javascript variables can be converted into a different type through different ways

Explicity ( '1234'.toString() ) Or, implicitly ( 42 + '' //returns "42" )

String conversion

String Conversion Method

Number conversion

Number Conversion Method

Boolean Conversion

Boolean Conversion Method

4.7 Strict Mode

Javascript Strict Mode is a restricted variant of Javascript where

Catches common coding errors, throwing exception Prevents “unsafe errors” such as gaining access to the global object (throws exception) Disables confusing or poor thought-out features

Notable Features:

Disallows global variables (catches missing var declarations or typos) Silent failing assignments throw errors (assigning NaN = 5; ) Throws exception when attempting to delete undeletable properties ( delete Object.prototype )

Sources:

5. Functions

5.2. Scope vs Context

Scope refers to the visibility of the variables while context refers to the object to which a function belongs.1

Scope

Scope pertains to the variable access of a function when it is invoked and is unique to each invocation.

Var is function scoped and let is block scoped which is denoted by the enclosing block {} .

Context

Is always the value of this keyword which is a reference to the object that "owns" the currently executing code. Using this keyword refers to the object that the function is executing in.

Understanding this context

Window Scope

If you declare a and b on your browser then you will see the a and b in your window

Global Scope

variables declared in the global scope can be accessed anywhere in the file global to the file or global relative to some block of code (block scope)

Local Scope

Local scope means it can be accessed only in a certain block of code

There are three types of scopes in ES6.

Global scope — Variables declared in the global scope can be accessed by all functions. Local Scope/Function Scope — Variables declared can only be accessed within the function itself. Block scope(ES6) — Variables declared can only be accessed within the block {} scope.

Sources:

5.1.3. Closures

Closures are when a nested or inner function declared inside an outer function has access to the outer functions variables. To expose a function, return it or pass it to another function to use the closure.

Closures Example

Simply put if you are inside your room in a house, this means you have access to all the other rooms in your house. Whether you go or use them is your choice.

Basically, all functions are closures because they have access to outer functions or the global object.

Arrow functions

Arrow functions make writing functions compact and removes issues with the this keyword. The context for this will not change during run-time. However they are ill suited as methods and cannot be used as constructors.

<script src=”https://gist.github.com/jyeung79/c1690c6e403b3a8dec1b34c65708afd6.js"></script>

Exports & Imports

Divide your javascript code across multiple files using export/import

Higher Order Functions

Higher order functions take other functions as a parameter or return a function as a value. The function passed as a parameter is called callback.

Callback

A callback is a function which can be passed as parameter to other functions.

Callback Calls Example

Sources:

Understanding callbacks

Q: How does a promise work then? How is callback hell related to functions?

Returning functions

Higher order functions return functions as values.

Returning function example

forEach, map, reduce all use callback functions to do some sort of function call

Functional Programming

These built-in Array prototype functions all use callbacks functions. ie) forEach, map, filter, reduce, find, every some, and sort

Callback function Methods

forEach — Iterates through the array’s elements and applies a callback function to each element

— Iterates through the array’s elements and applies a callback function to each element map — Returns a new array with a callback function applied to the input array

— Returns a new array with a callback function applied to the input array filter — Return the items that fulfill the filtering conditions

— Return the items that fulfill the filtering conditions reduce — Returns a single accumulator value from sum and value

— Returns a single accumulator value from sum and value every — Returns boolean from checking if all elements meet the same condition

— Returns boolean from checking if all elements meet the same condition find — Return first element that meets the condition

— Return first element that meets the condition findIndex — Return index of first element that meets condition

— Return index of first element that meets condition some — Check if one or more elements meet the condition

— Check if one or more elements meet the condition sort — Modifies the original array and sorts it by ascending or descending order

(Note— sort() will sorts numbers as strings not numbers. Refer to fix below)

Sorting Numbers Method

Function Declaration vs Expression

Function declaration means that the function is “saved for later use” while function expressions are executed when the interpreter reaches that line of code.

Function Declaration vs Function Expression

Function declarations are hoisted to the top of the code while function expressions are not. Benefits of using function expressions are:

Closures Arguments to other functions IIFE

NOTE: Arrow functions are similar to function expressions so they are not hoisted.

Sources:

Immediately invoked function expressions are immediately called when they are defined.

Different IIFE Declarations

Benefits of using IIFE

Avoid polluting global object Isolate variables declaration

6. Inheritance Model

6.1. Prototypes

All objects have a prototype. A prototype is the base class that the object accesses all its prototype’s methods & properties.

When defining functions for an object, it is better to do it on the prototype of that object. This is because defining the function in the constructor means that each time a new Object is created, the function gets duplicated.

6.2. Classes & Inheritance

Classes are prototypical inheritance model that you call to create an object of a certian blueprint. This is comparable to classes in other programmming languages such as C.

Classes Example

Theres a method to setting the prototype of an object Object.create . It returns a new object with the specified prototypes and any additional properties you want to add.

8. Other Javascript Concepts

8.1. Sets

Set is a collection of elements. Compared to arrays, a set can only contain unique elements.

Sets Example

Sets can be used to:

Count unique items in an array Find a union of two sets Difference of two sets

Different uses of Sets

8.2. Maps

TODO

8.3. Spread & Rest Operators

... can be used as a spread or a rest operator.

As Spread Operator

Used to split up array elements or Object properties Pulls out the elements out of the array or key pairs out of objects

Spread Operator

As Rest Operator

Used to merge a list of function arguments into an array

Rest Operator

8.4 Destructuring

TODO

9. Aynchronous Javascript

9.1. Promises vs Async/Await

Promise is an object that is a placeholder for the resulting value of an asynchronous operation. A promise is in one of these states:

Pending — initial state neither fulfilled or rejected Fulfilled — operation completed successfully Rejected — meaning that the operation failed

To understand Async/Await better you must understand promises. The reason you want to want to use Async/Await instead of Promises is to avoid Callback-hell

Callback Hell :(

Instead you can use Async/Await

Code is simplified and reduced significantly. Also there is no need to chain promises to make infinite callback loops.

Async/Await Usage

Await must be used within functions that are declared with async in front. ie)

Async/Await Example

Advantages of Async/Await