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
- It's common practice to end statements with semicolons
;
- To access chrome & firefox browser tools on Mac use
Cmd+Opt+I
- Single-line comments can be written with
//
- Multi-line comments can be written with
/* example comment */
- JavaScript uses dot notation to access properties:
button.onclick
Loading JavaScript in HTML:
- Write JavaScript in a file called script.js
- Place script.js in the same directory as the main html file
- Insert HTML
<script src="./script.js"></script>
before
</body>
in the html file
- This is added at the end so the browser can read all HTML elements
first
Document object model (DOM)
A web application programming interface (API) used to build
websites
- Actually consists of multiple individual APIs that work
together
- Represents web pages in memory so that programs can change the
document structure, style, and content
- This is an ‘object orientated’ representation of the web page
- This representation of the web page can be modified by a scripting
language such as JavaScript
Structured as a logical tree where:
- Each branch of the tree ends in a node
- Each node contains objects: which can represent properties, methods,
events etc.
- It’s common to refer to nodes in the DOM as elements, but not every
node is an element
API
An API is a way for two or more programs to communicate. The DOM
includes multiple APIs, for example:
- Core DOM: entities describing any document and objects within
- HTML DOM API: support for representing HTML documents to the core
DOM
- SVG API: support for representing SVG documents
Interfaces
The DOM is made up of interfaces. Each of these interfaces has
different methods. For example the interfaces include:
- Document
- DocumentType
- DocumentFragment
- Element
- CharacterData
- Attr
Some examples of common interfaces and methods are:
- Document interface, querySelector method
const constName = document.body.querySelector(".className");
- Element interface, addEventListener method
const setText = document.body.querySelector("#set-text");
setText.addEventListener("click", () => {}
- Node interface, textContent method:
constName.textContent = "Sample text to update";
The relationship between objects and interfaces that are implemented
in the DOM can be confusing.
- The form element gets name from HTMLFormElement interface, but class
from HTMLElement interface
- Many objects implement several different interfaces
Document
- Any markup based resource
- From short static docs to long essays to reports with
multimedia
- Each document is represented as a node tree. Some nodes can have
children
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:
- Document
- Doctype: html
- Element: html class=“e”
- Element: head
- Text: (carriage return)
- Element: body
- Text: why yes. (carriage return)
Node
- Every object located within a document is a node of some kind
- In an HTML document, an object can be an element node, a text node,
an attribute node
- Nodes can have event handlers attached to them
- These can be executed based on triggered events
NodeList
- An array of elements
- Accessed by index:
- dot notation:
list.item(1)
- bracket notation:
list[1]
- The method
document.querySelectorAll()
returns a
NodeList
Node tree
- Objects that implement node
NameNodeMap
- Like an array, but items are accessed by names or index
Element
- Refers to a node of type element
- Elements can use different interfaces
- DOM element interface
- More basic Node interface
- HTML element interface
- Others e.g. HTMLTableElement interface
Common elements and methods include:
document.querySelectorAll()
document.createElement()
Element.innerHTML
Element.setAttribute()
Element.getAttribute()
HTMLElement.style
Node.appendChild()
window.onload
window.scrollTo()
Attribute (Atr)
- An object reference that exposes a special interface for
attributes
- Method: createAttribute() returns attributes
Event
- Events are dispatched to objects to signal an occurrence
- For example network activity or user interaction
- Implement EventTarget interface (can therefore call
addEventListener())
Commands / keywords
return
- Functions can return a single value
- This value can be a collection containing multiple items
- Return also ends the current function (breaks out of)
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
- Surround by double quotes
"
, single quotes
'
or backticks
- Use escape
\
or single quotes to include double quotes
in a string
- Variables can be concatenated into strings using the concatenation
operator +
- There is also the concat() method
- Variables/text can be appended to existing strings using the append
operator +=
- The special escape sequence “” is interpreted as a new line
// 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
- For variable assignment numbers do not need quotes
"
or
'
- You can carry out mathematical operations (+, -, *, /)
- Note that the input field type=“number” has the following
properties:
- Allows special characters such as
.
+
and
e
- Users can input floats such as
2.2
, equations like
2e+3
, or even just e
let count = 8;
console.log(count + 1);
Binary numbers
- base-2 number system: 0 and 1
- binary digits 0 and 1 are called bits
- 0 represents false
- 1 represents true
Arrays
- Arrays are denoted by square brackets
[ ]
- Multiple values/elements are separated by commas
,
- Access element values with bracket notation and index number
[0]
- Index numbers start at zero (zero-based indexing)
- Arrays are considered mutable - you can change values at an index
- Both value and data type e.g. string to number
- Changing values at an index is called mutation
arrayName.length
returns the Length of an array
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
document.querySelectorAll
returns a
NodeList
, which is array-like
- Use array method .from() that accepts an array-like and returns an
array
- Helpful when you want access to more robust array methods
<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:
- Real life object: car.name = fiat, car.model = 500, car.weight =
850kg, car.color=white
- Real life car has methods like; car.start(), car.drive(),
car.brake(), car.stop()
- Car objects have the same properties, but values differ from car to
car
- Car objects have the same methods, but methods are performed at
different times
JavaScript objects:
{ key: value }
- Non-primitive data types
- Contain properties in the form of key:value pairs (sometimes
referred to as name:value)
- Similar to arrays, except instead of indexes, use properties to
access data
const car = {type: Fiat, model: "500", color: "white"};
// common practice to use const
Key points:
- Objects are containers for Properties and Methods
- Methods are Functions stored as Properties
- Properties can be primitive values, functions, or even other
objects
- (All JavaScript values, except primitives, are objects).
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.
- Property: fullName
- Value: function() {return this.firstName + ” ” + this.lastName}
- Example:
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
- Displaying a javascript object will display
[object Object]
- Solutions to display objects include:
- Displaying the Object Properties by name
- Displaying the Object Properties in a Loop
- Displaying the Object using Object.values()
- Displaying the Object using JSON.stringify()
// loop method
let text = "";
for (let x in person) {
text += person[x] + " ";
};
// Object.values() method
const myArray = Object.values(person);
Other object notes
- If the object name or key has more than one word it must be
surrounded by quotes
- Values can be defined as an array
- With objects stored in arrays either bracket notation or dot
notation can be used
arrayName[”Object name”]
arrayName.ObjectName
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
- As an alternative to dot notation
- Allows you to unpack values from arrays and objects.
let { property1: variable1, property2: variable2 } = object;
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: ?
- Optional chaining will return undefined instead of throwing an
error
- You should not use the when the value will not be
null
or undefined
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
- In JavaScript, a Boolean can be either
true
or
false
. These are not strings
- A truthy value is a value that is considered true when evaluated as
a boolean
- “false” evaluates as truthy, while false evaluates as false
- It is standard practice to prefix a boolean variable with
is
or has
- falsy values include
false
, 0
,
""
, null
, undefined
,
NaN
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
- A variable points to a specific memory address
- Use
let
for when you may reassign the value
- Use
const
when you do not plan to reassign values
const
will tell JavaScript to throw an error if you
accidentally re-assign it
- A
const
variable cannot be uninitialised
i.e. const exVariable;
- Use camelCase for variable names
- The first word in lowercase
- The first letter of every following world capitalised
- A variable declared without a value will have the value
undefined
- Variable names can include letters, numbers, dollar signs, and
underscores
- Variable names cannot contain spaces and must not begin with a
number
=
is used as the assignment operator
- Initialization is the assignment of a value at declaration
- You can assign the value of a variable to another variable.
Guidelines:
- Always declare variables
- Always use
const
if the value should not be
changed
- Always use
const
if the type should not be changed
(Arrays and Objects)
- Only use
let
if you can’t use const
- 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
- Where a variable is declared determines where it can be used
- The 1st scope is global scope:
- It applies to those declared outside of specific blocks
- The code block within a function can access global scope
variables
- Next is block scope or local
scope:
- It applies to those declared inside a block of code
- They are available only within that block
- If you try to access them outside their scope you get a reference
error
// 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
- Create a constant and assign to variables
- Several can be checked at once using logical OR (see section
later)
- Use an if statement with the variable to check
- True would indicate the variables have changed
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
- A property is an association between a name (or key) and a
value
- Note a property’s value can be a function (these properties are
methods)
For standard dom elements like type and id you can use: -
element.type = “text”; - element.id = “id”;
el.innerText
- Sets or gets the text between the start and end tags of the
object
- Only the text content of the element and it’s children
- Without CSS hidden text spacing and tags except
<script>
and <style>
elements
<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;
Replaces existing content of an element with new content
Sets or gets the text content of the element, including all
spacing and inner HTML tags
In RPG exercise: used to display the ☠ emoticon properly on the
page.
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
- With variables assigned using the getElementById method you use
variableName.value to access the value from html
node.textContent
- Sets the text of a node and allows you to set or retrieve the text
content of an HTML element
- Gets content of all elements including
<script>
and <style>
- In contrast innerText only gets human readable elements
- Returns every element in a node. In contrast innerText is aware of
styling and won’t return text of ‘hidden’ elements
<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
- Difference vs. parentNode, is that parentElement it returns null if
the parent element is not an element node
// 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.
- Array like, but not an array. You can use Array.from() to convert to
array.
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
- Allow other code to run while waiting for an operation to
complete
- They do not block the entire execution of the program
- Useful when dealing with tasks that might take some time
- Fetching data from an API
- Reading files
- Interacting with databases
- Commonly used with Promises (may be available now, future,
never)
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")
- Available on the document or any element object
- Select the first element that matches one or more CSS selectors
- Returns null if not found
- (Thought - does not seem to support .value - I used getElementById
instead)
- Selectors:
- Universal:
document.querySelector('*')
will select the
first element in the document
- elementName:
document.querySelector('h1')
will select
the first h1 in the document
- className:
document.querySelector('.menu-item')
will
select the first element with the ‘menu-item’ class
- id:
document.querySelector('#logo')
will select the
first element with the ‘logo’ id
- attributes:
document.querySelector('[autoplay]')
will
select the first element with the autoplay.
// 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")
- Returns a nodeList
- A
NodeList
is an array-like object, so you can access
the elements using bracket notation.
- e.g.
example[0]
for the 1st item
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
- Grouping selectors:
- div and p:
document.querySelectorAll('div, p');
find
all div & p elements
- Combinators examples:
- All anchor elements inside a paragraph element:
document.querySelectorAll('p a');
- All li elements inside a ul:
document.querySelectorAll('ul > li');
- All li elements directly inside a ul with class .nav:
document.querySelectorAll('ul.nav > li');
- All elements that follow the p element, immediately or not:
document.querySelectorAll('p ~ a');
- all a elements that direct follow a h1:
document.querySelectorAll('h1 + a');
- Pseudo-classes: syntax
element: state
- li:nth-child(2) selects the second li element in a list
document.querySelectorAll('li:nth-child(2)');
- Pseudo- elements: syntax:
::
- p::first-line matches the first line of all p elements
document.querySelector('p::first-line');
Document
get element by id: document.getElementById('id')
- Access/return an HTML element by using the
id
property
- Element IDs are unique so this is a useful way to get access to a
specific element quickly
- Returns an element object, or
null
if no matching
element is found
- You can assign to variables and use
variableName.value
to access element values
- Only available as a method of the global document object, id is
unique so there is no need for a local object
<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
- The style property is used to access the inline-style of an
element
- The display property is used to set the visibility of an
element
// 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()
- Arg1: String specifying position of inserted element
e.g. ‘beforeend’ inserts element as last child of specified element
- Arg2: String containing HTML to be inserted
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
- The classList property has the add method which accepts a string
representing a class to add to an element
//music player example
playButton.classList.add(playing);
Removing a
class from an element: classList.remove
- The classList property has the remove method which accepts a string
representing a class to remove from an element
paragraphElement.classList.remove('hide');
Toggle classes
on an element: el.classList.toggle()
- Will add a class to an element if not present, will remove if the
class if it is present
element.classList.toggle("class-to-toggle");
Set element
attribute .setAttribute(name, value)
Note might be easier to use
e.g. element.type = "text";
- Sets a new value to an attribute
- If the attribute doesn’t exist it is created first
- You can also use element.id = value and element.ariaLabel =
value
// 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”)
- Removes an attributes, does not have a return value
// syntax
element.removeAttribute(name)
// music player example
playlistSongElements.forEach((songEl) => {
songEl.removeAttribute("aria-current");
});
Object freeze
object.freeze()
- Ensure you can’t modify an object by adding or removing
properties
// 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
- An object can borrow a method from another 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()
- Cancels an event if cancellable
- Useful for:
- Clicking on “submit”, but preventing it from submitting a form
- Clicking on a link, but prevent the link from following a url
// 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
- You can chain methods together
- Example using join on the output of map
array.map().join();
// 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)
- Built into browsers. Displays pop-up message to the user
- The message is passed as the argument
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
- A callback function
- A number representing time in milliseconds to wait before executing
the callback function
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
- Computers store decimals as binary fractions
- 0.1 + 0.2 does not equal 0.3
Number constructor:
Number()
- Converts a value to a number
- Returns ‘Not a Number’ if the value passed cannot be converted to a
number
Number('10'); // returns the number 10
Number('abc'); // returns NaN
// calorie counter example
calories += Number(currVal);
.toFixed()
- Converts a number to a string
- Rounds the string to a specified number of decimals
- Use parseFloat() to turn back to decimal for comparisons etc.
let num = 5.56789;
let n = num.toFixed(2);
Even or odd
- You can do this by checking the remainder of division by 2
// check if array length is even
arr.length % 2 === 0;
// check if array length is odd
arr.length % 2 === 1;
isNaN()
- function to check ‘is not a number’
- Returns true if it evaluates to NaN
- Equality can’t be used to check if numbers == NaN (NaN does not
equal NaN)
- You can use the isNaN() method or !isNaN() which returns
true/false.
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
Math.random()
: generates a random number from 0
(inclusive) to 1 (exclusive)
Math.floor()
: rounds a given number down to the nearest
integer
Math.abs()
: returns the absolute value of a number
Math.min()
: get the smallest number from a series of
numbers
Math.max()
: get the largest number from a series of
numbers
Math.pow(base, exponent)
: calculate exponents and
square roots (as inverse exponent)
Math.sqrt()
: calculate square root
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
- A mathematical operator that appears between two operands
- e.g. 2 + 1
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),
Math.random()
generates our random number between 0 and
≈ 0.9
- Before multiplying it, it resolves the part between parenthesis
(myMax - myMin + 1)
because of the grouping operator
( )
.
- The result of that multiplication is followed by adding
myMin
and then “rounded” to the largest integer less than
or equal to it (eg: 9.9 would result in 9)
(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:
/
: surrounds a regex expression
()
capture group
(?:)
non capture group
[]
character class - search for individual characters
incl. OR
Adjusters:
|
alternate sequence: match text on left or right
?
zero or one times (optional)
?
changes preceding adjuster to lazy??
+
one or more times
*
zero or more
{N}
exactly N number of times
{N,}
N or more number of times
{N,M}
between N and M number of times
*?
zero or more but stop after first match
^
anchor: assert pattern matching starts at beginning
of string
- When used inside square brackets it means negation
$
anchor: assert pattern matching at the end of
string
Characters
.
any
\n
newline
\t
tab
\s
whitespace (includes nd and a few others)
\S
any non whitespace
\w
any word (\w
any non word)
\b
word boundary (\b
any non word
boundary)
\
the literal character
\d
: shorthand for digit
\
: escape
\+
: As + is a special character you need to escape to
match it
\.
: As period is a special character you need to escape
to match it
\/
: If you need to use / you have to escape before
it
Flags to alter behaviour (add after closing /
):
- The
g
flag; “global”, continue looking after match is
found
- The
i
flag; “insensitive”, ignore capitalisation.
Pattern collections:
[A-Z]
[a-z]
[0-9]
[asdf]
[^asdf]
[0-9A-Z]
[^a-z]
Examples:
[+/]
would match either + or /
yes|no
: will match yes or no
colou?r
: u is optional
([A-J])([1-9][0-9]?)
: second 0-9 is
optional
H.*llo
: will match “Hillo” to “Hello” to
“Hellollollo”
\b\w+\b
: This is a string > “this”, “is”, “a”,
and “string”
Character class
[0-9]
can be used to match any digit between 0 and
9
[0-9]+
can be used to match multiple digits
[aeiou]
can be used to match any character in the list
a,e,i,o,u
[a-z]
matches any character between a and z
Capture group
/h(i|ey) camper/
matches hi camper or hey camper and
would capture i or ey
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}
- Template literals allow you to interpolate variables directly within
a string
- Template literals are denoted with backticks `` as opposed to single
or double quotes
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
- Divide a string into a substring based on a specified separator,
return in array.
- The separator dictates where split should occur
- An empty string will into an 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
- arg1: character sequence to replace as a string or regex
pattern
- arg2: replacement character sequence
- 2nd argument can be a callback function
// 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)
- Accepts a regular expression
- Test if a string matches a pattern and return a boolean value
// 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.
- Takes at least one argument (a string)
- Returns an integer or NaN (not a number)
parseInt(2.2) // 2.2
parseInt("2e3") // 2
parseInt("e") // NaN
parseFloat()
Converts a string to a floating point number
- Leading whitespace is ignored
- NaN
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
- Use an object
- .forEach() through the array and update the object count
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
- Modifies an array by removing, replacing or adding elements at a
specified index
- Returns removed elements
- Up to three arguments
- Arg1: mandatory index at which to start
- Arg2: no. of items to remove
- Arg3: optional replacement item
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
- Returns 1st element in an array that satisfies the testing
function
- If no element satisfies condition, returns
undefined
- Other find methods:
- if you need the index use findindex()
- if you need index of a value use indexOf()
- If you need to check a value exist use includes()
- To find any element that satisfies testing function use some()
- To find all elements that satisfy testing function use filter()
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
- Returns 1st index at which a given element is found, or -1 if not
present
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
- Copy all elements from one array into another
- Concatenate multiple arrays into one
- You can use spread to convert collections (array like objects) to
arrays
// 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
- Iterate through an array and return a new array
- Does not modify input array
- New array with items separated by commas
- Takes a function as an argument (callback function)
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)
- Calls a function once per array element
- Does not directly change the object it calls
- Unlike map does not return anything
- Not executed for empty elements
- Arguments:
- function(): a function that runs for every element in the array
- currentValue: required (value of the current element)
- index: optional (index of the current element)
- arr: optional (array of the current element)
- thisValue: optional, default: undefined (a value passed as it’s
‘this’ value)
// 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
- Concatenate elements of an array into a single string
- Default separator is a comma, or specify desired separator as
argument
- Tips:
- Useful after using map with template literals to remove commas
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
- returns true if it finds an element where function tests as
true
- does not modify array
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:
- Syntax Uses two implicit returns!
- Starts with constant declaration for function:
const isSpam = (msg) => function
- Where function is array.some() with argument that is implicit
return:
denyList.some((regex) => regex.test(msg))
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
- Arg1: callback function
- param1: accumulator
- param2: current element
- Arg2: initial value of accumulator (defaults to 1st element)
// 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
- Shallow copy of an object: properties share the same references
- As a result, when you change either the source or the copy,
- You may also cause the other object to change too.
// 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
- Unpack the arrays or objects into a bunch of variables (copies)
- Does not modify the array
- Works with any iterable on the right side of the
=
- Consider it as similar to calling
for..of
- For arrays use [] for objects use {}
// 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.
- Arg1: event - a string representing the event to listen for
(‘click’, ‘submit’, ‘ended’, ‘change’. ‘keydown’),
- full
list of events
- Arg2: a function
- This function may utilise the
e
event object mentioned
above.
// 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
- Determine what happens when someone clicks a button
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.
- e.g. spreadsheet cell change
keydown & key
- The event listener for ‘keydown’ listens for key presses
- You can console log the event object
e
and see the
‘key’ and ‘target’
inputNumber.addEventListener('keydown', (e) => {console.log(e)});
- Pressing enter on the input field the console shows:
- keydown Meta { target: input#number-input.number-input, key:
“Enter”, charCode: 0; keyCode: 13}
// 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
- Curly braces indicate section of code
- Functions are executed in sequence called, not sequence defined
- Parameters go inside the parenthesis (separated by commas)
- Primitive types (e.g., number, string, boolean, null, undefined,
symbol, and bigint) are passed by value.
- Non-primitive types (e.g., objects, arrays, functions) are passed by
reference.
// 1) define
function name() {
}
function name(parameter) {
}
// 2) call
name();
Return
keyword
and return values
- Functions can return values
- Use the function call directly as the value it returns or
- Assign function calls to variables to capture return values
const call = functionName()
// use console.log to check
call
value
- Within the function use the
return
keyword to define
what value to return
- This allows you to return a locally scoped variable outside of the
function
- Note return stops the execution of code inside a function or a block
statement
// 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
() -> {}
- Anonymous function expression (i.e. function does not have a name)
- To create a named arrow function assign to a variable
- Shorter and more concise way to write functions
- If just one parameter, you can omit parentheses
- If returning a single expression omit return & curly braces -
implicit return
// 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
- Callback functions assist with sequence control
- In JavaScript functions are first-class citizens, you can pass a
function as an argument to another function
- A callback is a function passed as an argument to another function
for execution later
- Allows a function to call another function
- When you pass a function as an argument, remember not to use
parenthesis
- A function that accepts a function as an argument is known as a
high-order function
- A callback function can be an anonymous function (without a
name)
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:
- Extract ‘if’ logic and wrap in a separate function
- Then pass as an argument
- In this case you could have separate function for isEven as well as
isOdd
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:
let oddNumbers = filter(numbers, (number) => number % 2 != 0)
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
- Take first arg and return a new function
- Take second arg and return a new function
- Take third arg etc. until all arguments are complete.
Notes
- Functions can only return one value
- Curried functions are chain closures
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
- A while loop accepts a condition, and will run until it is no longer
true
- Take care of potential for infinite loops
// syntax
while (condition) {
logic;
}
// example from RPG instructions
while (i < 5) {
}
For
For loops are declared with three expressions separated by
semicolons.
for (iterator; condition; iteration)
- iterator is a variable to control how the loop, commonly
i = 0
- condition tells how many times to loop, stops when false
- iteration tells loop what to do with iterator after each loop
// 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
- Compare an expression against multiple possible values and execute
different code blocks
- It’s best practice to include break; this tells the JavaScript
interpreter to stop interpreting statements
- The
default
case is executed when none of the previous
case conditions match the value being evaluated. It serves as a
catch-all for any other possible cases.
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
- Can be used as a one line if-else statement
- Ensures negative values are not returned
// 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()
- Sorts elements of an array
- Overwrites the original array
- Sorts elements as strings in alphabetical or ascending order
- By default converts numbers to strings and sorts alpha
- Optional argument: compareFunction
- Called with two arguments:
- a: The first element for comparison
- b: The second element for comparison
- Should return a negative, zero or positive value:
- The return value is a number whose sign indicates order of the two
elements
- JS interpreter has a sort algorithm built-in which calls comparison
function some number of times (quicksort, mergesort etc.)
// 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.)
Equality: ==
- Note that “0” == 0 will evaluate to true
Strict Equality for both value and type: ===
Not: !
Not equal value: !=
Not equal value or type: !==
Greater than: >
Greater than or equal to: >=
Less than: <
Less than or equal to: <=
And: && (x < 10 && y > 1)
Or: ||
- Will use the first value if it is truthy; anything apart from
NaN
, null
, undefined
,
0
, -0
, 0n
, ""
, and
false
. Otherwise, it will use the second value.
Nullish coalescing operator: ?? (returns the first argument if it
is not nullish; null or undefined)
Optional chaining character: ? (returns undefined if an object is
undefined or null instead of throwing an error)
Checks if value & type matches
// example 1: from RPG exercise
return Math.random() > .2 || health < 20;
// example 2: from RPG instructions
if (firstName === "Quincy" && lastName === "Larson") {
}
// example 3
if (num === 5) {
} else {
}
Date()
- Date constructor
Date()
- Use with the
new
operator to create a new Date
object
- If you subtract one date from another the result is in
milliseconds
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
- All modern browsers support the Web Audio API, which lets you
generate and process audio in web applications
- To play a mp3 file, use the
play()
method on the
audio
variable
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
<canvas>
defines a bitmapped area in an HTML
page
- the Canvas API allows JavaScript to draw graphics on the canvas
- can draw shapes, lines, curves, boxes, text, images
- with colors, rotations, transparencies, and other pixel
manipulations
- With canvas (0,0) is top left corner (i.e X goes right, Y goes
down)
// 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)
- Generates a call to perform an animation before loading of the
screen
- The callback must call requestAnimationFrame() to animate another
frame
- Call it once and it recursively calls itself
- Returns an ID you can use to cancel it
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
- Use .forEach array method to loop through an array
- Compare each array element with an object:
- If it exists increment by one
- If it doesn’t exist set equal to one
- This will give you an object with each array value as a single
key:value pair
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.
- Take care to avoid infinite loop
- Use a base case to stop the function from calling itself, good
practice to write this first.
- Use the recursive case to call itself
- What is the least amount of work to get closer to the base case
Const vs. let
- With variables the data is created first, then the variable label is
pointed to it
- Re-assignment
- is pointing the variable label to a new value
- It isn’t modifying the data, it detaches from existing data and
attaches to new data
- Let vs. const
- With const we create an indestructible link between the variable
name and data, but we can still modify the data.This is known as
mutation
- Adding an entry to an array
- Editing the key: value pairs in an object
Primitive data types like strings and numbers are immutable
- In the below example we aren’t editing 36 to become 37, we are
re-assigning the variable to a different number
leg age = 36;
age = 37;
Object freeze
- Can be used on objects and arrays to prevent all form of
mutations
- It’s shallow, it won’t freeze nested objects
const arr = Object.freeze([1, 2, 3]);
const person = Object.freeze({ name: 'Hassan' });
const arr = [1, 2, 3] as const;
// typescript