Post

Javascript Cheatsheet

JavaScript: Understanding the Weird Parts - The First 3.5 Hours

Javascript compares the value of objects and variables stored in memory and not the value you assigned to them

Javascript behaves the way it does because there are 2 phases:

  1. There is a creation phase
  2. Then there is an execution phase

Execution context

The execution stack is a stack of execution contexts for running each function. Each function that runs add an execution context to the stack. Each execution context in the stack runs one at a time.

  • The javascript engine creates a global object for you and the keyword ‘this’
  • The window object is the native object of the browser.
  • When execution context runs it sets up Memory Space for Variables and Functions - this is called hoisting.
  • JavaScript does execute code line by line - so dont get caught in the trap of thinking that it does not and order your code accordingly

Undefined vs Defined

  • All variables in javascript are initially set to undefined
  • Undefined and Not defined are not the same
  • Undefined is a special value provided by the javascript engine that means the variable has not been set

Objects

  • An object is a collection of name value pairs
  • Allow us to group data together.
  • Objects can list arrow functions too.
1
2
3
4
5
6
7
8
9
10
var car = {
  color: "blue",
  year: "1988",
  for_sale : function () { return "$30, 000"; }
}
//add new elements to the car object
car.sunroof = true;
car.stop = function() { return "parachute execution"}
car.stop();

Arrays

arrays are lists. list of items, list of objects, list of names, other arrays arrays are grouped with [] square brackets arrays automatically define the keys - you just need to provide the values arrays are actually a type of object, you can add functions in an array but you cannot reference it by name

Example 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var car_models = ['subaru', 'holden', 'mazda'];

//add new item to array
car_models[3] = 'porshe';
car_models.newkey = "newkey";

//return the start and finish time of the race, but overide the start time
function race() {
  function concat(starttime = "1pm", finishtime = "2pm") {
    return ( starttime + finishtime);
  }

  return concat(starttime = "3pm");
}

//use a function as the parameter
function finish_race(finish_position) {
  return finish_position();
}
console.log(
  finish_race( function(){ return 'first'; })
);

Example 2

1
2
3
4
5
const hobbies = ['sports', 'cooking'];
for (let hobby of hobbies) {
console.log(hobby);
}

array.map() is a method you can use on arrays to create a new instance of the array and also call a function on each value in the provided array.

1
2
3
4
5
6
7
8
9
const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

array.slice(myArray) 
//will copy the array

Array Modification

Arrays are meant to be countable. ie: the key should always be a number.

1
car_models[3] = 'porshe';

This will add Porshe into the 3rd spot in the array

Array Shift

No arguments - move all values in the array down1 by removing the [0] the item at the [0] index

1
array.shift() 

Array Pop

No arguments - pop the element of the end of the array

1
array.pop()

Array Unshift

Pass in the new values as the arguments - add elements to the begining of the array

1
array.unshift()

Array Push

Pass in the new values as the arguments - add elements to the end of the array.

1
array.push()

Array Splice

Starting from which index, how many do you want to delete - delete the specified elements from the array. array.splice can also be used to add in as many elements as you want using the starting point you referenced array.splice can also replace elements in the array using the position/starting point you provided

1
array.splice()

OBJECT VS ARRAY

objects are obvious, objects contain nouns : adjectives, this key and value pair is called a property objects contain funcitons, we call these functions methods, or sub routines objects are grouped with {} curly brackets objects can contain objects objects can contain arrays

Member access

A property of an array or an object is also called a member. Member access function allows you to access properties in the objects with dot syntax.

Computed Member Access

Compute the value within the square brackets ie: javascript will look for variables. To access information you either access it with a dot or with brackets - never both. Use the square brackets when you want to compute the values.

You can access array information by providing the index key. Functions can be accessed too but in order to run the function you need the () on the end. You can add a mathematical statement within an array - referencing the the keys within the array as part of the statement.

You can override existing information in arrays and objects, you can add new elements into objects.

You can delete elements in objects.

1
delete car.year

Functions

invocation: Running a function - add () to a word to invoke it

  • You can think of functions as invokable objects. Notice the use of curly brackets in the function, same as objects.
  • You can put functions inside of functions
  • You can pass objects to functions
  • You can put functions inside of const and variables. Use the name of the variable to call the function.
  • You can create arguments/parameters for functions

Normal Functions

Named function with multiple params

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function sum(a, b) {
return a + b
}

// named function with one param
function isPostive(number) {
return number >= 0

}

// named function with no params
function randomNumber() {
return Math.random
}

//anonomouse function
document.addEventListener('click', function()) {
console.log('click')
}

Arrow functions

Named function with multiple params remove the ‘function’ word and assign the function name to a variable. Arrow functions have 2 syntax - verbose and expression If the Arrow function only returns a single expression you can use the expression syntax.

  • Whatever comes after the arrow => will be returned
  • Remove the function keyword and use a variable name instead

Example 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Arrow function used with map To create a new array of companyNames

const companies = [
{ name: "Company One", category: "Finance", start: 1981, end: 2004 },
{ name: "Company Two", category: "Retail", start: 1992, end: 2008 },
{ name: "Company Three", category: "Auto", start: 1999, end: 2007 },
{ name: "Company Four", category: "Retail", start: 1989, end: 2010 },
{ name: "Company Five", category: "Technology", start: 2009, end: 2014 },
{ name: "Company Six", category: "Finance", start: 1987, end: 2010 },
{ name: "Company Seven", category: "Auto", start: 1986, end: 1996 },
{ name: "Company Eight", category: "Technology", start: 2011, end: 2016 },
{ name: "Company Nine", category: "Retail", start: 1981, end: 1989 },
];

//create array of company names

const companyNames = companies.map((company) => company.name);
console.log(companyNames);

//output company start and end date
const startToEnd = companies.map(
(company) => `${company.name} - [${company.start} - ${company.end}]`
);
console.log(startToEnd);

Example 2

https://youtu.be/h33Srr5J9nY

1
2
3
let sum = (a, b) =>  {
return a + b
}

You can simplify this further if you only have one line of code and it returns something. It will assume whatever comes after the arrow will be returned.

1
let sum = (a, b) => a + b

When you only have one param you can remove the () arround the param.

1
let isPostive = number => number >= 0
1
2
3
let randomNumber = () => Math.random
document.addEventListener('click', () => console.log('click'))

Example 3

https://academind.com/learn/javascript/this-keyword-function-references/ Another way of creating a function. Its shorter syntax and preferred way to write functions now as it makes the this keyword more predictable. Arrow function treats this keyword differently. Arrow functions keep the reference of this to the surrounding object and not the immediate element that called it.

Syntax

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const functionName = (param1, param2, param3) => {
return (
console.log(param1 + param2 + param3);
);
}


//there is a shorter way of writting this.

const functionName = (param1, param2) => {
return param1 + param2;
}
console.log(functionName(param1, param2));

//if you have an arrow function that only returns 1 value you can ommit the "return" and the curly brackets.

const functionName = (param1, param2) => param1 + param2;
//executing functionName will always return the result of param1 + param2

console.log(functionName(param1, param2));

//if you have only one argument you can remove the () brackets around the argument list.

const functionName = param1 => param1 + 1;
console.log(functionName(1));
result = 2

//arrow functions that take no parameters/arguments still need a set of empty brackets for the parameters/arguments

const functionName = () => 1 + 2;
console.log(functionName());

Constructor Functions

  • Constructor functions are like normal functions but they use a capital letter.
  • They are invoked with the “new” keyword
  • If you want to have instances of functions then use a constructor function.
  • Call a constructor function to initialize new objects and methods

Memory hoisting

  • Functions (or callable objects) get “hoisted”
  • Scripts do not immediately execute
  • Compilers read code line by line then pull “symbols” out and store them in memory.
  • If there is syntax errors the jit stops the initial scan.

Scope

  • Think about scope as access
  • Objects and callable objects have scope
  • Callable objects go into the execution stack
  • Garbage collection will remove any symbols from the symbols table that are no longer needed because they cannot be accessed.
  • In regards to the execution stack, 1 function is run at a time. the jit will not run half a function, see a nested function then stop to run that function. No. It runs the full function (as per the list in the stack). When finished it then runs the next function in the stack. This stack is also known as the main thread.
  • The symbols table is a temporary table - due to the nature of “execution” and garbage collection.
    Collectively the symbols table and execution stack is known as the outer execution environment

Global scope

  • Not declared inside a function
  • Window object is the highest level object - this object and all of its memory pointers are globally available. (accessible from anywhere)
  • Declaring variables under the window object means they are also global and available from anywhere.
  • Inferred globals is the act of looking for the global variable - keep going up the scope until its found.

Context

  • “This” will point to the window object by default.
  • “This” in an array or object will point to the window object.
  • Callable objects allows us to change the this context.
  • “This” object steps out 1 level.
  • This function takes a parameter name which is also another function.

https://www.youtube.com/watch?v=9ooYYRLdg_g

Primitive data types

Primitive data types are stored on the stack. They are values that are copied by value:

  • strings
  • numbers
  • boolean
  • undefined
  • null
  • (es6) symbol

Reference data types

Referrence types are stored on the heap

  • objects
  • arrays

The Stack

The stack is allocated memory that is short living, very fast it doesnt hold much info. Values are stored ontop of each other in the stack, new values are stored on top - even if there is already an existing value.

The Heap

The heap is allocated memory that holds more data and is not as fast. Items have their own address in the heap, item values are updated if required.

Includes

Check if a value exists in an array.

1
2
3
4
5
const myArray = [1, 2, 3, 4];
myArray.includes(3);
//returns true
myArray.includes(9);
//returns false

Rest and Spread

REST

Rest operator ...args Allows you to merge an unspecified amount of arguments into an array. Rest puts the rest of something inside other variables.

1
2
3
4
const toArray = (...args) => {
return args;
};
console.log(toArray(1, 2, 3, 4, 3, 33, 33));

Spread

...spread operator will pull the values from a specified array or object and put them in your new array / object. The spread operator can be inserted anywhere

1
2
3
const hobbies = ["sports", "cooking"];
const myNewArray = [...hobbies];
console.log(myNewArray);

es6 classes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Person {
constructor(name) {
this.name = name
}

printNameArrow() {
setTimeout(() => {
console.log('Arrow: ' + this.name)
}, 100)
}
printNamefunction() {
setTimeout(function() {
console.log('Function: ' + this.name)
}, 100)
}
}

let person = new Person('bob')

//the arrow function will print out bob
person.printNameArrow()

//the normal function prints nothing
person.printNamefunction()

console.log(this.name)

This

“this” generally refers to the surrounding object (to the class). “this” refers to whoever called the function is which you use “this”. use console.log(this) to find out what this is referring to. use bind(this); to bind this back to the surrounding object within an object to get this to refer to the object

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const person = {
name: 'max',
age: 20,
greet() {
console.log('hello i am ' + this.name);
}
};

person.greet();

class Person {
//set defaults in the constructor
constructor(name = "Anonymous", age = 0) {
this.name = name;
this.age = age;
}

getGreeting() {
return `Hi i am ${this.name} and i am ${this.age}`;
}

getDescription(name, age) {
return `${this.name} is premium ${this.age}`;
}
}

class Traveller extends Person {
constructor(name, age, homeLocation = "anonymous") {
super(name, age);
this.homeLocation = homeLocation;
}

hasLocation() {
this.hasLocation = hasLocation;
}

getGreeting() {
let greeting = super.getGreeting();
if (this.hasLocation) {
return `yo yo, its ${this.name} from ${this.homeLocation} age ${this.age} bitches`;
}
}
}

const me = new Person("dan", 40);
console.log(me.getGreeting());

const other = new Person("brian", 30);
console.log(other.getDescription());

const trav = new Traveller("bras", "22", "diggstown");
console.log(trav.getGreeting());

const trav2 = new Traveller("beanzy", "33");
console.log(trav2.getGreeting());

Filters

  • Filters are easy and elegant way to pick out values from an array
  • Filters take-in a function
  • You can use arrow function to simplify it
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
const ages = [33, 12, 20, 16, 5, 54, 21, 44, 61, 13, 15, 45, 25, 64, 32];

//using arrow function
const canDrink = ages.filter( age => age >= 18);

console.log(canDrink);

//not using arrow function
const canDrink = ages.filter(function(age)) {
if(age >= 18) {
return true;
}
}

//filter retail companies
const companies = [
{ name: "Company One", category: "Finance", start: 1981, end: 2004 },
{ name: "Company Two", category: "Retail", start: 1992, end: 2008 },
{ name: "Company Three", category: "Auto", start: 1999, end: 2007 },
{ name: "Company Four", category: "Retail", start: 1989, end: 2010 },
{ name: "Company Five", category: "Technology", start: 2009, end: 2014 },
{ name: "Company Six", category: "Finance", start: 1987, end: 2010 },
{ name: "Company Seven", category: "Auto", start: 1986, end: 1996 },
{ name: "Company Eight", category: "Technology", start: 2011, end: 2016 },
{ name: "Company Nine", category: "Retail", start: 1981, end: 1989 },
];

const retailCompanies = companies.filter(company => company.category === 'Retail');
//console.log(retailCompanies);


//get companies started in the 80's

const eightiesCompanies = companies.filter(company => (company.start >= 1980 && company.start <= 1989));
//console.log(eightiesCompanies);

//get companies that lasted 10 years or more
const lastedTenYears = companies.filter(company => (company.end - company.start >= 10) )
console.log(lastedTenYears);

forEach Loop

  • A much nicer way to loop through an array - see forloop comparison below
  • It does not return anything back to you
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const companies = [
{ name: "Company One", category: "Finance", start: 1981, end: 2004 },
{ name: "Company Two", category: "Retail", start: 1992, end: 2008 },
{ name: "Company Three", category: "Auto", start: 1999, end: 2007 },
{ name: "Company Four", category: "Retail", start: 1989, end: 2010 },
{ name: "Company Five", category: "Technology", start: 2009, end: 2014 },
{ name: "Company Six", category: "Finance", start: 1987, end: 2010 },
{ name: "Company Seven", category: "Auto", start: 1986, end: 1996 },
{ name: "Company Eight", category: "Technology", start: 2011, end: 2016 },
{ name: "Company Nine", category: "Retail", start: 1981, end: 1989 },
];

companies.forEach(function (company) {
console.log(company.name);
});

/*
* forLoop
* the below is much harder to read but has same output as the foreach
*/

for (let i = 0; i < companies.length; i++) {
console.log(companies[i]);
}

Reduce

  • Add up all array elements
  • The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.
  • The reducer function takes four arguments:
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
  1. Accumulator
  2. Current Value
  3. Current Index
  4. Source Array
1
2
3
4
5
const ages = [33, 12, 20, 16, 5, 54, 21, 44, 61, 13, 15, 45, 25, 64, 32];
const calculateVals = ages.reduce((a, b) => a + b, 0);

console.log(calculateVals);
//output 460

Array Maps

  • The map() method creates a new array
  • populated with the results of calling a provided function
  • on every element in the calling array.
1
2
3
4
5
6
7
const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map((x) => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]
  • we can create new arrays from anything
  • you can further manipulate data by using .map on an array then applying an
  • arrow function to output manipulated data
  • map takes a function param,
  • you can use an arrow function which will output/return anything after the arrow
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const companies = [
{ name: "Company One", category: "Finance", start: 1981, end: 2004 },
{ name: "Company Two", category: "Retail", start: 1992, end: 2008 },
{ name: "Company Three", category: "Auto", start: 1999, end: 2007 },
{ name: "Company Four", category: "Retail", start: 1989, end: 2010 },
{ name: "Company Five", category: "Technology", start: 2009, end: 2014 },
{ name: "Company Six", category: "Finance", start: 1987, end: 2010 },
{ name: "Company Seven", category: "Auto", start: 1986, end: 1996 },
{ name: "Company Eight", category: "Technology", start: 2011, end: 2016 },
{ name: "Company Nine", category: "Retail", start: 1981, end: 1989 },
];

//create array of company names

const companyNames = companies.map((companyBlaBla) => companyBlaBla.name);
console.log(companyNames);

const startToEnd = companies.map(
(company) => `${company.name} - [${company.start} - ${company.end}]`
);
console.log(startToEnd);

//get ages squared (* the value of itself)
const ages = [33, 12, 20, 16, 5, 54, 21, 44, 61, 13, 15, 45, 25, 64, 32];
const agesSquared = ages.map((age) => Math.sqrt(age));
console.log(agesSquared);

Array Sort

  • Returns 1 or -1 (move up or move down)
  • Takes 2 parameters and compares them however you instruct them by moving the values up and down in the array
  • Using a and b as the parameters is common practice
  • Sort on a simple array of numbers only looks at the first number
  • So you must use arrow function to sort a - b or b - a depending on what sort order you want
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const companies = [
{ name: "Company One", category: "Finance", start: 1981, end: 2004 },
{ name: "Company Two", category: "Retail", start: 1992, end: 2008 },
{ name: "Company Three", category: "Auto", start: 1999, end: 2007 },
{ name: "Company Four", category: "Retail", start: 1989, end: 2010 },
{ name: "Company Five", category: "Technology", start: 2009, end: 2014 },
{ name: "Company Six", category: "Finance", start: 1987, end: 2010 },
{ name: "Company Seven", category: "Auto", start: 1986, end: 1996 },
{ name: "Company Eight", category: "Technology", start: 2011, end: 2016 },
{ name: "Company Nine", category: "Retail", start: 1981, end: 1989 },
];

//sort companies by start year - earliest to the latest
const sortedCompanies = companies.sort((a, b) => (a.start > b.start ? 1 : -1));

const ages = [33, 12, 20, 16, 5, 54, 21, 44, 61, 13, 15, 45, 25, 64, 32];

const sortAges = ages.sort((a, b) => a - b);

console.log(sortAges);
//console.log(sortedCompanies);

Destructuring

https://youtu.be/NIq3qLaHCIs

  • The objective of destructuring is to take an object or an array and convert
  • It into smaller elements or variables
  • The array/object you want to destructure is on the right after the equals
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const alphabet = ["a", "b", "c", "d", "e", "f"];
const numbers = ["1", "2", "3", "4", "5", "6", "7"];

const [a, b, c, ...rest] = alphabet;

const newArray = [...alphabet, ...numbers];

console.log(newArray);

console.log(a);
console.log(b);
console.log(c);
console.log(rest);
  • The real power in destructuring is when working with objects
  • You can map variable names ie: name: firstname
  • You can set default values for when nothing is set in the object
  • Log out the values by referring to the object key in any order
  • Use the spread operator to output multiple values
  • You can output nested objects ie: address{street}
  • You can combine 2 objects together
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63


const person = {
name: "max",
favouriteFood: "watermelon",
age: 20,
address: {
city: "portland",
street: "dorssic",
},
};

//destructuring the person object
const {
name: firstname,
age,
address: { street },
favouriteFood = "rice",
favouriteSport = "mma",
} = person;
console.log(firstname, age, favouriteSport, favouriteFood, street);

const personTwo = {
name: "mat",
age: 22,
address: {
city: "port adelaide",
street: "dokkker",
},
};

/*
* Combine 2 objects together.
* The latter object will overide the values of the first object if they co-exist
*/

const frankenstein = { ...person, ...personTwo };
console.log(frankenstein);

/*
* use destructuring in functions
* once again you can set defaults in the parameters
  */

const person = {
name: "max",
//favouriteFood: "watermelon",
age: 20,
address: {
city: "portland",
street: "dorssic",
},
};

function printUser({ name, age, favouriteFood = "avacados" }) {
console.log(
`Name is: ${name}. Age is: ${age}. favouriteFood is = ${favouriteFood}`
);
}

printUser(person);

Destructuring arrays

array values are pulled out by position. so you can use any value for the destructuring values.

1
2
3
4
5
const hobbies = ["sports", "cooking"];
const [param1, param2] = hobbies;
console.log(param1, param2);

Destructuring

destructuring is the act of pulling values out of an object or array We cant just go person.name - this gives us nothing; instead we need to write a function to destructure the data

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const person = {
name: "max",
age: 20,
greet() {
console.log("hello i am " + this.name);
},
};
const printName = ({ name, age }) => {
console.log(name);
};
printName(person);

/*
simpler destructuring syntax to pull values from the person object:
*/
const { name, age } = person;
console.log(name, age);

//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
let a, b, rest;
[a, b] = [10, 20];

console.log(a);
// expected output: 10

console.log(b);
// expected output: 20

[a, b, ...rest] = [10, 20, 30, 40, 50];

console.log(rest);
// expected output: Array [30,40,50]

// Stage 4(finished) proposal
({ a, b, ...rest } = { a: 10, b: 20, c: 30, d: 40 });
console.log(a); // 10
console.log(b); // 20
console.log(rest); // {c: 30, d: 40}

//https://www.udemy.com/course/nodejs-the-complete-guide/learn/lecture/11561874#overview
//examples of object destructuring - objects destructure by name

const person = {
name: "max",
age: 20,
greet() {
console.log("hello i am " + this.name);
},
};

person.greet();
//output hello i am max

const printName = ({ name }) => {
console.log(name);
};

printName(person);

//output max

const { name, age } = person;
console.log(name, age);
//output max, 20

//destructuring arrays - arrays destructure by position
const hobbies = ["sports", "cooking"];
const [param1, param2] = hobbies;
console.log(param1, param2);
//output sports cooking

Arrays

What’s the real difference between declaring an array like this:

1
2
3
4
5
var myArray = new Array();
//and

var myArray = [];

There is a difference, but there is no difference in that example. Using the more verbose method: new Array() does have one extra option in the parameters: if you pass a number to the constructor, you will get an array of that length:

1
2
3
4
x = new Array(5);
alert(x.length); // 5

To illustrate the different ways to create an array:

1
2
3
4
5
6
7
8
9
var a = [], // these are the same
b = new Array(), // a and b are arrays with length 0
c = ["foo", "bar"], // these are the same
d = new Array("foo", "bar"), // c and d are arrays with 2 strings
// these are different:
e = [3], // e.length == 1, e[0] == 3
f = new Array(3); // f.length == 3, f[0] == undefined

As pointed out in this answer, new Array(5) will not actually add five undefined items to the array. It simply adds space for five items.

Promises

Promises are meant to replace callbacks. Promises in javascript are just like promises in real life.

If i promise to do something im commited to delivering it. But if i fail at my promise nothing will be delivered.

So there is only 2 possible outcomes of a promise

So if I can deliver on my promise (if i dont hit any errors).

  • then I can will do it for you. -then I can do something else for you.
  • then I can do something else for you.

If I fail on my promise

  • Then ill tell you why i failed (catch),

You can create a promise with new Promise()

https://youtu.be/DHvZLI7Db8E

1
2
3
4
5
6
7
8
9
10
11
12
13
14
let p = new Promise((resolve, reject) => {
let a = 1 + 1;
if (a == 2) {
resolve("success");
} else {
reject("fail");
}
});

p.then((message) => {
console.log("this is in the then" + message);
}).catch((message) => {
console.log("this is in the catch" + message);
});

You can use promise.all to run several promises. promise.all takes an array of promises. Use promise.all instead of using too many .then.then.then.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const recordVideoOne = new Promise((resolve, reject) => {
resolve("Video 1 recored");
});

const recordVideoTwo = new Promise((resolve, reject) => {
resolve("Video 2 recored");
});

const recordVideoThress = new Promise((resolve, reject) => {
resolve("Video 3 recored");
});

Promise.all([recordVideoOne, recordVideoTwo, recordVideoThress]).then(
(messages) => {
console.log(messages);
}
);

//.race only returns to the first promise to finish
Promise.race([recordVideoOne, recordVideoTwo, recordVideoThress]).then(
(messages) => {
console.log(messages);
}
);

youtu.be/PoRJizFvM7s

Output all the posts, Create a new post and add it to the post object, Use a promise to handle the response

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//the posts
const posts = [
  { title: "post one", body: "body 1" },
  { title: "post two", body: "body 2" },
];

//get posts function
function getPosts() {
  setTimeout(() => {
    let output = "";
    posts.forEach((post, index) => {
    output += `<li>${post.title}</li>`;
  });
  //document.body.innerHTML = output;
  console.log(output);
  }, 1000);
}

//create post function
function createPost(post) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      posts.push(post);
      const error = false;
      if (!error) {
        resolve();
      } else {
        reject("error for you");
      }
    }, 2000);
  });
}

//use the createPost function to create a new post and if it worked then run the getPosts function. if id didnt work display the error using catch.
createPost({
  title: "Post Three",
  body: "this is a new post we adding to the post object",
})
.then(getPosts)
.catch((err) => console.log(err));

//use promise.all

const promise1 = Promise.resolve("hello");
const wtf2 = 10;
const promise3 = new Promise((resolve, reject) =>
setTimeout(resolve, 2000, "goodbye")
);

Promise.all([promise1, wtf2, promise3]).then((values) => console.log(values));


Async Await

  • JS is synchronous - one at a time
  • JS is single threaded - one function at a time
  • Asynchronous code is code that does not finish immediately.
  • Asynchronous code uses a callback function.

Asynchronous

Controlling the timing of operations by the use of pulses sent when the previous operation is completed rather than at regular intervals. when an action takes an indefinate amount of time and javascript does not know when a function will be finished.

Synchronous

existing or occurring at the same time: glaciations were approximately synchronous in both hemispheres. it happens immediatly

What does async await do?

Async/Await is a way to write asynchronous code in a more synchronous-looking way. It allows you to write code that looks like it is running synchronously, but is actually running asynchronously. Async/Await makes it easier to write code that runs asynchronously, without having to use callbacks or promises. It also makes it easier to read and understand asynchronous code.

What is the difference between asynchronous and synchronous code?

Synchronous code is code that runs in a linear fashion, meaning that each line of code is executed one after the other in the order it is written. Asynchronous code is code that can run in parallel or out of order, meaning that multiple lines of code can be executed at the same time or in a different order than they are written.

What is the use case for asynchronous code?

Asynchronous code is used when you need to perform tasks that take a long time to complete, such as making an API calls, downloading a file, or waiting for a response from a server. Asynchronous code allows your program to continue running while the task is being completed in the background, so that your program does not become unresponsive or slow down.

ASYNC / AWAIT -

Is away to handle responses. Await for the function to run before running the next function. Its a more elegant way to handle promises. Its a cleaner way of dealing with promises.

Async must be in function declaration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
const posts = [
{ title: "post one", body: "thei is this" },
{ title: "post two", body: "thei is this 2" },
];

function createPost(post) {
return new Promise((resolve, reject) => {
setTimeout(() => {
  posts.push(post);
  const error = false;
    if (!error) {
      resolve();
    } else {
      reject("error for you");
    }
  }, 2000);
});
}

function getPosts() {
  setTimeout(() => {
    let output = "";
    posts.forEach((post, index) => {
    output += `<li>${post.title}</li>`;
  });
  //document.body.innerHTML = output;
  console.log(output);
  }, 1000);
}

async function init() {
  await createPost({ title: "Post Three", body: "this is post three" });
  //wait for createPost to be done before calling getPosts
  getPosts();
}

init();

Operators

B O SM AS

Operator precedent in Javascript

Brackets pOwers (Division Multiple) (Addition Subtraction)

Modulas operators

Gives you the remainder (whatever is left) of any division.

First it divides what it can.

ie: 5 goes into 9 once with 4 left over

9 % 5 = 4

10 % 2 = 0 (there is nothing left over from the division)

Modulas is good for finding odd or even numbers

+= 30 Add to the existing values.

-= 20 Subtract from the existing values.

*= 2 Multiple existing values.

/= 4 Divide existing values.

%= 4 Modulas existing values.

**= 4 “to the power of (4 x existing value 4 times)” existing values.

The plus + operator also deals with strings.

1
"string" + "string" = stringstring

polymorphism is like playdo. It adapts to whatever shape you need

1
"string" + 10 = string10
  • How to handle money values in javascript https://frontstuff.io/how-to-handle-monetary-values-in-javascript
This post is licensed under CC BY 4.0 by the author.