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 – 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.

Javascript – Working with strings

String methods

string.indexOf('') // gives position of needle in haystack
string.lastIndexOf('') // if there are multiple

sting.slice(i, ii) // remove the first i and last ii characters of string

string.slice(-i) // Save last i of string

string.slice(0, string.indexOf(' ')) // gets first word.

string.toLowerCase();
string.toUpperCase();
string.trim(); removes LEADING spaces and \n

const normalizedEmail = eMail.toLowerCase().trim();

// replacing
.replace(item, replacement) // replace first appearance
.replaceAll() // replaces all // ***New method***

.replace(/string/g, replacement) // replacing with global exoressions

// Booleans
string.includes()
string.startsWith()
string.endsWith()


//Split and join
console.log('a+lovely+string'.split(+)) // returns an array
const [firstName, lastName] = "Duncan Samwell".split(' ') // creates an array
const newName = ['Mr.' firstName, lastName].join();

//Capitalize function
const capitalizeName = function(name) {
 const names = name.split(' ');
 for (const n of names) {
  n[0].toUpperClass() + n.slice(1);
  n.push(n.replace(n[0], n[0].toUpperCase());
 }
}

//Padding
string.padStart(n, p) // fill string with p until entire string is length of n
string.padEnd(n, p)

// Example for Credit Card
const maskCreditCard = function(cc) {
 const l = cc.length;
 const lastFour = cc.slice(-4);
 return lastFour.padStart(l, '*');
}


//repeat
string.repeat(x) // repeat x amount of times

String Methods Practice

/*
///////////////////////////////////////
// String Methods Practice
*/

const flights =
  '_Delayed_Departure;fao93766109;txl2133758440;11:25+_Arrival;bru0943384722;fao93766109;11:45+_Delayed_Arrival;hel7439299980;fao93766109;12:05+_Departure;fao93766109;lis2323639855;12:30';

// 🔴 Delayed Departure from FAO to TXL (11h25)
//              Arrival from BRU to FAO (11h45)
//   🔴 Delayed Arrival from HEL to FAO (12h05)
//            Departure from FAO to LIS (12h30)

const getCode = flights.split('+');

const l = getCode[0].length;

for (const line of getCode) {
  const section = line.split(';');
  // Status
  let status = section[0].slice(1).replace('_', ' ');
  if (status.startsWith('Delayed')) status = '🔴 ' + status;
  // From
  let from = section[1][0] + section[1][1] + section[1][2];
  // To
  let to = section[2][0] + section[2][1] + section[2][2];
  // Clock
  let clock = section[3].replace(':', 'h');

  const output = status + ' from ' + from.toUpperCase() + ' to ' + to.toUpperCase() + ' (' + clock + ')';

  console.log(output.padStart(l - 6));
}

Alternative

const flights =
  '_Delayed_Departure;fao93766109;txl2133758440;11:25+_Arrival;bru0943384722;fao93766109;11:45+_Delayed_Arrival;hel7439299980;fao93766109;12:05+_Departure;fao93766109;lis2323639855;12:30';

// 🔴 Delayed Departure from FAO to TXL (11h25)
//              Arrival from BRU to FAO (11h45)
//   🔴 Delayed Arrival from HEL to FAO (12h05)
//            Departure from FAO to LIS (12h30)

const getCode = str => str.slice(0, 3).toUpperCase();

for (const flight of flights.split('+')) {
  const [type, from, to, time] = flight.split(';');
  const output = `${type.startsWith('_Delayed') ? '🔴' : ''}${type.replaceAll(
    '_',
    ' '
  )} ${getCode(from)} ${getCode(to)} (${time.replace(':', 'h')})`.padStart(36);
  console.log(output);
}

Javascript – Sets & Maps

Sets and Maps new datasctructures introduced in ES6

Sets

A collection of unique data values (iterrables)

const mySet = new Set([
 'unique value 1', // iterable
 'unique value 2'
]);

Sets are also iterrables like arrays, however they differ for two reasons:

  • Can contain only unique elements
  • Order of elements are irrelevant

If a string (also an iterrable) is passed this will create a set with elements of each letter of the string (must be no duplicate letters though.

Set methods

console.log(mySet.size); // similar to .length
console.log(mySet.has('element'); // similar to .includes
orderSet.add('New Element'):
orderSet.delete('Old Element');
orderSet.clear()

Retrieving values from sets

Cannot be done as there is no point as all elements are unique. Just need to use .has() method

Looping sets

for ( const myDatavalue of mySet ) // action

Use cases for sets

Can be used to create a unique iterrable from an array which has multiple repeating datavalues.

const staff = ['Waiter', 'Chef', 'Waiter', 'Manager', 'Waiter', 'Chef'];
const uniqueStaff = [..new Set(staff)]; // creates an array which only includes waiter, chef and manager

New ES2025 set methods

const commonFoods = italianFoods.intersection(mexicanFoods) // creates a new set of common elements

const italianMexicanFusion = italianFoods.union(mexicanFoods); // Creates a new array combining all elements without duplicates. ( although this can me done with spread operator)

const uniqueItalianFoods = italianFoods.difference(mexicanFoods) // create a set of elements that are included only in Italian Foods

const uniqueItalianAndMexicanFoods = italianFoods.symetricDifference(mexicanFoods) 

.isDisjointFrom() // check if both arrays have unique values from each other

Maps

Maps are like arrays but with assignable keys.

Create with new Map();

// best practice is to create an empty map first
const restaurant = new Map();

Add items with .set()

restaurant.set('name', 'My Lovely Restaurant');
restaurant.set('open', '19').set('closed', '23'); // can also be chained
restaurant.set(true, 'We are open').set(false, 'We are closed'); // can use boolean or numbers too

Retrieve values with .get(key) – expressions can also be passed

console.log(restaurant.get('name')); // returns name value

let time = 21;
console.log(rest.get(time > restaurant.get('open') && time < restaurant.get('close'))); returns true, therefore returns 'we are open' (value of true).

Other map methods

.has()
.delete()
.size
.clear()

Objects and Arrays can also be Map Keys. Arrays must be created in the heap.

Populating maps without using .set() method

const question = new Map([
 ['question', 'What is the capital of Peru?'],
 [1, 'Lima'],
 [2, 'Lama'],
 [3, 'Lemur'],
 ['correct', 1],
 [true, 'Correct'],
 [false, 'Try Again']
]);

Converting objects to map

const myMap = new Map(Object.entries(myObject));

Destructing maps in the same way as destructing objects (although .entries method is not required

for(const [key, value] of myMap) {
 //
}
const answer = Number(
  prompt(
    `What is the capital of Peru\n1. ${question.get(1)}\n2. ${question.get(2)}\n3. ${question.get(3)}`
  )
);
console.log(question.get(answer === question.get('correct')));

Javascript – Looping

The for-of loop

Similar to PHP for as loop

for ( const item of myArray ) console.log(item) // Iterates through an array each item is the value

Getting the index of a value, use the .entries method

for ( const item of myArray.entries() ) {
  key = item[0]; value = item[1];
}

// Destructured approach
for ( const [i, el] of myArray.entries() ) {
  key = i; value = el;
}

Enhanced object literals

ES6 three ways to write object literals:

const miniObject = {
 day1: {
  open: 08:00,
  close: 16:00
 },
 day2: {
  open: 08:00,
  close: 12:00
 },
}

const mainObject = {
 miniObject,  // referencing the other object creates a new object within this object with the same property name
}

For methods (functions) within objects, there is no need to add the function keyword:

orderDelivery: function(arg1, arg2) {
 // action
}
// With ES6 you can do this instead...
orderDelivery(arg1, arg2) {
 // action
}

Compute property names instead of manually writing them:

const weekdays = ['mon', 'tues', 'wed', 'thu', 'fri', 'sat', 'sun'];
const openingHours = {
 [weekdays[3]]: {
  open: 12,
  close: 22
 }
}

You can also compute property names with expressions (ie maths)

Optional Chaining (?)

ES2020

Using ? operator after the potentially non-existent property prevents errors. It will return undefined (falsey) if not, otherwise it will continue down the chain.

restaurant.openingHours.mon?.open // return undefined if mon does not exist (shortcircuit), if it does then return open.
const weekdays = ['mon', 'tues', 'wed', 'thu', 'fri', 'sat', 'sun'];

for (const day of weekdays) {
 const open = restuarant.openingHours[day]?.open ?? 'closed';
}

Optional chaining on methods and arrays too.

const users = [{name: 'Duncan', email: 'duncan@samwell.me'}];
console.log(users[0]?.name ?? 'no name given';

Looping objects

Indirectly looping over objects

Looping over property names: Object.keys

for ( const day of Object.keys(openingHours)) {
 console.log(day) // array of all the property names within that object
}

Looping over property values: Object.values

for ( const values of Object.values(openingHours)) {
 console.log(values) // array of all the values within that object
}

Looping over entire objects: Object.entries

Transfers object into an array

for ( const [key, {propertyName1, propertyName2] of Object.entries(openinghours)) {

}

JavaScript – Modern Operators

&&, ||, ??

Operators can use ANY data type, return ANY data type, and can be used for short-circuiting

console.log(3 || 'Nothing'); // returns the first truthy value (3)
console.log('' || 'Nothing')// Nothing
console.log(true || 'Alternative') // true
console.log(undefined || null) // null (null is truthy, undefined is not

Returns the first true value of an argument and then stops (short-circuits)

Can use this instead of terniary arguments

const myVar = trueArgument ? trueArgument : falseAction;
const myVar = argument || falsAction;

&& operator works in the opposite way

Will return the first falsey or all of them if they are all truthy

myFunction && myFunction('arg'); Checks that functions exists, if not then argument ends.

?? Nullish Coalescing Operator

This is used to avoid the issue if 0 should not be a falsey value.

Nullish: null and undefined only (not 0 or ”)

Other logical operators (ES6)

||=, &&=, ??=

myVariable ??= 10; // sets value to 10 if it is nullish

myVariable &&= '<anonymous>'; // resets value to annonymous if it exists

JavaScript Data Structuring

An ES6 feature that allows you to unpack array or an object and assign each value to a variable.

// Simple array
const arr = [2, 3, 4];
const [x, y, z] = arr; // creates 3 variables: x=2, y=3, z=4.

const [a, ,b] = arr; // misses out middle array value (a=2, b=4)

// switching variables
let first = "starter";let second = "main";
[first, second] = [second, first]; // first = main, second = starter

// nested arrays
const nested = [2, 4, [5, 6]];
const [, ,[j, k]] = nested; // j = 5, k = 6

// default values
const [p=1, q=1, r=1] = [8, 9]; // p=8, q=9, r=1

Destructuring Objects

Use curly braces to destructure objects. You use the property names as variable names.

const {propertyName1, propertyName2} = myObject; // desctructuring using property names.

const {propertyName1: myName, propertyName2: myName2} = myObject // destructuring with custom variable names

// setting default values (in case the property doesn't exist)
const {menu = [], starters: starterMenu = []} = myObject;

Mutating Objects

Surround the code with brackets to create a code block.

let a = 111;
let b = 999;
const obj = { a: 23, b: 7. c: 14 };
({ a,b } = obj); // not allowed to use const or let as variables are already declared - add brackets to prevent error and create a code block.

Nested objects

const { fri: { open: o, close } } = openingHours;
// fri is the property name of the first object which has open and close nested object. This syntax will create new variables "o" and "close" which will be Friday opening and closing hours

Destructuring objects with functions/methods

you can destructure objects passed in functions using curly brackets within the function parameters. You can also set default values as before.

restaurant = {
 name: "My Restaurant";
 // this method will destructure a passed object into four variables (using property names)
 orderDelivery: function ({starterIndex = 0, mainIndex = 1, time, address}) {
   console.log("delivery address:" + address);
 }
}

restaurant.orderDelivery({
 // create an object:
 time: '22:30',
 address: '29 This Street, This Town',
 mainIndex: 1,
 starterIndex: 2
});

Spread Operator

Scenario: Create a new array that has two values and then all the values of another array

const = oldArray = [3, 4, 5];
const = newArray = [1, 2, ...oldArray]; // newArray equals 1,2,3,4,5

Spread operator descructures a literal array but does not create new variables for each value.

Can be used to create shallow copies of arrays or merging arrays:

const copiedArray = [...originalArray]; // copy array
const firstAndSecondArray = [...firstArray, ...secondArray]; // merged arrays

Can also be used on any iterables (ie can break down a strings, maps, sets).

const str = 'word';
const letters = [...str]; Creates an array "w","o","r","d"

The spread operator can also be used as the parameter in a function to deconstruct an array and then pass the individual arguments.

Can be used to copy objects too as before.

Rest Pattern

Rest pattern does the opposite of the spread operator. Used to collect multiple elements and condense them into an array.

Uses the spread operator but on the left side of the equals operator

const [a, b, ...others] = [1,2,3,4,5]; // a = 1, b = 2, others = [3,4,5]

REST ELEMENT MUST BE THE LAST ELEMENT OF THE ARRAY. THERE CAN BE ONLY ONE.

Can be used in objects to pick properties out of existing objects.

const { sat, ...weekdays } = restuarant.openingHours; // creates an object of sat and an object of weekdays which includes all the properties of the remaining days less saturday.
Use case:

Can be used in functions when any number of arguments can be passed:

// rest parameter
const add = function (...numbers) {
  let sum = 0;
  for( let i = 0; i<numbers.length; i++) sum += numbers[i];
  return sum;
}

// can pass any number of arguments
add(2,3);
add(1,2,5,6);
const x = [23,5,7];
add(...x); // spread parameter to pass each value of the array.

The above example allows you to pass either an array or multiple single arguments through the function parameters.

Additional use in method

restaurant = {
 orderPizza = function(mainIngredient, ...otherIngredients){
  // will create a variable of first value of the arguement, and then an array of all the other arguments.
 }
};

The spread and the rest look exactly the same but work in opposite ways depending on where they are used.

Spread: Used where we would otherwise write values seperated by a comma

Rest: Used where we would otherwise write variable names separated by commas.

Javascript Fundementals (Part 1)

The Complete JavaScript Course 2025

High-level object-oreinted multi-paradigm programming language

VERSIONS:

ES6 is Modern Javascript (2015)

Values and Variables

  • Never use: function. new or name as variables. Prefix with _ or $ to use.
  • useCamelCase

Data Types

Every value is either OBJECT or PRIMITIVE

PRIMITIVE DATATYPES:

  • Number (floating point numbers)
  • Strings (sequence of characters
  • Boolean (true / false)
  • Undefined (empty value)
  • Null (empty value)
  • Symbol (ES2015) – Unique cannot be changed
  • BigInt – Massive numbers

Javascript has dynamic typing – it automatically assigns data type.

typeof – used to display what data type the variable is.

Declaring variables

var is legacy, use let or const. Use const where possible.

Use let if the variable can change.

Use const if the value of the variable cannot be changed (immutable) (also cannot be empty).

Operators

math (+ – / * x**y), assignment (= += -= *= ++ –), comparison (<> ===)

OPERATOR PRECEDENCE

Precedence Associativity Individual operators Notes
18: grouping n/a Grouping
(x)
[1]
17: access and call left-to-right Member access
x.y
[2]
Optional chaining
x?.y
n/a Computed member access
x[y]
[3]
new with argument list
new x(y)
[4]
Function call
x(y)
import(x)
16: new n/a new without argument list
new x
15: postfix operators n/a Postfix increment
x++
[5]
Postfix decrement
x--
14: prefix operators n/a Prefix increment
++x
[6]
Prefix decrement
--x
Logical NOT
!x
Bitwise NOT
~x
Unary plus
+x
Unary negation
-x
typeof x
void x
delete x [7]
await x
13: exponentiation right-to-left Exponentiation
x ** y
[8]
12: multiplicative operators left-to-right Multiplication
x * y
Division
x / y
Remainder
x % y
11: additive operators left-to-right Addition
x + y
Subtraction
x - y
10: bitwise shift left-to-right Left shift
x << y
Right shift
x >> y
Unsigned right shift
x >>> y
9: relational operators left-to-right Less than
x < y
Less than or equal
x <= y
Greater than
x > y
Greater than or equal
x >= y
x in y
x instanceof y
8: equality operators left-to-right Equality
x == y
Inequality
x != y
Strict equality
x === y
Strict inequality
x !== y
7: bitwise AND left-to-right Bitwise AND
x & y
6: bitwise XOR left-to-right Bitwise XOR
x ^ y
5: bitwise OR left-to-right Bitwise OR
x | y
4: logical AND left-to-right Logical AND
x && y
3: logical OR, nullish coalescing left-to-right Logical OR
x || y
Nullish coalescing operator
x ?? y
[9]
2: assignment and miscellaneous right-to-left Assignment
x = y
[10]
Addition assignment
x += y
Subtraction assignment
x -= y
Exponentiation assignment
x **= y
Multiplication assignment
x *= y
Division assignment
x /= y
Remainder assignment
x %= y
Left shift assignment
x <<= y
Right shift assignment
x >>= y
Unsigned right shift assignment
x >>>= y
Bitwise AND assignment
x &= y
Bitwise XOR assignment
x ^= y
Bitwise OR assignment
x |= y
Logical AND assignment
x &&= y
Logical OR assignment
x ||= y
Nullish coalescing assignment
x ??= y
right-to-left Conditional (ternary) operator
x ? y : z
[11]
right-to-left Arrow
x => y
[12]
n/a yield x
yield* x
Spread
...x
[13]
1: comma left-to-right Comma operator
x, y

jQuery Basics

The document ready function

$(document).ready(function(){
// jQuery programming goes here
}); // end ready

This is only required when you include your javaScript in the head of your document before html – because you often use JS to manipulate existing HTML on the page, you’ll need to wait until all the elements have loaded before executing any JS commands.

AJAX with JSON and jQuery

Javascript Object Notation

  • Uses basic JavaScript arrays and objects to store data.
  • Can either be formatted using array or object notation or a combo of both.

JSON objects vs arrays

Creates key/value pairs to help distinguish what data is in the array.

JSON Formatted data

JSON properties must be enclosed in double-quotes.
[
{
"name": "Aimee",
"inOffice": "true",
},
{
"name": "Bob",
"inOffice": "true",
},
{
"name": "Carl",
"inOffice": "false",
},
]

Use a validator like JSONLint to check if the JSON is formatted correctly.

Parsing JSON

JSON data is just a string of text and needs to be converted to JavaScript (parsing). Takes a string and converts it into a JavaScript object.

JSON.parse(xhr.responseText)

Processing JSON

Using JavaScript

var statusHTML = "<ul>";for (var i=0; i < jsonObject.length; i ++) {
statusHTML += "<li>" . jsonObject[i].keyname . "</li>";
}
status HTML += "ul";

Using jQuery

jQuery has a method function that rolls all four steps of a usual AJAX request into one:

function sendAJAX() {
$('#ajax').load(sidebar.html)
}

jQuery has a number of shorthand methods to simplify using AJAX. These are documented on the jQuery API reference website.

The get method

The get method does not require an element to be selected first.

var url = "/employees.html';
The URL you are making the request to. (as you would use in the js Open method)

var data ={firstName : "Dave", lastName : "McFarland"}
In the form of a query string, the data that would be added to the query string appended to the URL

var callback = function(response){
// Do something with the ajax response
}

$.get(url, data, callback);

getJSON method

$.getJSON(url, data, callback);

The data needs to be in JSON format. The method will automatically parse the JSON data returned. Process the response using the jQuery each method.

$.each(array_or_object, callback) ;

$.each(response, function(index, value) {});

post method

$.post(url,data,callback);

$('form').submit(function(evt) {
evt.preventDefault();
var url = $(this).attr("action");
var formData = $(this).serialize(); //creates a text string with standar URL-encoded notation of fields in an HTML form
$.post(url, formData, function(response{
$('#signup').html(');
});

ajax method

$.ajax(url,settings);

The ultimate (low-level) AJAX method. Requires a url parameter and a JavaScript object containing settings for how the AJAX request should be handled. Refer to the online documentation for all the settings.
$.ajax(url, {
data : formData,
type : "POST",
success : function(response) {
$('#signup").html(<p>Thanks for signing up!</p&gt")
}
});

Handling Errors with jQuery & Ajax

.fail method

A chainable method – jqXHR will return the error.

$.get('missing.html',function(data){ $('#myDiv').html(data); }).fail(function (jqXHR) { alert(jqXHR.statusText)});});

Doesn’t work for a $.load() method and doesn’t work when using JSONP

 

Better to use Fetch API