Freemote Logo
Background pattern

Don't ForgetJavaScript
Cheat Sheet

JS

JavaScript Fundamentals

JavaScript-Specific

Additional Topics

Why JavaScript?

Why JavaScript dominates modern development

MOST POPULAR LANGUAGE

// Stack Overflow 2023 Survey
JavaScript: 63.6%
HTML/CSS: 52.0%
Python: 49.2%
SQL: 47.7%
TypeScript: 40.5%
JavaScript has been the most used programming language for 11 years straight according to Stack Overflow's annual developer survey

WHERE IT RUNS

// Frontend (browsers)
websites, web apps

// Backend (Node.js)
servers, APIs

// Mobile (React Native)
iOS, Android apps

// Desktop (Electron)
Windows, Mac, Linux apps
JavaScript is the only language that runs natively in every web browser, plus it can power servers, mobile apps, and desktop software

JOB OPPORTUNITIES

// Average US Salaries (2024)
Junior Dev: $76,526
Mid-Level: $108,431
Senior: $147,192

// Job Openings
178,000+ JavaScript jobs
on LinkedIn USA
JavaScript developers are in high demand with competitive salaries. It's often considered the best first programming language to learn

MASSIVE ECOSYSTEM

// NPM Package Registry
Total Packages: 2.1M+
Weekly Downloads: 25B+
Active Users: 17M+
The Node Package Manager (NPM) is the world's largest software registry, with millions of free code packages you can use in your projects

EASY TO START

// To run JavaScript you need:
1. A web browser
2. A text editor

// That's it! No complex
// setup required
JavaScript has a gentle learning curve and requires minimal setup. You can start coding right in your browser's developer tools

Variables & Types

The building blocks of JavaScript programs

DECLARING VARIABLES

// let - can be changed later
let score = 0
score = 10

// const - can't be changed
const name = 'John'
// name = 'Jane' // Error!

// var - avoid (outdated)
Use let for variables that will change. Use const for variables that won't change. Avoid var (it's outdated and has scope issues)

DATA TYPES

typeof "hello"    // text (string)
typeof 42       // number
typeof true     // true/false (boolean)
typeof {}       // object
typeof []       // array (special object)
JavaScript has different types of data: text (strings), numbers, true/false values (booleans), and objects (including arrays)

CHANGING TYPES

Number("42")     // turns "42" into 42
String(42)      // turns 42 into "42"
Boolean(1)      // turns 1 into true
Sometimes you need to change one type to another. These functions help you do that

Functions

Reusable blocks of code

FUNCTION DECLARATION

function greet(name) {
  return `Hello ${name}!`
}

greet('John')  // call the function
returns "Hello John!"
Functions are reusable blocks of code. They can take inputs (parameters) and return outputs

FUNCTION EXPRESSION

const greet = function(name) {
  return `Hello ${name}!`
}

greet('John')
returns "Hello John!"
You can also store functions in variables. This is called a function expression

PARAMETERS & DEFAULTS

function greet(name = 'friend') {
  return `Hello ${name}!`
}

greet()        // uses default
greet('John')  // uses 'John'
returns "Hello friend!" "Hello John!"
Functions can have default parameter values that are used when no argument is provided

RETURN VALUES

function add(a, b) {
  return a + b
  // code after return is never run
}

const sum = add(2, 3)  // returns 5
returns 5
The return statement sends a value back from the function and ends its execution

Loops & Iteration

Different ways to repeat code

FOR LOOP

// counts from 0 to 2
for (let count = 0; count < 3; count++) {
  console.log(count)
}
returns 0 1 2
Repeats code a specific number of times. Great for when you know how many times you want to repeat something

FOR...OF LOOP

const fruits = ['apple', 'banana', 'orange']

for (let fruit of fruits) {
  console.log(fruit)
}
returns apple banana orange
An easier way to look at each item in a list (array). It's like saying 'for each fruit in my fruits list...'

WHILE LOOP

let count = 0

while (count < 3) {
  console.log(count)
  count = count + 1
}
returns 0 1 2
Repeats code as long as something is true. Like saying 'keep going while this is true'

Conditionals

Make decisions in your code

IF...ELSE

if (age >= 18) {
  console.log('Adult')
} else if (age >= 13) {
  console.log('Teen')
} else {
  console.log('Child')
}
Use if for the first condition, else if for additional conditions, and else as a final fallback

TERNARY OPERATOR

const status = age >= 18 ? 'Adult' : 'Minor'
Shorthand if/else for simple conditions

SWITCH

switch (fruit) {
  case 'apple':
    console.log('Selected apple')
    break
  default:
    console.log('No fruit selected')
}
Use switch when comparing a value against multiple options

String & Array

These methods create copies of the original (except for splice)

SLICE

[1, 2, 3].slice(0, 1)
returns [1]
Creates a new arr / str from first index, until second (or end, if no second arg)

SPLIT

"Jun-1".split("-")
returns ["Jun", "1"]
Convert a string to an array, split on the character you provide

JOIN

["Jun", "1"].join("-")
returns "Jun-1"
Convert an array to a string, separated by character you provide (or nothing using empty string)

SPLICE

[4, 2, 3].splice(0, 1)
returns [4] original array is set to [2, 3]
Modifies the array in place by removing 2nd arg # of items at index of first arg. You can also add items with a third argument. Finally, returns removed items

MAP

[1, 2, 3].map(num => num * 2)
returns [2, 4, 6]
Like a factory line - takes each item in your array, does something to it, and puts the result in a new array

FILTER

[1, 2, 3].filter(num => num > 1)
returns [2, 3]
Like a sieve - creates a new array keeping only the items that pass your test

REDUCE

[1, 2, 3].reduce((sum, num) => 
  sum + num, 0)
returns 6
Like a snowball - rolls through your array combining all items into one final value (like adding all numbers together)

Arrow Functions

Replace the function keyword with => after your arguments and you have an arrow function

ARROW FUNCTION DECLARATION

const add = (num1, num2) => {
  return num1 + num2
}
Unlike a regular function, you must store an arrow function in a variable to save it

AUTO RETURNS

(num1, num2) => num1 + num2
If your arrow function can fit on one line, you can remove the brackets AND return statement (return is automatic)

AUTO RETURNS II

(num1, num2) => (
  num1 + num2
)
Using a parenthesis on the same line (not bracket) is also an automatic return

SINGLE PARAMETER

word => word.toUpperCase()
If you just have a single parameter, you don't need the parentheses around your params

Objects

Powerful, quick storage and retrieval

KEY LITERALS

obj.a OR obj["a"]
This literally gives you the value of key "a"

KEY WITH VARIABLE

obj[a]
But this gives you the value of the key stored in variable a

FOR IN... LOOPS

for (let key in obj) ...
Loop over an object's keys with a for...in loop, and access its values using obj[key]

OBJECT.KEYS

Object.keys({a: 1, b: 2})
returns ["a", "b"]
Easily get an object's keys in an array with Object.keys(), or values with Object.values()

DESTRUCTURING

const {a} = {a: 1}
returns variable a is set to 1
Destructuring lets you pull values out of objects, the key becomes its variable name

DESTRUCTURING II

const a = 1
const obj = {a}
returns variable obj is set to {a: 1}
It goes the other way too, assuming the variable a was already 1, this creates an object

the DOM

For every HTML tag there is a JavaScript DOM node

CREATE ELEMENT

document.createElement('div')
Create an HTML element with JavaScript, returns a <Node> object

SET STYLE

<Node>.style.color = "blue"
You can change a <Node> object's CSS styles

ADD CLASS

<Node>.classList.add(".myClass")
Add or remove a Node's CSS classes

INNER HTML

<Node>.innerHTML = "<div>hey</div>"
<Node>.innerText = "hey"
You can set a Node's HTML or text contents

ADD CHILD

<Node1>.appendChild(<Node2>)
You can nest nodes as children to existing nodes

QUERY SELECTOR

document
.querySelector("#my-id")
Search the DOM for the first Node that matches - both ".classes" and "#ids" work!

QUERY SELECTOR ALL

document
.querySelectorAll(".my-class")
Same as above, but returns all matches (in a node list)

ADD EVENT LISTENER

<Node>.addEventListener("click",
function() {...}
)
Add listeners to user events, like clicks. The function will run when the event happens.

Async Programming

Usually network requests, these functions happen outside of the normal "flow" of code

FETCH

fetch('https://google.com')
Fetch returns a promise, which is non blocking, in other words, your code keeps going

PROMISE.THEN

.then(result => console.log(result))
When it finally does return, use a .then method to capture its result in the first argument

THEN CHAINING

.then(...).then(...)
A then block may also return a promise, in which case we can add another .then to it

PROMISE.CATCH

.catch(err => console.error(err))
Add a "catch" method to a promise, or chain of promises to handle any errors that may occur

PROMISE.ALL

Promise.all([fetch(...),fetch(...)])
  .then(allResults => ...)
You can pass multiple promises into the Promise.all function. Attaching a .then block will give you the result of all the promises, in a single array.

ASYNC/AWAIT

const res = await fetch(URL)
Async await is a cleaner syntax for promises. Instead of .then blocks simply use the await keyword, which will block your code until the promise returns ..however...

ASYNC/AWAIT II

const getURL = async (URL) => {
  await fetch(URL)
}
Await keywords must be inside of an "async" function -- simply attach the async keyword before any function, or arrow function definition

Common Mistakes

Easy mistakes to avoid when writing JavaScript

EQUALS SIGNS

// = is for setting values
let x = 5

// == checks if values are equal
"5" == 5  // true

// === checks if values AND types are equal
"5" === 5  // false
One equals sign (=) sets values. Two equals signs (==) checks if things are equal. Three equals signs (===) is the safest - use this most of the time!

VAR VS LET

if (true) {
  var x = "I exist everywhere"
  let y = "I only exist in here"
}
console.log(x)  // works
console.log(y)  // error!
var is old and creates variables that can leak out of their containers. Use let instead - it's safer and stays where you put it

ARRAY CLEARING

const arr = [1, 2, 3]
arr.length = 0  // Oops! Empties the array
console.log(arr)  // []
Setting an array's length to 0 deletes everything in it! This is usually not what you want. To check if an array is empty, use arr.length === 0 instead

DECIMAL MATH

0.1 + 0.2 === 0.3  // false!
0.1 + 0.2  // gives 0.30000000000000004
JavaScript isn't great at decimal math. 0.1 + 0.2 doesn't exactly equal 0.3! For money or precise decimals, use special libraries or round your numbers

TRY/CATCH

try {
  riskyOperation()
} catch (error) {
  console.error(error)
} finally {
  cleanup()
}
Like a safety net - wrap risky code in try/catch so your program doesn't crash if something goes wrong. The finally part always runs at the end

Classes & OOP

Object-oriented programming in JavaScript

CLASS BASICS

class Dog {
  constructor(name) {
    this.name = name
  }
  bark() {
    return `${this.name} says woof!`
  }
}
Like a blueprint - classes let you create many objects that share the same basic features (like many dogs that can all bark)

INHERITANCE

class Puppy extends Dog {
  constructor(name) {
    super(name)
  }
  playful() {
    return `${this.name} wants to play!`
  }
}
Like a child inheriting traits from parents - a Puppy class gets all the features of a Dog class, plus its own special features

Modern Features

ES6+ JavaScript features you should know

SPREAD OPERATOR (...)

const arr = [1, 2]
const newArr = [...arr, 3]

const obj = {a: 1}
const newObj = {...obj, b: 2}
Like unpacking a box - the ... spreads out all the items from an array or object into their individual pieces

NULLISH COALESCING (??)

const value = null ?? 'default'
const zero = 0 ?? 'default'
returns 'default' 0
Like a backup plan - if the first value is missing (null or undefined), use the backup value instead

OPTIONAL CHAINING (?.)

const value = obj?.deep?.property
Like checking if each step of a path exists before continuing - prevents errors when accessing nested object properties

NPM & Node.js

Managing projects and packages in JavaScript

NPM BASICS

npm init              // start a new project
npm install package    // add a package
npm start             // run your app
npm run dev           // start dev mode
Like an app store for code - NPM helps you add pre-built tools to your project and manage it

PACKAGE.JSON

{
  "dependencies": {
    "react": "^18.0.0"
  },
  "scripts": {
    "start": "node index.js"
  }
}
Like a recipe book - lists all the packages your project needs and commands it can run

NODE_MODULES

const express = require('express')
// or
import express from 'express'
The folder where NPM stores all your project's packages. Never edit it directly - let NPM handle it!

Popular Frameworks

Most-used tools for building modern websites

REACT logo

REACT

Made by Facebook

Pros

  • Huge community & job market
  • Flexible and powerful
  • Great for large applications

Cons

  • Steeper learning curve
  • Requires additional libraries
  • Can be overwhelming for beginners
VUE logo

VUE

Community-driven

Pros

  • Easier to learn
  • Great documentation
  • More structured than React

Cons

  • Smaller community than React
  • Fewer job opportunities
  • Less ecosystem support
NEXT.JS logo

NEXT.JS

Made by Vercel

Pros

  • Built-in routing & optimization
  • Server-side rendering
  • Great developer experience

Cons

  • React knowledge required
  • More complex deployment
  • Overkill for simple sites
SVELTE logo

SVELTE

Created by Rich Harris

Pros

  • Very fast performance
  • Simple, clean syntax
  • Small bundle sizes

Cons

  • Smaller ecosystem
  • Fewer learning resources
  • Less mature than others