JavaScript – JS & the DOM

Creating and inserting elements

  • createElement()
  • insertAdjacentHTML()
const newElement = document.createElement('div');
newElement.classList.add('newClass');
message.innerHTML =  'My HTML content';

header.append(message); // or prepend, or before, or after.

message.remove(); // remove element

Other methods etc:

// Styles

message.style.backgroundColor = '#232323'; // use camelCase - sets inline style
getComputedStyle(message).height;

Number.parseFloat(getComputedStyle(message).height, 10) // Gets numeric value of height

document.documentElement.style.setProperty('--color-primary', 'orangered'); // Sets root style variables

// Attributes
myButton.alt; myButton.src; myButton.className;
myButton.getAttribute('customAttribute');
myButton.dataset.versionNumber // gets data-version-number

Smooth Scroll

const btnScrollTo = document.querySelector('.btn-scroll-to');
const section1 = document.querySelector('#section--1');

btnScrollTo.addEventListener('click', function(e) {
  const s1coords = section1.getBoundingClientRect();
}

window.scrollTo({
 left: s1coords.left,
 top: s1coords.top + window.pageYOffset);
 behaviour: 'smooth'
});

// MODERN BROWSERS
section1.scrollIntoView({behaviour: 'smooth'});

// Viewport
document.documentElement.clientHeight document.documentElement.clientWidth

More Events & EventHandlers

const mouseEnterFunction = function(e) {// do something}

message.addEventListener('mouseenter', mouseEnterFunction); // allows you to add multiple event listeners.

// Alternatively - old version
message.onmouseenter = function (e) {};

// Remove
setTimeout(() => message.removeEventListener('mouseenter', mouseEnterFunction), 2000);

Bubbling & Capturing

Event is initially captured at root. Capturing phase goes through all the child elements to the target phase and the passes back (bubbling phase).

JavaScript: Timers

There are two types of timers: setTimeout and setInterval.

setTimeout()

setTimeout( () => console.log('show this after 3 seconds'), 3000);

The code will continue to be read after the setTimeout, it will run the timer in the background while it continues the code.

Timer can be cleared before executed using clearTimeout()

setInterval()

Creates a timed loop.

setInterval(function () {
  const now = new Date();
  console.log(now);
}, 1000);

Example Timer countdown

const startLogoutTimer = function() {
  const tick = function() {
    const min = String(Math.tunc(time / 60).padStart(2,0);
    const sec = String(time % 60).padStart(2,0); // remainder literal

    // In each call, print the remaining time to UI
    labelTimer.textContent = `${min}:${sec}`;

    // when - seconds, stop timer and log out user
    if(time === 0) {
      clearInterval(timer)
    }

    // Decrease by 1s
    time--;

  }

  // Set time to 5 minutes
  let time = 100;
  
  // Call the timer every second
  tick()
  const startTimer = setInterval(tick , 1000}
}

JavaScript – Dates

New Date()

Get’s current date, or pass a string or seconds passed since UNIX time 1/1/70 01:00

Date components have methods

const future = new Date(2037, 10, 19, 15, 23)
future.getFullYear();
future.getMonth();
future.getDate();
future.getDay();
future.getHours();
future.getMinutes()
future.getSeconds()
future.getISOString()
future.getTime(); // get timestamp

future.setFullYear(2040) // Modifies object

Operations with Dates

Convert date to a Number (+ or Number()) you can then perform maths on dates.

const calcDaysPassed = (date1, date2) => Math.abs(date2 - date1) / (1000 * 60 * 60 * 24);

Internationalizing Dates (Intl)

const now = new Date();
const options = {
 hour: 'numeric',
 minute: 'numeric',
 day: 'numeric',
 month: 'long',
 year: 'numeric',
 weekday: 'long'
}

new Intl.DateTimeFormat('en-US', options).format(now); // use ISO language code

const locale = navigator.language // Get ISO code from user's browser

Internationalizing Numbers (Intl)

new Intl.NumberFormat('en-US').format(num);

const options = {
  style: 'currency', // unit percent or currancy
  unit: 'celsius',
  currency: 'EUR'  // Not defined by locale so needs to be implied
  useGrouping: false // removes seperators
}

Javascript – Numbers

Numbers are binary base in javascript

+ works the same as Number():

Number('23')
+('23)

Number.parseInt(string, redex)

Turns string into integer if it starts with a number (removing any other characters in the string. Redex not neccessary

Number.parseInt('20px', 10) // returns 20
Number.parseInt('e20', 10) // returns NaN

Number.parseFloat(string, redex)

parseFloat is used if the number has a decimal place.

Number.isNaN(string)

Boolean to check if it is not a number

Number.isFinite(), Number.isInteger()

Better to use than isNaN. To check if it is a number as it can check if numbers are divided by 0.

Math

Math.sqrt*(); Square root
Math.max(array) // Returns maximum number in array (does string to number converstion)
Math.min(array) // Returns minimum in array

Math.PI + Number.parseFloat(radius) ++2)

//Random
Math.trunc.random() * 6) + 1); // gets a number between 1 and 6

// Random Function
const randomInt = (min, max) => Math.floor(random() * (min-max + 1) + min)
console.log(randomInt(10,20));

// Rounding Integers
Math.trunc(23.3) // removes the decimal values
Math.round() // round to nearest
Math.ceil() // round up
Math.floor() // round down

// Rounding decimals
(value).toFixed(nummber of decimal places) // !!! Returns String
+(2.345).toFixed(2) // returns 2.34

Remainder operator

returns the remainder of a division

5 % 2 // returns 1

Numeric Seperator

Use _, js will ignore it and convert the number fully.

BigInt

JS has 53 bytes for integers, so there is a limit to the highest number that can be used

Number.MAX_SAFE_INTEGER

Use n at the end of a very lager number or use BigInt()

Cannot mix BigInts with regular numbers (except on < or >) (convert number to bigInt). Math operations will not work either.

JavaScript – Array Methods

.slice

Works the same as for strings. Specify start from and start to in parameters. CAN ALSO BE USED to return a shallow copy of array.

let arr = ['a', 'b', 'c', 'd', 'e'];

//SLICE
arr.slice(2); // Returns c, d, e
arr.slice(2,4); // Returns c, d
arr.slice(-2); // Slices from rear (returns last two) d e
arr.slice(-1); // Returns last (e)
arr.slice(1, -2); // returns b, c
arr.slice; creates shallow copy of orignal array (same as [...arr]

.splice()

Same as above but MUTATES the original array (returns mutated array)

.toSpliced()

Non-destructive method of the above

.reverse()

Reverses the original array (mutates).

.toReversed()

Non-destructive method of reverse.

.concat(array)

Concatonated two arrays (as […arr, arr]). Doesn’t mutate original arrays.

.join(‘-‘)

Turns the array into a string joined by optional parameter

let arr = ['a', 'b', 'c', 'd', 'e'];
arr.join('+'); // Returns string of a+b+c+d+e

.at() (ES6)

Works just the same as [] however can use negative index (also works on strings):

// Get last array element.
arr.at(-1); works the same as arr[arr.length - 1]

forEach

Used for looping through arrays. Requires a callback function.

Passes the element, index and entire array

arr.forEach(function (element, index, array) {
 // Do something
});

YOU CANNOT BREAK OUT OF THE forEach LOOP. Use For of instead.

Works also with Maps and Sets. (will not return key of sets because there isn’t one).

.map()

Map loops through array and applies a function and builds a brand new array (no side effects).

const movements = [200, 450, -400, 3000, -650, -130, 70, 1300];

const eurToUsd = 1.1;

const movementsUSD = movements.map( function(mov) {
  return mov * eurToUsd;
}) // Functional programming

//Arrow function version.
const movementsUSD = movements.map(mov => mov * eurToUsd); 

// EXAMPLE 2
const movementsDescriptions = movements.map((mov,i ) => {
  `Movement ${i + 1}: You ${mov > 0 ? 'deposited' : 'withdrew'} ${Math.abs(mov)}`
});

// EXAMPLE 3
const user = 'Steven Thomas Williams';
const username = user
  .toLowerCase()
  .split(' ')
  .map(word => word[0])
  .join('');
console.log(username); // returns 'stw'

.filter(condition)

Will go through and return a new array containing all elements in original array the meet the specified test condition.

const deposits = movements.filter(function(mov){
  return mov > 0;
}); creates a new array with only deposits

const withdrawals = movements.filter(mov => mov < 0); // returns new array with only negative values.

.reduce(condition)

Boils all array elemements down to one single value (like adding all elements together.

// accumalator -> SNOWBALL
const balance = movements.reduce(function (acc, cur, i, arr) {
  return acc + cur;
}, 0); // 0 defines the start value of the accumalator

console.log(balance);

// simplified arrow function:
const balance = movements.reduce((acc,cur) => acc + cur, 0);


// Maximum values
const maxValue = movements.reduce((acc, mov) => acc > mov ? acc : mov, movements[0]); // Returns the highest amount in the array

.find(condition) ES6

Needs a callback function that returns a boolean. It will loop until the first true value is returned and will return the first element only.

const account = accounts.find(acc => acc.owner === 'Jessica Davis'); // returns the first object that returns a true value. 

.findIndex(condition) ES6

Needs a callback function that returns a boolean. It will loop until the first true value is returned and will return the first element index only.

.findLast(condition) & .findLastIndex(condition) ES2023

Same as above but returns last value / index.

.some(boolean condition)

Similar to includes but includes a condition instead rather than a specific value

.every(boolean condition)

Method returns true if every element in array meets the condition.

array.flat(depth)

No callback required, flattens the array.

array.flatMap(callback)

No callback required, Creates a map and then flattens the array.

Sorting Arrays

Sorting Arrays
arr.sort() // sorts in alphabeltical (converts to strings) - MUTATES original

// To sort in numerical strings ascending order (loops through array)
// return < 0, A, B (keep order)
// return > 0, B, A (switch order)
arr.sort((a, b) => {
 if (a > b) return 1;
 if (b > a) return -1;
}); //

// For numbers. simplified
arr.sort(( a,b ) => a - b);

// Non destructive method
const newArray = arr.toSorted(( a,b ) => a - b);

Array Grouping (Object.groupBy)

Creates an Object grouping elements as per callback condition.

const groupedArr = Object.groupBy(arr, callback => callback > 0 ? 'positives' : 'negatives') // 

Generating arrays programatically

const arr = new Array(7) // creates 7 empty slots
arr.fill(1) // fills the array with 1s
arr.fill(1, 3) // starts from index 3 [ , , 1, 1, 1, 1]
arr.fill(1, 3, 5) // fills from index 3 until index 5


const arr = Array.from({length: 7), () => 1); // creates array full of 1s


const inc = Array.from({length: 7}, (cur, i) => i + 1); // creates incrementing array

// Create an array of 100 random dice rolls
const diceRolls = Array.from(
  { length: 100 },
  () => Math.floor(Math.random() * 6) + 1
);
console.log(diceRolls);

.with(i, val)

Creates a new array copy but replaces the element at index i with new value

When to use each method?

To mutate original

Add to original

  • push (end)
  • unshift (start)

Remove from original

  • pop (end)
  • shift (start)
  • splice (any)

Others:

  • reverse
  • sort
  • fill

A new array based on original

Same length as original

  • map (loop)
  • filter (using condition)
  • slice (taking portion)
  • with (with one item replaced)
  • flat (flattened)
  • flatMap (flattened into a map)
  • toReversed
  • toSorted
  • toSpliced (with deleted items)
  • concat (joining two arrays)

An array index

  • indexOf (based on value)
  • findIndex / findLastIndex (based on test condition)

An array index

  • find
  • findLast

I want to know ifd array includes…

  • includes (based on value)
  • some (based on test condtion (boolean)
  • every (based on test condtion (boolean)

I want a new string

  • join (based on seperator)

To transform to value

  • reduce (based on accumulator – boils down array to a single value)

to just loop over the array

  • forEach (does not create a new array, just loops over it)

Other useful tools

  • Object.groupBy – Grouping an array by categories
  • Array.from – Creating a new array from scratch
  • new Array(n) – create a new array from scractch with n empty positions (use with .fill method)
  • […arr1, …arr2] joining arrays
  • [… new Set(arr)] Creating a new array containing unique values from arr
  • [… new Set(arr1).intersection(new Set(arr2))] – Create a new array containing unique elements that are present in both arr1 and arr2.