live-coding practice Flashcards
*How do you declare an object
(literal) const blah = {}, (constructor) new Object(), Object.create()
—————————————————————
Actually there’s 6 ways:
Object Literal Object Constructor Constructor Function Object.create() Method Object.assign() Method ES6 Classes
https://attacomsian.com/blog/javascript-create-object
*How do you declare an array
(literal) const blah = [], (constructor) new Array(), Array.from() ————————————————————— // using the new keywrod const array1 = new Array("1", "2") console.log(array1)
// array literal const array2 = [true, false] console.log(array2)
// using the from method, createds a shallow copy array // doesn't work in IE const array3 = Array.from(array2) console.log(array3)
// you can spread one array into another one const sup = ['1', '2'] const sup2 = [...sup] console.log(sup2)
—————————————————————
Not sure if this counts as declaring an array but … you can create an array from objects like this
// You can create an array from an objects values using Object.values const obj1 = { name: "brad", age: "12", } console.log(Object.values(obj1)) >> [ 'brad', '12' ]
// Or you could do it from an object’s keys using Object.keys
console.log(Object.keys(obj1))
» [‘name’, ‘age’]
*IMplement the revealing module pattern
There’s also something called the ‘revealing module pattern’ where you return stuff out of your IIFE for use elsewhere. For example in the code below I return an object for use:
const myName = (function() { function logFn(){ console.log("hello"); } return {logStuff: logFn} })()
Now I can use stuff like myName.name in other places
How do you implement inheritance
ES6 way with classes: class Player { constructor(name, type) { console.log(this, "From player") //console.log(name, `This is the name inside the Player class`) this.name = name; this.type = type; }
introduce() { console.log(`Hi my name is ${this.name}, I'm a ${this.type}`) } }
class Wizard extends Player { constructor (name, type) { //console.log(name, `This is the name inside of the wizard class`) let othertype = "billy"; let othername = "mark" super(othername, othertype) console.log(this, "From Wizard")
} play() { console.log(`Weeee I'm a ${this.name}, of type ${this.type}`) } }
const wizard1 = new Wizard('Shelly', 'Healer') const wizard2 = new Wizard('Shawn', 'tank')
wizard2. introduce() wizard2. play() wizard1. introduce() wizard1. play() Pre-es6 way with prototypes:
var Player = function(name, type) { this.name = name; this.type = type; }
Player.prototype.introduce = function() { console.log(`Hi I'm ${this.name} of type ${this.type}`) }
var wizard1 = new Player("Shelly", "healer"); var wizard2 = new Player("Billy", "tank");
wizard1.play = function() { console.log(`Weeee, I'm a ${this.type}`) } wizard2.play = function() { console.log(`Woop, I'm also a ${this.type}`) } wizard1. introduce() wizard1. play()
Learn classes and extends from 20:53 https://www.udemy.com/course/advanced-javascript-concepts/learn/lecture/13511600#search
Can relearn classes and prototypes with this udemy section: https://www.udemy.com/course/javascript-beginners-complete-tutorial/learn/lecture/17190250#search
^that’s a setup, with a missing constructor in the child objects, that you would use if you don’t need to add any particular opening variables to the child and just want to use the parents constructor
Video tutorial on this one: https://www.udemy.com/course/javascript-beginners-complete-tutorial/learn/lecture/17190274#announcements
Also figured out how to do it like this:
>>const Player = function(name, age) { this.name = name; this.age = age; }
//Player.prototype = new Player("billy", 12) Player.prototype.sayname = function() { console.log(`My name is ${this.name} and I am ${this.age} old`) }
>>const Athlete = function(sport, name, age) { Player.call(name, age) this.sport = sport; }
Athlete.prototype.saysport = function() {
console.log(I play ${this.sport}
)
}
const bobby = new Athlete(“soccer”, “billy”, 12)
bobby.saysport()
bobby.__proto__ = new Player(“billy”, 12)
//console.log(bobby.__proto__)
bobby.sayname()
Create a constructor function that hides a variable and then create new instances of it which can manipulate their version of that variabl without having direct access.
function Ninja() { let feints = 0; this.getFeints = function() { return feints; } this.feint = function() { feints++; } }
let ninja1 = new Ninja(); ninja1.feint(); // increae value of feints
console. log(ninja1.feints, "can't access feints directly for ninja1"); console. log(ninja1.getFeints()); // return value of feints, for ninja1
let ninja2 = new Ninja(); console.log(ninja2.getFeints()); // return feints for ninja2
1 const Stuff = function() { 2 let name = "TEMPORARY"; 3 4 return { 5 sayname: function() { 6 console.log(name) 7 }, 8 setname: function(input) { 9 name = input 10 } 11 } 12 13 //this.sayname = function() { 14 // console.log(name); 15 //} 16 17 //this.setname = function(newname) { 18 // name = newname; 19 //} 20 21 } 22 23 const bobby = Stuff() 24 25 bobby.sayname() 26 bobby.setname("brad") 27 bobby.sayname() 28 const sarah = new Stuff() 29 sarah.sayname() 30 sarah.setname("sarah") 31 sarah.sayname() 32 bobby.sayname()
Create your own promise object for use
let PENDING = 0; let FULFILLED = 1; let REJECTED = 2;
function CustomPromise(executor){ let state = PENDING; let value = null; //the this.then method will use this let handlers = []; // the this.then method will use this to throw additional callack functions into let catchers = []; // the this.thn will also dump callback functions in here but ... yah
function resolve(result) { if (state !== PENDING) return; state = FULFILLED; value = result; handlers.forEach(func => { func(value) }) }
function reject(error) { if (state !== PENDING) return; state = REJECTED; value = error; catchers.forEach(ruin => ruin(value)) }
this.then = function(additionalFunction) { if (state === FULFILLED) { additionalFunction(value); } else { handlers.push(additionalFunction) } } executor(resolve, reject); }
const doWork = (res, rej) => { setTimeout(() => { res("HelloWorld"); }, 1000); }
let someText = new CustomPromise(doWork) someText.then((res) => console.log(res)); someText.then(sup => console.log(sup));
Demonstrate the difference of this between a normal function and an arrow function
(refer to anki deck for images which are … excellent ones. I need to convert those to text actually)
This is the object that the function is a property of
Benefits include
- It gives methods access to their object
- You can execute the same code for multiple objects
https: //www.udemy.com/course/advanced-javascript-concepts/learn/lecture/13772916#search
https: //www.udemy.com/course/advanced-javascript-concepts/learn/lecture/13772930#search <– the examples below are from this video
… might want to spend time updating this answer with better, more explainy, code examples
Longer definition: This refers to the object that calls the function since it has runtime binding (dynamically scoped - not lexically scoped)most of th time. Behavior differs when explicitly setting its value with bind, apply, and call, and also arrow functions do not provide their own this binding, it retains the value from its enclosing lexical environment instead.
demonstrate this and explain:
const a = function() { console.log('a', this) // window => window.a() const b = functio\\\\\n() { console.log('b', this) // window => window.a( /* b() */ ) const c = { hi: function() { console.log('c', this) // c => window.a ( /* b( /* c.hi() */ ) */) } } c.hi() } b() }
a()
// a function // output 'a' window // var b // b function // output 'b' window // var c b // c.hi function // output 'c' c // var c
another example:
var b = { name: 'b', say() { console.log(this)} }
var c = { name: 'c', say() { return function() { console.log(this)}} }
var d = { name: 'd', say() { return () => console.log(this)} }
d. say()() //d c. say()() //window b. say() //b
««_space;some more»_space;>
Demonstrate different ways to make this fourth this variable not refer to the global object
const first = function() { console.log('first this is: ' + this); const second = function() { console.log('second this is: ' + this) const third = { printThird: function() { console.log('third this is: ' + this) const fourth = function() { console.log('fourth this is: ' + this) } fourth() } } third.printThird() } second(); } first()
const first = function() { console.log('first this is: ' + this); const second = function() { console.log('second this is: ' + this) const third = { printThird: function() { console.log('third this is: ' + this) const fourth = function() { console.log('fourth this is: ' + this) } fourth() } } third.printThird() } second(); } first()
// fixed version below with arrow function
const fourth = () => { console.log('fourth this is: ' + this)
// fixed version below binding this to a variable
const third = { printThird: function() { console.log('third this is: ' + this) that = this; const fourth = function() { console.log('fourth this is: ' + that) } fourth() } }
// call version below // apply, bind not shown
const first = function() { console.log('first this is: ' + this); const second = function() { console.log('second this is: ' + this) const third = { printThird: function() { console.log('third this is: ' + this) const fourth = function() { console.log('fourth this is: ' + this) } fourth.call(third) } } third.printThird() } second(); } first() // here is another version of this getting broken but includes commented out fixes
const obj = { name: 'Billy', sing() { console.log('a', this); var anotherFunc = function() { console.log('b', this) } // anotherFunc.bind(obj)() //fix with bind // return anotherFunc.bind(this) // fix with bind to lcoal this return anotherFunc; // global this } }
obj.sing()()
Demonstrate variable leakage and how to fix it
Leaks: function stuff() {
hello = function() { console.log("can you see me") }
}
stuff()
hello()
—————————————————————
fixed by using the let keyword, or const
Demonstrate variable leakage and how to fix it
Leaks: function stuff() {
hello = function() { console.log("can you see me") }
}
stuff()
hello()
—————————————————————
fixed by using the let keyword, or const
Demonstrate the use of call and apply and say what they do
const wizard = { name: "wizard", health: 20, heal() { this.health = 100; return `Just healed ${this} to 100 `; }, gloat(num, realname) { console.log(`Heh, ${this.name} health is now over ${num} maybe, an my real name is ${realname}`) } }
const shooter = { name: "shooter", health: 30, }
console.log(`The wizards health is ${wizard.health} and the shooters health is ${shooter.health}`) wizard.heal.apply(shooter) wizard.gloat.call(shooter, 5000, "bobby") //call differs from apply by taking comma separated parameters wizard.gloat.apply(shooter, [20, "???"]) // apply differs by taking an array of parameters // const sup = wizard.gloat.bind(shooter, 999999, "lol") // sup() wizard.gloat.bind(shooter, 1, 77777, "lol")() // bind, unlike call and apply, doesn't run immediately, instead it returns a function to be run in the future console.log(`The wizards health is ${wizard.health} and the shooters health is ${shooter.health}`)
give an example of function composition
“Function Composition” is applying one function to the results of another. · (g º f)(x) = g(f(x))
note: Function composition is an approach where the result of one function is passed on to the next function, which is passed to another until the final function is executed for the final result.
Composing functions is where you take a set of pure functions and compose a new function that is a composition of all the functions
When we compose functions together, the main goal is to take a function and combine it with another function–so that when both of them are together gives us a more enhanced function that helps to produce a value that we want.
const compose = (a, b) => (num) => a(b(num));
const subtract = (num) => num - 1; const multiply = (num) => num * 5;
const multiplyAndSubtract = (multiplyNum, subtractNum) => compose(multiplyNum, subtractNum); const doit = multiplyAndSubtract(subtract, multiply) doit(5) another example: fn1(fn2(fn3(50))); compose(fn1, fn2, fn3)(50); // do 3, then 2, then 1 on the input of 50
give an example of partial application, and or properly describe it
Partial application is a process of reducing a function’s arity (the number of its parameters) by creating a new function with some of the arguments passed in.
Partial application allows us to fix a function’s arguments. This lets us derive new functions, with specific behavior, from other, more general functions.
Partial application starts with a function. We take this function and create a new one with one or more of its arguments already “set”
Partial application is the act of taking a function which takes multiple arguments, and “locking in” some of those arguments, producing a function which takes fewer arguments.
Partial application says on the second call of the function, I expect all the arguments while currying says I expect the arguments one at a time
const multiply = (a,b,c) => a*b*c; const partialmultiply = multiply.bind(null, 5) console.log(partialmultiply(1,3))
compare pipe to compose
It's just like compose except it swaps the order of the composition. in this case, we reverse the order in which functions are operated on data const compose = (a, b) => (num) => a(b(num)); const pipe = (a, b) => (num) => b(a(num));
const subtract = (num) => num - 1; const multiply = (num) => num * 5;
const multiplyAndSubtract = (multiplyNum, subtractNum) => compose(multiplyNum, subtractNum); const doit = multiplyAndSubtract(subtract, multiply) doit(5) another example: fn1(fn2(fn3(50))); pipe(fn3, fn2, fn1)(50); // do 3, then 2, then 1 on the input of 50
*How many types are there in javascript and what are they
There are 7:
booleans strings numbers symbol undefined null
object - this is a non primitive type as it doesn't have the value directly like the others. arrays, and function are objects too
*Quickly convert a variable to a number
you could use unary plus
console.log(+”10”)
console.log(Number(“10”)) is also correct
implement promise.all [with fetch?]
const urls = [
‘https://jsonplaceholder.typeicode.com/users’,
‘https://jsonplaceholder.typicode.com/posts’,
‘https://jsonplaceholder.typicode.com/albums’
]
Promise.all(urls.map(url => { return fetch(url).then(resp => resp.json()) })).then(results => { console.log(results[0]) console.log(results[1]) console.log(results[2]) }).catch(() => console.log('woops')) // I should probably annotate this code above for reference
const sup1 = Promise.resolve("done") const sup2 = Promise.resolve("done 2") const sup3 = Promise.resolve("done 3")
const things = Promise.all([sup1, sup2, sup3]) things.then(result => console.log(result[0]))
console. log(things) https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
*loop through the properties of an object
const obj = { name: "billy", age: 12, value: false, }
const obj2 = { color: "blue" } obj2.\_\_proto\_\_ = obj
console.log(obj2.color)
for (const prop in obj2) { if (obj2.hasOwnProperty(prop)){ // use hasOwnProperty so you don't get the prototypes properties as console.log(prop, obj[prop]) } }
for (const [key, value] of Object.entries(obj2)){ console.log(key, value) } for (const key of Object.keys(obj2)){ console.log(key) } for (const value of Object.values(obj2)){ console.log(value) }