Unofficial JavaScript Quick Reference

Introduction

This is a quick reference covering freeCodeCamp's Responsive Web Design and Javascript Algorithms and Data Structures courses. It's simply a translation of my notes in markdown into HTML. I found it useful to jog my memory when tackling projects. Credit for the content goes to the freeCodeCamp authors. And further credit to websites like developers.mozilla and w3schools where I found additional information.

- Alexander

Basics

Loading JavaScript in HTML:

Document object model (DOM)

A web application programming interface (API) used to build websites

Structured as a logical tree where:

API

An API is a way for two or more programs to communicate. The DOM includes multiple APIs, for example:

Interfaces

The DOM is made up of interfaces. Each of these interfaces has different methods. For example the interfaces include:

Some examples of common interfaces and methods are:

The relationship between objects and interfaces that are implemented in the DOM can be confusing.

Document

For example the following HTML document

<!DOCTYPE html>
<html class="e">
<head><title>Aliens?</title></head>
<body>Why yes.</body>
</html>

Would be represented by the DOM as:

Node

NodeList

Node tree

NameNodeMap

Element

Common elements and methods include:

Attribute (Atr)

Event

Commands / keywords

return

return 1 return exampleVariable return exampleArray

this

Refers to the current object Depending where used, what it references changes

// class constructor example
class Computer {
  constructor() {
      this.ram = 16;
  }
}

async

Use to create an asynchronous function This will return a Promise (Refer also to methods section and fetch API section)

const example = async () => {
  console.log("this is an example");
};

Data types

JavaScript has seven basic data types Use typeof to get variable information typeof exampleVariable

Primitive - Immutable (values cannot be changed after creation) - Represent single values - Number, string, boolean, undefined, null, symbol, bigint Non-primitive / reference: - Mutable (data can be changed after created) - Can store collections of data - Stored as references to memory locations - Object, array, function, date, regexp, map, set, weakmap, weakset

Undefined

A special data type that represents a value that doesn’t have a definition yet

Strings

// concatenation operator
const ourName = "freeCodeCamp";
const ourStr = "Hello, our name is " + ourName + ".";

// append operator
let newWeapon = weapons[currentWeapon].name;
text.innerText = "You now have a " + newWeapon + ".";
text.innerText += " In your inventory you have: "

// double quotes in a string
let text = "Naomi likes to play \"Zelda\" sometimes.";
let text = 'The monster screams "Arg!" as it dies. You gain experience points.'

// include a new line using \n
`lineOne = lineOne + "\n" + lineTwo;`

Numbers

let count = 8;
console.log(count + 1);

Binary numbers

Arrays

const locations = []; // create an empty array
let inventory = ["firstEntry", "secondEntry", "thirdEntry"]; // declare and initialise
inventory[0]; // access the first entry

Set

A set is a data structure that only allows unique values - Use new Set() to create a new set

// statistics calculator example - part of a method to identify duplicates
 if (new Set(Object.values(counts)).size === 1) {
    return null;

Node List

<ul>
  <li>List 1</li>
  <li>List 2</li>
  <li>List 3</li>
</ul>
const listItemsArray = Array.from(document.querySelectorAll('li'));
console.log(listItemsArray); // Output: (3) [li, li, li]

Objects

Object basics

Real life objects:

JavaScript objects:

Key points:

Defining JavaScript objects

Method 1: Object literal / object initializer: - a: const person = {firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue"}; - b: - const person = {}; - person.firstName = "John"; - person.lastName = "Doe"; - person.age = 50; - person.eyeColor = blue;

Method 2: new Keyword - const person = new Object(); - person.firstName = "John"; - person.lastName = "Doe"; - person.age = 50; - person.eyeColor = blue;

Accessing JavaScript object properties

Method 1 (dot notation): objectName.propertyName;

Method 2 (bracket notation): objectName["propertyName"]; - Use when property name has a space in it

Adding new values

Give it a value: person.nationality: "English";

Deleting properties

Use the delete keyword: delete person.age; or delete person["age"]; (delete both value of property and property)

JavaScript object methods

Actions that can be performed on objects. These are function definitions stored as property values.

const person = {
  firstName: "John",
  lastName: "Doe",
  age: 50,
  eyeColor: "blue",
  fullName = function() {
    return this.firstName + " " + this.lastName;  // this refers to the person object
    }  
  };

Accessing object methods

objectName.methodName(); // executes as a function objectName.methodName; // returns function definition

Displaying objects

// loop method
let text = "";
for (let x in person) {
  text += person[x] + " ";
};

// Object.values() method
const myArray = Object.values(person);

Other object notes

const locations = [{
  name: "town square", 
  "button text": ["Go to store", "Go to cave", "Fight dragon"], 
  "button functions": [goStore, goCave, fightDragon],
  text: "You are in the town square. You see a sign that says \"Store\"."
}];

location["button text"][0]; // bracket notation
locations.text; // dot notation

Object nesting

const user = {
name: "Quincy",
address: {
  city: "San Francisco",
  state: "CA",
  country: "USA"
}};

const state = user.address.state;
const state = user.address.["state"];
const state = user["address"]["state"];

Object destructuring syntax

const developerObj = {
name: "Jessica Wilkins",
isDeveloper: true
};

// The normal way to assign object properties to variables uses dot notation:
const nameVar = developerObj.name;
const isDevVar = developerObj.isDeveloper;

// Object destructuring reduces this to:
const { name: nameVar, isDeveloper: isDevVar } = developerObj;

// If variables have the same names as the object properties you can make it more concise:
const { name, isDeveloper } = developerObj;

Optional chaining: ?

const user = {
name: "Quincy",
address: {
  city: "San Francisco",
  state: "CA",
  country: "USA"
}};

// Accessing nested properties without optional chaining
const state = user.address.state; // CA

// Accessing a non-existent nested property with optional chaining
const zipCode = user.address?.zipCode; // Returns undefined instead of throwing an error

Class

A class in JavaScript is like a blueprint for creating objects. You can define objects and methods and create new objects with them.

class Computer {};

Instantiate a class

To test or use a class object you need to instantiate it.

const myComputer = new Computer();

Boolean + truthy & falsy

let isRunning = true;
let hasCompleted = false;

Rather than check a value is equal to a falsy value you can use the logical NOT operator (!) to check if the value is falsy.

const num = 0;

console.log(num === 0); // true
console.log(!num); // true

Variables

Variable definition

Guidelines:

  1. Always declare variables
  2. Always use const if the value should not be changed
  3. Always use const if the type should not be changed (Arrays and Objects)
  4. Only use let if you can’t use const
  5. Only use var if you MUST support old browsers.
// examples
let variableName; // declare variable (us camelCase
let variableName = 0; // declare and initialise a variable
let variableName = "exampleString"; 

let first = "One";
let second = "Two";
second = first;

let inventory = ["firstEntry", "secondEntry", "thirdEntry"]; // declare and initialise array with values
const locations = [{}];    // declare and initialise array with empty object
const button1 = document.querySelector("#button1");

Variable reassignment

When you reassign a variable, you reference the previous value. bees = bees + 3

Addition assignment operator: shorthand for assign the original value plus this test = test + 1; test += 1;

Increment operator: increases the value of a variable by 1 let test = 7; test++

// addition, subtraction
gold = gold - 10;
health = health + 10;
// compound assignment shorthand:
gold -= 10;
health += 10;
// increment operator
currentWeapon++;

Variable scope

// example from RPG instruction:
let num = 1;
if (num === 1) {
  let num = 2; // this num is scoped to the if statement
  console.log(num); // expected output: 2
}
console.log(num); // expected output: 1 (the global variable)

Checking variable values

You can check if inputs have had values entered by checking if true/false

const formInputsContainValues = titleInput.value || dateInput.value || descriptionInput.value;
if (formInputsContainValues) {}

typeof // checking variable types

console.log(typeof 42);  // Expected output: "number"
console.log(typeof 'blubber');  // Expected output: "string"
console.log(typeof true);  // Expected output: "boolean"
console.log(typeof undeclaredVariable);  // Expected output: "undefined"

Hard-coding

This is when you have values explicitly written in your code. This reduces reusability.

Arguments and parameters

Parameters are special variables that are given a value when you call a function. When you pass a value to a function call it’s referred to as an argument. They can be used in the function to dynamically change the result.

function demo(name) {

}

Node & elements

For standard dom elements like type and id you can use: - element.type = “text”; - element.id = “id”;

el.innerText

<p id="info">Example text</p>
// Replace the “Example text” with “Hello World”
const info = document.querySelector("#info");
info.innerText = "Hello World";

el.innerHTML

element.innerHTML = newHTML;

Example 1:

<p id="demo">This is a paragraph.</p>
document.querySelector("#demo").innerHTML = "Hello, innerHTML!";

Example 2:

<form id="form">
<label for="first-name">First name</label>
<input id="first-name" type="text">
</form>
// add a second label and input to a form
const formElement = document.getElementById("form");
const formContent = `
<label for="last-name">Last name</label>
<input id="last-name" type="text">
`;
formElement.innerHTML += formContent;

Reading innerHTML

<ul id="menu">
  <li>Home</li>
  <li>Services</li>
</ul>
```html

```jsx
let menu = document.getElementById('menu');
console.log(menu.innerHTML);

This will output:

<li>Home</li>
<li>Services</li>

el.textContent

Updating an element text based using a ternary operator conditional.

// example 1
el.textContent = condition ? "Use this text if the condition is true" : "Use this text if the condition is false";

// example 2
currentProductCount > 1 ? currentProductCountSpan.textContent = `${currentProductCount}x` : undefined;

Example from spam filter:

result.textContent = isSpam(messageInput.value) ? "Oh no! This looks like a spam message.":"This message does not seem to contain any spam."

el.value

node.textContent

<div id="example">This is some text content</div>
const element = document.getElementById('example');
console.log(element.textContent); // Output: This is some text content

node.parentElement

Returns the parent element of the specified element

// syntax
node.parentElement

// examples
document.body.parentNode; // returns html element
document.body.parentElement; // returns html element

document.documentElement.parentNode; // returns document node
document.documentElement.parentElement; // returns null (<html> does not have parent ELEMENT node)

element.Children

Returns a live HTML collection which contains all the child elements of the element upon which it was called.

const myElement = document.getElementById("foo");
for (const child of myElement.children) {
  console.log(child.tagName);
}

Window

Represents browser window

Methods

A method is a JavaScript function associated with certain values or objects It’s important to know what values methods return. Experiment with this.

Asynchronous

Console methods

The console object provides various methods to interact with the browsers debugging console (or terminal in environments like node.js)

.log()

Use to print to the console - Access within browser tools - Useful for debugging - Can show the current HTML structure by printing element.innerHTML

- console.log(”text”);
- console.log(variable);
- console.log("text" + variable + "text");
- console.log(element.innerHTML) // show current HTML structure

.error()

logs error messages usually displayed in red or with error icon in some environments includes a stack trace non-blocking

try {
    // Trying to call a non-existent function to trigger an error
    nonExistentFunction();
} catch (error) {
    console.error("An error occurred:", error);
}

In the above case the console log will show:

An error occurred: ReferenceError: nonExistentFunction is not defined at <anonymous>:2:5 ...

Element methods

Document query by CSS selector document.querySelector("valid CSS selector string")

// example - class
const el = document.querySelector(".myClass");

// example - first input element with name "login" inside a <div> with a class
const el = document.querySelector("div.user-panel.main input[name='login']");

// example - input with a parent div with the user-panel class but not the main class
const el = document.querySelector("div.user-panel:not(.main) input[name='login']",
);

// Calories counter example, uses constant representing an id plus also a class
const targetInputContainer = document.querySelector(targetId + " " + '.input-container');

Document query all document.querySelectorAll("valid CSS selector string")

Selectors: - Universal: document.querySelectorAll('*') all elements in the document - ElementName: document.querySelectorAll('h1') all h1 elements in the document - ClassName: document.querySelectorAll('.menu-item') all ‘menu-item’ class elements - id: document.querySelectorAll('#logo') the element with the ‘logo’ id - attributes: document.querySelectorAll('[autoplay]') all the elements with the autoplay attr

Document get element by id: document.getElementById('id')

<h1 id="title">Main title</h1>
// syntax
const mainTitleElement = document.getElementById('title');

// example from calorie counter
const calorieCounter = document.getElementById('calorie-counter');
calorieCounter.value

Document get elements by class name: ‘document.getElementsByClassName(’className’)

Returns an array like object. Use spread operator to convert to array.

const inputValues = document.getElementByClassName('values-dropdown');

Document create element: document.createElement('tagName');

// syntax
document.createElement('tagName')
// example
const divElement = document.createElement('div')

Document create text node: document.createTextNode("text");

// syntax
document.createTextNode("your text")
// example
const myText = document.createTextNode("your text")
const resetText = document.createTextNode("Reset Playlist");

Document append child: element.appendChild()

// example
const parentElement = document.createElement("button")
const parentElementText = document.createTextNode("Click me")
parentElement.appendChild(parentElementText) // attach the text "Click me" to the button

Show or hide an element: object.style.display

// example from RPG instruction to update display for a <p> element
const paragraph = document.querySelector('p');
paragraph.style.display = 'block';
paragraph.style.display = 'none';

Insert HTML: insertAdjacentHTML()

Remove HTML element: element.remove()

// Todo App example
buttonEl.parentElement.remove();

Set a class on an element: ’el.className`

el.className = "class"

Adding a class to an element: classList.add

//music player example
playButton.classList.add(playing);

Removing a class from an element: classList.remove

paragraphElement.classList.remove('hide');

Toggle classes on an element: el.classList.toggle()

element.classList.toggle("class-to-toggle");

Set element attribute .setAttribute(name, value)

Note might be easier to use e.g. element.type = "text";

// syntax
element.setAttribute("class", "democlass");

// example
myInput.setAttribute("type", "button");

// example
const button = document.querySelector("button");
button.setAttribute("name", "helloButton");
button.setAttribute("disabled", "");

If you have a node list of radio buttons and you want to change between enabled and disabled you just do this: nodeList[index].disabled = false;

Removing an attribute from html .removeAttribute(”attributeName”)

// syntax
element.removeAttribute(name) 

// music player example
playlistSongElements.forEach((songEl) => {
  songEl.removeAttribute("aria-current");
});

Object freeze object.freeze()

// example
`Object.freeze(myFavoriteFootballTeam)`

Show modal for dialog elements dialogElement.showModal();

The HTML dialog element has a showModal() method that can be used to display a modal dialog box on a web page.

dialogElement.showModal();

Close a dialog element

The HTML dialog element has a close() method that can be used to close or cancel out of a modal

dialogElement.close();

Other methods

.bind() object borrows method from other object

const person = {
  firstName:"John",
  lastName: "Doe",
  fullName: function () {
    return this.firstName + " " + this.lastName;
  }
}

const member = {
  firstName:"Hege",
  lastName: "Nilsen",
}

let fullName = person.fullName.bind(member);

Preventing default event behaviour: preventDefault()

// syntax
event.preventDefault();

// example - prevent default action of a checkbox
document.getElementById("myCheckbox").addEventListener("click", function(event){
event.preventDefault()
}); 

// example - from do app, stop browser from refreshing
taskForm.addEventListener("submit", (e) => {
e.preventDefault();
})

Chaining

// From todo app: good example using split and join on an input string
id: `${titleInput.value.toLowerCase().split(' ').join('-')}-${Date.now()}`,

Alert message: alert(message)

window.alert("Please provide a decimal number");

Confirm message: .confirm(message)

Displays a confirmation prompt to the user.

const isCartCleared = confirm("Are you sure you want to clear all items from your shopping cart?")

SetTimeout()

Takes two arguments

setTimeout(() => {
console.log("Hello, world!");
}, 3000);

.charCodeAt()

Return the unicode of a character at a specific index.

let text = "Hello, world";
let code = text.charCodeAt(0);

.fromCharCode()

Convert unichode value to character Syntax is always String. you cannot use myString

let char = String.fromCharCode(65);

Number methods

Notes on calculating with numbers

Number constructor: Number()

Number('10'); // returns the number 10
Number('abc'); // returns NaN

// calorie counter example
calories += Number(currVal);

.toFixed()

let num = 5.56789;
let n = num.toFixed(2);

Even or odd

// check if array length is even
arr.length % 2 === 0;

// check if array length is odd
arr.length % 2 === 1;

isNaN()

isNaN("test"); // true
isNaN(2); // false
isNaN("3.5"); // false

// check an input field string is a number
isNaN(parseInt(numberInput.value))

// example from statistics calculator
const filtered = numbers.filter((el) => !isNaN(el));

Squaring numbers

To square a value, you can use the ** operator. For example, 3 ** 2 would return 9.

// statistics calc example
const squaredDifferences = differences.map(
  el => el ** 2
);

Math()

Contains static properties for mathematical constants and functions

One way to randomize an array of items would be to subtract 0.5 from Math.random() which produces random values that are either positive or negative. This makes the comparison result a mix of positive and negative values, leading to a random ordering of elements.

// generate a random number between 1 & 5
Math.floor(Math.random() * 5) + 1
// generate a random number between 0 & 3
Math.floor(Math.random() * 3)

// sorting an array randomly (see details on how sort works)
const names = ["Tom", "Jessica", "Quincy", "Naomi"];
names.sort(() => Math.random() - 0.5);

// absolute number
const num = -5;
Math.abs(num); // 5

// minimum number
const numbersArr = [2, 3, 1];
console.log(Math.min(...numbersArr));  // Expected output: 1

// square root using exponents: to calculate square root of 4
const base = 4;
const exponent = 0.5;
// returns 2
Math.pow(base, exponent);

infix

Random numbers

function randomRange(myMin, myMax) {
  return Math.floor(Math.random() * (myMax - myMin + 1) + myMin);
}

// spreadsheet example
random: (nums) => Math.floor(Math.random() * ((nums[0] + nums[1]) - Math.min(...nums) + 1) + Math.min(...nums))
// or
random: ([x, y]) => Math.floor(Math.random() * y + x),

(see strings for parseInt() and parseFloat())

Boolean methods

Invert boolean

You can use the logical not operator ! to invert the value of a boolean

isCartShowing = !isCartShowing;

String methods

Concatenation: + or .concat()

Use + to append a new string to an existing string Or use the string.concat(string)

hello = hello + " World";
avatarUrl.concat(avatar)

/hello/: regex (regular expressions)

Basics:

Adjusters:

Characters

Flags to alter behaviour (add after closing /):

Pattern collections:

Examples:

const regex = /hello/; // search for "hello"
const regex = /\+-\s/; // search for "+- "
const regex = /[+-\s]/; // search for '+', '-', ' '

// examples from spam filter
const helpRegex = /please help|assist me/i;
const dollarRegex = /[0-9]+ (?:hundred|thousand|million|billion)? dollars/i;
const freeRegex = /(?:^|\s)fr[e3][e3] m[o0]n[e3]y(?:$|\s)/i;
const stockRegex = /(?:^|\s)[s5][t7][o0][c{[(]k [a@4]l[e3]r[t7](?:$|\s)/i;
const dearRegex = /(?:\s|^)d[e3][a@4]r fr[i1|][e3]nd(?:\s|$)/i;

template literals: Hello ${variable}

const name = "Naomi";
const templateLiteral = `Hello, my name is ${name}~!`;
console.log(templateLiteral); // "Hello, my name is Naomi~!"

// From calorie counter
function addEntry() {
const targetInputContainer = document.querySelector(`#${entryDropdown.value} .input-container`);
}

// From music player
const songToHighlight = document.getElementById(`song-${userData?.currentSong?.id}`);

// From todo app: reformat an input string (lowercase, hyphen separate) and add the date:
id: `${titleInput.value.toLowerCase().split(' ').join('-')}-${Date.now()}`,

.split(): split a string into array of characters

const str = 'Hello World';
const str1 = str.split(); // ["Hello World"]
const str2 = str.split(""); // ["H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"]

.replace(arg1, arg2) replace a character in a string

// example from calorie counter instructions
"hello".replace(/l/g, "1");

.repeat()

The repeat method can be used to repeat strings.

const activity = "Code! ";
activity.repeat(3);

.match(): return 1st/all matches in a string

const str = 'example string';
const regex = /example/;
const result = str.match(regex); // Returns ['example']

.test(): test if string matches a regex

regexVariable.test(stringVariable)

// spam filter example
const isSpam = (msg) => helpRegex.test(msg);

.toLowerCase(): convert string to lowercase

const firstName = 'JESSICA';
console.log(firstName.toLowerCase()); // Output: jessica

string(): convert value to string

Reliable way to convert values to strings. Even falsy values such as null, undefined

const num = 5;
console.log(String(num)); // "5"
console.log(String(null)); // "null"

includes()

See array methods. Also works with strings as used in spreadsheet exercise. Where value = input value and element.id = element id.

if (!value.includes(element.id)) {};

parseInt()

Converts a string into a whole number.

parseInt(2.2) // 2.2
parseInt("2e3") // 2
parseInt("e") // NaN

parseFloat()

Converts a string to a floating point number

function circumference(r) {
  return parseFloat(r) * 2.0 * Math.PI;
}

Tip: cleaning strings with regex, replace & match

Example 1: removing +, -, ” ” from strings through using two approaches

Method A: with if statement and new array

function cleanInputString(str) {
  const strArray = str.split('');  // put string into array of chars
  const cleanStrArray = [];

  for (let i = 0; i < strArray.length; i++) {  // loop through array of chars
    if (!["+", "-", " "].includes(strArray[i])) {  // if char not +, -, " " move to new array
      cleanStrArray.push(strArray[i])
    };
  };
};

Method B: with regex and replace

function cleanInputString(str) {
  const regex = /[+-\s]/g;  // regular expression of chars +. - , " "
  return str.replace(regex, '');  // use replace to replace matches with blank
}

Example 2: filtering out exponential notation

function isInvalidInput(str) {
  const regex = /\d+e\d+/i;
  str.match(regex);
}

Object methods

shorthand property name syntax

Relevant when property name and value are the same.

// using shorthand property name syntax
obj = {
  a, b, c
}

obj = {
  a: a,
  b: b,
  c: c
}

.keys(obj)

Use to return the keys of an object Returns each object key as a string entry in an array element

const object1 = {a: 'string', b: 42, c: false}
object.keys(object1) // output: ["a", "b", "c"]

.values(obj)

Use to return the values of an object Returns each object value as a string entry in an array element

const object1 = {a: 'string', b: 42, c: false}
object.values(object1) // output: ["string", "42", "false"]

Object.entries(objectName)

Convert an object to an array of key value pairs

let obj = { name: 'John', age: 30, city: 'New York' };

let arr = Object.entries(obj);
console.log(arr);

// Output: [['name', 'John'], ['age', 30], ['city', 'New York']]

object to array using Array.from

let obj = {a: 1, b: 2, c: 3};
let arr = Array.from(Object.entries(obj), ([key, value]) => value);

console.log(arr);
// Output: [1, 2, 3]

Sorting objects by key or value

Sort alphabetically on property key / name:

const obj = {
  "banana": "yellow",
  "apple": "red",
  "cherry": "dark red"
};
const sortedKeys = Object.keys(obj).sort();

Sort numerically on property key / name:

const obj = {
  "100": "century",
  "10": "decade",
  "1": "year"
};
const sortedKeys = Object.keys(obj).sort((a, b) => a - b);

Sort numerically on property value:

const obj = {
  "kiwi": 2,
  "banana": 3,
  "apple": 1
};
const sortedKeys = Object.keys(obj).sort((a, b) => obj[a] - obj[b]);

Convert object to array then sort on values

let arr = Object.entries(counts).sort((a, b) => b[1] - a[1]);

.hasOwnProperty()

Returns a boolean indicating whether this object has the specified property as its own property as opposed to inheriting it

const object1 = {};
object1.property1 = 42;

console.log(object1.hasOwnProperty('property1'));
// Expected output: true

console.log(object1.hasOwnProperty('toString'));
// Expected output: false


// a function that searches an object for an id 
const forumCategory = (id) => {
  if (allCategories.hasOwnProperty(id)) {

  }
};

object tips

Apply sort on option keys
const highest = Object.keys(counts).sort(
  (a, b) => {return counts[b] - counts[a]})

Array methods

Array tips

Accessing the last element array[array.length - 1] Check an array is empty if (!array.length)

Count entries of numbers in arrays
const numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5];

// Create an empty object to store the counts
const counts = {};

numbers.forEach(num => {
  // If the number is already a key in the object, increment its count
  // Otherwise, initialize it with a count of 1
  counts[num] = (counts[num] || 0) + 1;
});

console.log(counts);

Array()

new Array(Value1, Value2, ...); or Array(Value1, Value2, ...); new Array(ArrayLength); or Array(ArrayLength);

Create array objects Call with or without a new keyword If value is only one element, then it creates an array with that length

// Using elements 
const array1 = new Array(1, 2, 3, 4, 5) 
  
// Using arrayLength 
const array2 = new Array(10) 
  
console.log(array1);  // (5) [1, 2, 3, 4, 5]
console.log(array2); // (10) [empty × 10]

.from()

Create a new shallow copied array instance from an iterable or array-like object.

Array.from(arrayLike) Array.from(arrayLike, mapFn) Array.from(arrayLike, mapFn, thisArg)

console.log(Array.from('foo')); // ["f", "o", "o"]

console.log(Array.from([1, 2, 3], (x) => x + x)); // [2, 4, 6]

.length

Returns the Length of an array

.push() a value to the end of an array

Push a value to the end of an array Returns the new length of the array

let rows = ["Naomi", "Quincy", "CamperChan"];
rows.push("freeCodeCamp");

.pop(): a value of the end of an array & return

Pop a value of the end of an array and return it

let rows = ["Naomi", "Quincy", "CamperChan"];
rows.push("freeCodeCamp");
let popped = rows.pop();
}

.unshift(): add a value to the start of an array, return new length

Add one or more elements to the beginning of an array

const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5)); // will result in [4, 5, 1, 2, 3]
// Expected output: 5 (new length)

.shift(): remove a value at the start of an array and return it

// example from RPG instruction
const numbers = [1, 2, 3];
const firstNumber = numbers.shift(); // returns 1

.splice(): remove, replace or add

const fruits = {"mango", "date", "cherry", "banana", "apple"};

const removedFruits = fruits.splice(1, 2);
console.log(removedFruits); // ['date', 'cherry']
console.log(fruits); // ['mango', 'banana', 'apple']

.includes(): check if contains an element

// Instructions example from RPG
const numbersArray = [1, 2, 3, 4, 5]
const number = 3

if (numbersArray.includes(number)) {
console.log("The number is in the array.")
}

// example from calorie counter instructions
const inputString = "Hello World";
const charArray = inputString.split('');
const consonantArray = [];

// if charArray[i] is not a,e,i,o,u push it into consonantArray
for (let i = 0; i < charArray.length; i++) {
if (!['a', 'e', 'i', 'o', 'u'].includes(charArray[i])) {
  consonantArray.push(charArray[i]);
}
}

.find(): find 1st element using callback

const numbers = [10, 20, 30, 40, 50];

// Find the first number greater than 25
const found = numbers.find((element) => element > 25);
console.log(found); // Output: 30

.indexOf(): find 1st index of element

const animals = ["dog", "cat", "horse"];
animals.indexOf("cat") // result = 1

.findIndex(): find 1st index based on function criteria

Finds and returns the 1st element in an array that meets the criteria specified by a provided testing function. If no such element is found, the method returns -1

const numbers = [3, 1, 5, 6];
const firstNumLargerThanThree = numbers.findIndex((num) => num > 3);

console.log(firstNumLargerThanThree); // results = 2

.filter(): filter using callback

Keeps only the elements of an array that satisfy the callback function passed to it

const numArr = [1, 10, 8, 3, 4, 5]
const numsGreaterThanThree = numArr.filter((num) => num > 3);

console.log(numsGreaterThanThree) // Output: [10, 8, 4, 5]

Using filter and indexOf to remove duplicates

nodupes: nums => nums.filter((num, index) => nums.indexOf(num) === index)

spread [...arr1,...arr2]: copies one array to another

// use to convert a collection to an array
[...addToCartBtns].forEach();

st arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combinedArr = [...arr1, ...arr2];
console.log(combinedArr); // Output: [1, 2, 3, 4, 5, 6]

// example - music player, used to copy the array `allSongs` to a playlist object property 'songs' 
let userData = {
songs: [...allSongs]
};

.map(): Iterate through, apply callback, return new array

const numbers = [1, 2, 3];
const doubledNumbers = numbers.map((number) => number * 2); // result = [2, 4, 6]

// music player example
const songsHTML = array.map(song => {});
// spreadsheet example
.map((element, index) => element + index);

.forEach(): call a function once per array element

array.forEach(function(currentValue, index, arr), thisValue)

// example 1
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((number) => {
console.log(number); // result = 1, 2, 3, 4, 5
});

// example 2
let sum = 0;
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction);

function myFunction(item) {
sum += item;
}

// example 3: modify the element values in the array

let arr = [1, 2, 3]; 
arr.forEach((element, index) => {  
    arr[index] = element + 10;  
}); 
console.log(arr);

.join(): Join elements to create a string

const exampleArr = ["This", "is", "a", "sentence"];
const sentence = exampleArray.join(" "); // = This is a sentence

.reverse(): reverse an array in place

Reverse the order of the elements in the array in place.

const array = [1, 2, 3, 4, 5];
array.reverse();
console.log(array); // [5, 4, 3, 2, 1]

.some(function): test array against function

Tests whether at least one element passes test provided by implemented function

const array = [1, 2, 4, 5,];
const even = (element) => element % 2 === 0;  // check if an element is even
console.log(array.some(even));

Example from spam filter:

const isSpam = (msg) => denyList.some((regex) => regex.test(msg))

Example from spreadsheet

const arr = ["A", "b", "C"];
arr.some(letter => letter === letter.toUpperCase());

.reduce()

Takes an array and applies a callback to condense to a single value

// to sum an array
const sum = array.reduce((acc, el) => {return acc + el}, 0);

// setting initial value to an empty string
array.reduce((acc, el) => acc + el.toLowerCase(), "");

.slice()

slice() or slice(start) or slice(start, end)

Return a shallow copy of an array into new array from start to end

// used in statistics calculation
const sorted = array.slice().sort((a, b) => a - b);

.fill()

Fill an array with a value. Tip: chain to an array creation with specified length

Array(end - start + 1).fill(start);

.every()

Tests if all elements in an array pass the test provided by a function Can be used to check if all elements in an array are true

const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// Expected output: true

// check all elements in an array are true
if (array.every((element) => element)) {
  // do something
}

destructure / unpack array object keys

// array - a shorter way of writing let firstName = johnDoe[0] etc.
let johnDoe = ["John", "Doe", "Iskolo"]
let [firstName, lastName, title] = johnDoe

// unwanted items can be skipped using commas

let [firstName, , title] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
alert( title ); // Consul

// other iterables
let [a, b, c] = "abc"; // ["a", "b", "c"]
let [one, two, three] = new Set([1, 2, 3]);

// using with array-returning methods
let [firstName, surname] = "John Smith".split(' ');
alert(firstName); // John
alert(surname);  // Smith

// Object property as assignable on left side
let user = {};
[user.name, user.surname] = "John Smith".split(' ');
alert(user.name); // John
alert(user.surname); // Smith

// object destructuring syntax
let {var1, var2} = {var1:…, var2:…}

// object example
let options = {
  title: "Menu",
  width: 100,
  height: 200
};

let {title, width, height} = options;

alert(title);  // Menu
alert(width);  // 100
alert(height); // 200

Class methods

constructor

Use to create a new instance of a class

class Computer {
  constructor() {

  }
}

// constructor that takes in coordinates
class Platform {
  constructor(x, y) {

  }
}

// object
class CheckPoint {
  constructor(x, y, z) {
    this.position = {x, y};
  };
};

example of add item method

class Computer {
  constructor() {
    this.ram = 16;
  }

  addRam(amount) {
    this.ram += amount;
  }
}

Events

Listen for an event: addEventListener('event',function)

Tip: when picking up and logging a number from an input on a form use preventDefault to stop refresh of form

Whenever an event listener is triggered, an event object is created automatically. You don’t have to use this, but it can be useful to access information about the event that was triggered. e is used as a common parameter name for this event object.

// examples
const button = document.querySelector("button")
button.addEventListener('click', e => {
console.log(e)
})
const button = document.querySelector("button")
function printName() {
console.log("Jessica");
}
button.addEventListener('click', printName);

// examples from exercises
audio.addEventListener('ended', () => {});
element.addEventListener('change', () => {});
numberInput.addEventListener('keydown', () => {});  // decimal to binary converter

Target

When using a change event listener the event parameter is used as a change event The target property of the change event represents the element that was changed

input.onchange = update; 
// as it's a change event update can be called with parameter event?

const update = event => {
  const element = event.target;
  const value = element.value.replace(/\s/g, ""); 
  // example above replaces whitespace from an the changed input element

onload

Allows you to define behaviour when the window has loaded the entire page, including stylesheets and scripts.

window.onload

// example 3 - calling functions on window load
window.addEventListener('load', () => {
  initChangeInDrawer();
  initPrice();
});

onclick

button.onclick = myFunction // not myFunction()

onchange

Occurs when the value of an HTML element is changed and it loses focus Similar to oninput event which occurs immediately after the change Onchange works on works on select, oninput does not.

keydown & key

// example 1
numberInput.addEventListener("keydown", (e) => {
  if (e.key === "Enter") {
  checkUserInput();
  }
});

// example 2 - destructuring to get the key property from the event object
window.addEventListener('keydown', ({key}) => {});

// another example with destructuring
btn.addEventListener('click', ({ target }) => {
  console.log(target);
});

Functions

Function basics

A function is a block of code that can be reused throughout your application

// 1) define
function name() {
}

function name(parameter) {

}
  
// 2) call
name();

Return keyword and return values

// return value
function demo() {
  return "Functions are cool!";
}

// return directly a locally scoped variable
function getName() {
  const name = "Camper cat";
  return name;
}
console.log(getName()); // "Camper cat"

// return via global variable a locally scoped variable
const capturedReturnValue = getName();
console.log(capturedReturnValue); // "Camper cat"
console.log(name); // reference error

Return multuple values (via array or object)

JavaScript functions technically only return 1 value - But I note you can return a variable + “text” But it can be a collection that holds multiple values You can return multiple values using an array or object - Array: values accessed by position - Object: values accessed by name


// return using array
function getValues() {
  let arr = [1, 2, 3];
  let num1 = 10;
  let num2 = 20;
  return [arr, num1, num2];  // Return multiple values as an array
}

let [myArray, a, b] = getValues();  // Destructuring assignment

console.log(myArray);  // Output: [1, 2, 3]
console.log(a);        // Output: 10
console.log(b);        // Output: 20

// return using object
function getValues() {
  let arr = [1, 2, 3];
  let num1 = 10;
  let num2 = 20;
  return {
    array: arr,
    value1: num1,
    value2: num2
  };  // Return an object with multiple properties
}

let result = getValues();

console.log(result.array);  // Output: [1, 2, 3]
console.log(result.value1); // Output: 10
console.log(result.value2); // Output: 20

// or using destructuring

let { array, value1, value2 } = getValues();

console.log(array);  // Output: [1, 2, 3]
console.log(value1); // Output: 10
console.log(value2); // Output: 20

Arrow functions

// regular arrow
const arrowFunction = (param) => {
return param
};

//implicit return arrow
const arrowFunction = (param) => param;

// isSpam example of implicit return
const isSpam = (msg) => false;

Callback function

Examples below from taken from here

Example 1: Consider a function to filter out odd numbers:

function filter(numbers) {
let results = [];
for (const number of numbers) {
  if (number % 2 != 0) {
    results.push(number);
  }
}
return results;
}
let numbers = [1, 2, 4, 7, 3, 5, 6];
console.log(filter(numbers));

To make filter more generic and re-usable:

function isOdd(number) {
return (number % 2 != 0);
}

function filter(numbers, fn) {
let results = [];
for (const number of numbers) {
  if (fn(number)) {
    results.push(number);
  }
}
return results;
}
let numbers = [1, 2, 4, 7, 3, 5, 6];
console.log(filter(numbers, isOdd));

Example 2: Anonymous callback function

function filter(numbers, callback) {
let results = [];
for (const number of numbers) {
  if (callback(number)) {
    results.push(number);
  }
}
return results;
}

let numbers = [1, 2, 4, 7, 3, 5, 6];

let oddNumbers = filter(numbers, function (number) {
return number % 2 != 0;
});

console.log(oddNumbers);

This can be further simplified using arrow notation:

Pass function reference as callback

const myFunc = (val) => `value: ${val}`;
const array = [1, 2, 3, 4];
const newArray = array.map(myFunc);

.map calls myFunc result will be newArray = [value: 1, value: 2, value: 3, value: 4] If you want to ren the inner of a callback you need to call it not reference it

Default values for functions

Function parameters can be initialized with default values. If a function is called without an argument, the default value will be used.

const greeting = (name = "Anonymous") => {
return "Hello " + name;
} 

console.log(greeting("John")); // Hello John
console.log(greeting()); // Hello Anonymous

Functions with fallback values

Useful when writing functions that won’t immediately have a return value.

const myFunction = (string = "") => {};
const updateUI = (array = []) => {};

Nested functions

const outer = () => {
  const inner = () => {

  };
};

Currying

sum(1, 2, 3) becomes sum(1)(2)(3)

Returning a function within a function Functions with multiple args become a sequence of functions with single arg

Notes

const sum = (a, b, c) =>  a + b + c;

const sumCurry = (a) => { // takes one argument a
  return (b) => {  // returns a function that takes arg b
    return (c) => {  // returns a function that takes arg c
      return a + b + c  // returns the sum
    }
  }
}

const sumCurry (a) => (b) => (c) => {
  return a + b + c;
}

Spreadsheet example:

Error log example

// Regular
function log(level, context, message) {
  console.log(`[${level}] ${context}: ${message}`);
}

log('INFO', 'MyApp', 'This is an info message:')
log('ERROR', 'MyApp', 'This is an error message:')

// Curried
const log = level => context => message => {
  console.log(`[${level}] ${context}: ${message}`);
}

const infoLog = log('INFO');
const errorLog = log('ERROR');

const myAppInfoLog = infoLog('MyApp');
const myAppErrorLog = errorLog('MyApp');

myAppInfoLog('This is an info message:');
myAppErrorLog('This is an error message:');

Unused parameters

Common practice to proceed unused parameters with an underscore

e.g. _match

Loops (for, while)

While

// syntax
while (condition) {
  logic;
}


// example from RPG instructions
while (i < 5) {

}

For

For loops are declared with three expressions separated by semicolons.

// Example from RPG exercise
for (let x = 1; x < 5; x++) {

}

For…of

Used to iterate over items in an iterable object (comprised of elements such as an array)

for (const value of iterable) {
  console.log(value);
}

Sample use cases

Fill an array using a loop and .push()

for (let i = 0; i < 8; i++) {
  rows.push(i);
}

Conditionals (if, switch, ternary)

if else

Run a block of code only if a condition is met.

// syntax
if (condition) {
  logic
}

// example if and else
const num = 5;
if (num >= 3) {
console.log("This code will run because num is greater than or equal to 3.");
} else {
console.log("This code would run if const num is less than 3");
}

// music player example with equal or strict not equal
if (userData?.currentSong === null || userData?.currentSong.id !== song.id) {
  audio.currentTime = 0;
}

else if

Check multiple conditions in a single block of code

//syntax
if (condition1) {
  // code to run if condition1 is true
} else if (condition2) {
  // code to run if condition2 is true
} else if (condition3) {
  // code to run if condition3 is true
} 

Switch

Commonly used for drop down options or branching logic

switch (expr) {
case 'case123':
  // Write your logic here
break; // Terminate the switch statement 
}

switch (dayOfWeek) {
case 1:
  console.log("It's Monday!");
  break;
case 2:
  console.log("It's Tuesday!");
  break;
// ...cases for other workdays
default:
  console.log("It's the weekend!");
}

For similar cases in a switch statement with the same actions you can utilise the fall through feature and positioning of break

case "ArrowUp":
case " ":
case "Spacebar":
  player.velocity.y -= 8;
break;

Ternary operator

condition ? expressionIfTrue : expressionIfFalse

// Example 1 - traditional if statement approach
if (num > 5) {
return 'num is greater than 5';
} else {
return 'num is smaller than or equal to 5';
}

// Example 1 - simplified approach using ternary operator
return num > 5 ? 'num is greater than 5' : 'num is smaller than or equal to 5';

// Example 2 - assigning a value to an element/variable using ternary
showHideCartSpan.textContent = isCartShowing ? "Hide" : "Show";

You can execute more than one action in a ternary operator by using comma notation e.g.

rulesBtn.addEventListener('click', e => {
  rulesContainer[0].style.display = rulesContainer[0].style.display === 'none' 
  ? (rulesContainer[0].style.display = 'block', isModalShowing = true)
  : (rulesContainer[0].style.display = 'none', isModalShowing = false);
  console.log(isModalShowing);
})

Sorting

.sort()

// syntax
array.sort(compareFunction)

// examples
const names = ["Tom", "Jessica", "Quincy", "Naomi"];
names.sort() // ["Jessica", "Naomi", "Quincy", "Tom"]

const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});

// fruits example
const fruits = [
{ name: "Apples", price: 0.99 },
{ name: "Blueberries", price: 1.49 },
{ name: "Grapes", price: 2.99 },
];

fruits.sort((a, b) => {
if (a.name < b.name) {
  return -1;
}

if (a.name > b.name) {
  return 1;
}
return 0;
});

// random example
const names = ["Tom", "Jessica", "Quincy", "Naomi"];
names.sort(() => Math.random() - 0.5);

Bubble Sort

Manual bubble sort

const bubbleSort = (array) => {
  for (let i = 0; i < array.length; i++) {
    for (let j = 0; j < array.length - 1; j++) {
      if (array[j] > array[j + 1]) {
        const temp = array[j];
        array[j] = array[j + 1];
        array[j + 1] = temp;
      }
    }
  }

  return array;
}

Selection sort

Manual selection sort

const selectionSort = (array) => {
  for (let i = 0; i < array.length; i++) {
    let minIndex = i;

    for (let j = i + 1; j < array.length; j++) {
      if (array[j] < array[minIndex]) {
        minIndex = j;
      }
    }

    const temp = array[i];
    array[i] = array[minIndex];
    array[minIndex] = temp;
  }

  return array;
}

Insertion sort

Manual insertion sort

const insertionSort = (array) => {
  for (let i = 1; i < array.length; i++) {
    const currValue = array[i];
    let j = i - 1;

    while (j >= 0 && array[j] > currValue) {
      array[j + 1] = array[j];
      j--;
    }
    array[j + 1] = currValue;
  }
  return array;
}

Operators (==, !, > etc.)

Date()

const currentDate = new Date();
console.log(currentDate);
// Output: Mon Aug 23 2021 15:31:00 GMT-0400 (Eastern Daylight Time)

// Calculations
let date1 = new Date('2023-01-01T00:00:00');
let date2 = new Date('2023-01-01T00:01:00');

let difference = date2 - date1;
console.log(difference); // 60000 (milliseconds)

Date.now()

Returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC

Get date .getDate()

Returns a number between 1 and 31 for the day of the month for that date

const date = new Date();
const dayOfTheMonth = date.getDate();
console.log(dayOfTheMonth); // 20

Get month .getMonth()

Returns a number between 0 and 11 that represents month for date provided

Get full year .getFullYear()

Returns a number which represents the year for the provided date

Get hours .getHours()

Returns a number between 0 (midnight) and 23 (11pm)

Get minutes .getMinutes()

Returns a number between 0 and 59 that represents minutes for the provided date

Web audio API

const audio = new Audio();

// from music player where song is a constant representing an object with current song information
audio.src = song.src;
audio.title = song.title;
audio.play()

audio.addEventListener('ended', () => {});

Local storage

A web storage feature that lets you persist data by storing as a key:value pair

Set item

Save an item to local storage

syntax
localStorage.setItem("key", value) // value can be string, number, or any other data type

// Todo App explanation

// Sample array data
const myTaskArr = [
{ task: "Walk the Dog", date: "22-04-2022" },
{ task: "Read some books", date: "02-11-2023" },
{ task: "Watch football", date: "10-08-2021" },
];

// First Check storage tab of console 
// Data will show up as [object Object]: everything in local storage should be string format
// Therefore you need to wrap the data with JSON.stringify()
localStorage.setItem("data", JSON.stringify(myTaskArr));

// Todo App actual exercise
localStorage.setItem("data", JSON.stringify(taskData));

Get item

Retrieve an item from local storage

// Todo App explanation continued from 'set item' above
// Retrieve "data' from local storage and print to console log. It will be retrieved as a string.
const getTaskArr = localStorage.getItem("data")
console.log(getTaskArr)

// Wrap getItem() in JSON.parse to retrieve and store as object.
const getTaskArrObj = JSON.parse(localStorage.getItem("data"));
console.log(getTaskArrObj);

Remove item

Delete a specific item from local storage

// Syntax
localStorage.removeItem()

// Todo app example
localStorage.removeItem("data");

Clear

// Syntax
localStorage.clear()

Delete all items from local storage

Canvas

W3 full canvas reference

// you can add a canvas element anywhere on an HTML page
 <canvas id="myCanvas" width="300" height="150"></canvas> 

Accessing a canvas

You can access a canvas with the DOM method getElementById

const myCanvas = document.getElementById("myCanvas");
}

.getContext("2D") draw in a canvas

To draw in the canvas you need to create a 2D context object

const ctx = myCanvas.getContext("2d");

.fillRect() draw a rectangle

After creating a 2D context object you can draw a rectangle with fill rect. Syntax: ctx.fillRect(x, y, width, height)

ctx.fillRect(20, 20, 150, 100)`

.fillStyle() adding colors

fillStyle() sets the fill color of a drawing object.

ctx.fillStyle(red);
ctx.fillRect(20, 20, 150, 100)

Canvas width

The innerWidth property is a number that represents the interior width of the browser window.

canvas.width = innerWidth;

Canvas height

The innerHeight property is a number that represents the interior height of the browser window.

canvas.height = innerHeight

Creating a canvas

You can use document.createElement() to add a new canvas to an HTML page

const myCanvas = document.createElement("canvas");
document.body.appendChild(myCanvas);
const ctx = myCanvas.getContext("2d");

ctx.fillStyle = "red";
ctx.fillRect(20, 20, 150, 100);

requestAnimationFrame(callback)

function repeatOften() {
  // Do whatever
  requestAnimationFrame(repeatOften);
}
requestAnimationFrame(repeatOften);

fetch API

fetch()

Make GET, POST, PUT, PATCH requests GET request to a URL for a JSON file with information Returns a Promise: a placeholder that will be filled or rejected - if fulfilled resolves to a Response object

fetch('url');
fetch('https://cdn.freecodecamp.org/curriculum/news-author-page/authors.json');

.then()

Access a response You can chain to a fetch request Takes a callback: e.g. res as a parameter (response) Chain twice to convert Response to JSON and access data.

fetch('url').then((res) => res)

fetch('url').then((res) => res.json()).then((data) => {
  console.log(data);
})

.catch()

Asynchronous method which can be used to handle errors Useful in case the Promise gets rejected

fetch('url')
  .then((res) => res.json())
  .then((data) => {
    console.log(data);
  }).catch((err) => {console.error(`There was an error: ${err}`)})

try…catch()

The try block is designed to handle potential errors The code inside the catch block is executed if an error occurs

try {
  const name = "freeCodeCamp";
  name = "fCC";
} catch (err) {
  console.log(err); // TypeError: Assignment to constant variable.
}

await (keyword)

The await keyword waits for a Promise to resolve and returns the result - .fetch() returns a Promise so it can be used here - .json() returns a Promise so it can be used here

const example = async () => {
  const data = await fetch("https://example.com/api");
  const dataJ = await data.json();
  console.log(data);
}

.json()

The data from a GET request is not usable at first You can use .json() method on a Response to parse into JSON You can view the .json() in the response prototype in the browser

Destructuring json data

Syntax depends on whether desctructuring array or object

The forum leaderboard exercise fetches a url for latest posts - This returns an object which includes a topic_list object and users array - The topic_list object contains a topics array - The topics array contains objects - We can use map & destructuring to access object items

// we fetch a url within a try, and call showLatestPosts
const res = await fetch(forumLatest);
const data = await res.json();
showLatestPosts(data);

const showLatestPosts = (data) => {
  const { topic_list, users } = data;
  const { topics } = topic_list;
  postsContainer.innerHTML = topics.map((item) => {
    const { id, title, views, posts_count, slug, posters, category_id, bumped_at } = item;
  });
};

Reference patterns

Pyramid with .push .unshift and loops

const character = "!"; const count = 10; const rows = [];
let inverted = false; let result = ""

function padRow(rowNumber, rowCount) {
  return " ".repeat(rowCount - rowNumber) + character.repeat(2 * rowNumber - 1) + " ".repeat(rowCount - rowNumber);
}

for (let i = 1; i <= count; i++) {
  if (inverted) {
    rows.unshift(padRow(i, count));
  } else {
    rows.push(padRow(i, count));
  }
}

for (const row of rows) {
  result = result + "\n" + row;
}

console.log(result);

Returning true with if using && and ||

function hasPlayerWonTheRound(player, computer) {
  return (
    (player === "Rock" && computer === "Scissors") ||
    (player === "Scissors" && computer === "Paper") ||
    (player === "Paper" && computer === "Rock")
  );
}

Using an object to count occurrence

The Set object can then be used to check if there was only one value.

const numbersArr = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4];
const counts = {};
numbersArr.forEach((el) => {
  if (counts[el]) {
    counts[el] += 1;
  } else {
    counts[el] = 1;
  }
})
if (new Set(Object.values(counts)).size === 1) {
  return null;
};

In the Statistics calculator exercise step 36 they use the following pattern:

const getMode = (array) => {
  const counts = {};
  array.forEach(el => counts[el] = (counts[el] || 0) + 1)
  if (new Set(Object.values(counts)).size === 1) {
    return null;
  }
}

A function that takes an array as a parameter

// array
const locations = [
{
  name: "town square",
  "button text": ["Go to store", "Go to cave", "Fight dragon"],
  "button functions": [goStore, goCave, fightDragon],
  text: "You are in the town square. You see a sign that says \"Store\"."
},
{
  name: "store",
  "button text": ["Buy 10 health (10 gold)", "Buy weapon (30 gold)", "Go to town square"],
  "button functions": [buyHealth, buyWeapon, goTown],
  text: "You enter the store."
}
];

// function declaration
function update(location) {
button1.innerText = location["button text"][0];
button2.innerText = location["button text"][1];
button3.innerText = location["button text"][2];
button1.onclick = location["button functions"][0];
button2.onclick = location["button functions"][1];
button3.onclick = location["button functions"][2];
text.innerText = location.text;
}

// function call
function goTown() {
update(locations[0]);
}

Create / update an object based on .forEach loop on an array

This is kind of updating an empty object just by bracket notation reference to an element of an array we use forEach on.

We need to use || 0 on the right hand side, as it will give undefined error if dessert not already found.

1 Created a JavaScript class ‘shoppingCart’ - Using a constructor() this included an empty array this.items = [] 2 Created a method under this to add items which takes id and product - It checks by id if the product exists in a product array (with object incl. id, name, price, category) - If it does it adds it to this.items (id, name, price, category) - We create a new object to track total count per product - We loop through this.items array of objects (dessert) and for each one - Add a new entry to totalCountPerProduct object based on dessert.id

  addItem(id, products) {
    const product = products.find((item) => item.id === id);
    const { name, price } = product;
    this.items.push(product);

    const totalCountPerProduct = {};
    this.items.forEach((dessert) => {
      totalCountPerProduct[dessert.id] = (totalCountPerProduct[dessert.id] || 0) + 1;
    })
  }

Theory

Call stack

In computer science, a stack is a data structure where items are stored in a LIFO (last-in-first-out) manner. If you imagine a stack of books, the last book you add to the stack is the first book you can take off the stack. Or an array where you can only .push() and .pop() elements.

The call stack is a collection of function calls stored in a stack structure. When you call a function, it is added to the top of the stack, and when it returns, it is removed from the top / end of the stack.

Recursion

A recursive function is a function that calls itself over and over.

Const vs. let

Primitive data types like strings and numbers are immutable

leg age = 36;
age = 37;

Object freeze

const arr = Object.freeze([1, 2, 3]); const person = Object.freeze({ name: 'Hassan' }); const arr = [1, 2, 3] as const; // typescript