es6 javascript Flashcards
Symbol.Iterator
let myRange = {
from: 1,
to: 5,
Symbol.iterator {
this.current = this.from;
return this;
},
next() { if (this.current <= this.to) { return { done: false, value: this.current++ }; } else { return { done: true }; } } };
for (let num of myRange) {
alert(num); // 1, then 2, 3, 4, 5
}
// or
var iter = myRangeSymbol.Iterator;
iter. next() // { value: 1, done: false}
iter. next() // { value: 2, done: false}
iter. next() // { value: 3, done: false}
iter. next() // { value: 4, done: false}
iter. next() // { value: 5, done: false}
iter. next() // { value: undefined, done: true}
What does bind() do
Sets the “this” of a function to an object
var dog = { noise: “arf”, speak: function () { console.log(this.noise) } };
var cat = { noise: “meow” };
dog.speak.call(cat); // meow
var kitty = dog.speak; kitty() // undefined!!!! var boundKitty = kitty.bind(cat); boundKiity() // meow
difference between call and apply
The difference between call() and apply() is that call() passes all arguments after the first one on to the invoked function, while apply() takes an array as its second argument and passes the members of that array as arguments.
var someFunc = function () {return this.length} someFunc.call(thisArg, 1, 2, 3) // returns 3 someFunc.apply(thisArg, [1, 2, 3]) // returns 3
Array.from()
es6 only. Useful for converting array-type objects (DOM lists) into real arrays
Function.prototype.call()
var person = { fullName: function() { return this.firstName + “ “ + this.lastName; }}
var person1 = { firstName:”John”, lastName: “Doe”}var person2 = { firstName:”Mary”, lastName: “Doe”}
person. fullName() // undefined, because there is no this
person. fullName.call(person1); // Will return “John Doe”
why doesnt document.getElementsByTagName().shift() work
Not an real array. DOM lists are “array type objects”
What does console.log(arguments.constructor) print?
Object() //. it’s an “array type object”
vs
Array()
Array.prototype.slice
midstring for arrays
const animals = [‘ant’, ‘bison’, ‘camel’, ‘duck’, ‘elephant’];
console. log(animals.slice(2)); // expected output: Array [“camel”, “duck”, “elephant”]
console. log(animals.slice(2, 4)); // expected output: Array [“camel”, “duck”]
How does the ‘auguments’ keyword work
arguments is an array-like object that lists the arguments and a few other properties (such as a reference to the current function in arguments.callee and length).
What is the ‘rest’ parameter
function sum(...args) { let total = 0; for (const a of args) { total += a; } return total; }
sum(1, 2, 3);
Give example of spread operator
Acts like Append() for arrays.
const odd = [1,3,5];
const combined = [2,4,6, …odd];
console.log(combined);
Output:
[ 2, 4, 6, 1, 3, 5 ]
For example, the push() method of an array object allows you to add one or more elements to an array. If you want to pass an array to the push() method, you need to use apply() method as follows:
var rivers = ['Nile', 'Ganges', 'Yangte']; var moreRivers = ['Danube', 'Amazon'];
Array.prototype.push.apply(rivers, moreRivers);
console.log(rivers);
vs
rivers.push(…moreRivers);
Lots more: https://www.javascripttutorial.net/es6/javascript-spread/
Object literals
old: function createMachine(name, status) { return { name: name, status: status }; }
new: function createMachine(name, status) { return { name, status }; }
old: let server = { name: 'Server', restart: function() { console.log('The' + this.name + ' is restarting...'); } };
new: let server = { name: 'Server', restart() { console.log(`The ${this.name} is restarting...`); }, 'starting up'() { console.log(`The ${this.name} is starting up!`); } }; server['starting up'](); //'the Server is starting up
Different between Array and Set
Sets are hashtable; they dont allow duplicates.
tricky: var arr = Array.from("123"); // ['1','2','3']
create an array with no duplicates from[1,2,2,3,2,4]
const myArray = [‘a’, 1, ‘a’, 2, ‘1’];
const unique = […new Set(myArray)];
// old const unique = Array.from(new Set(myArray) )
how to determine if var a = [1,2,3] contains a 2
var a = [1,2,3] var exists = a.indexOf(2) != -1;
var exists = a.includes(2); // Not supported by IE
how to determine if var a = new Set([1,2,3]) contains a 2
var a = new Set([1,2,3]) var exists = a.has(2)
Add and remove element to array:
1: append to end
2: pre-append to front
3: remove last
4: remove first
a = [1,2,3]
a. push(4). //[1,2,34]
a. unshift(0) // [0,1,2,3,4]
a. pop() // 4
a. shift() // 0
what does splice do?
Multi element pop() of array.
Splice(index, deleteCount) — remove a number deleteCount of element (s) starting from index.
a = [1,2,3,4,5,6,7]
a. splice(2,3) //[3, 4, 5]
console. log(a) // [1, 2, 6, 7]
explain var hoisting
javascript compiler virtually moves all var declaration to the top of the function, regardless of where they are declared.
x = 5; // good!
y = 2; // reference error!!
let y;
var x;
What is es6 Object de-structuring
let person = { name: 'Maya', age: 30, phone: '123', address:{ zipcode: 1234, street: 'rainbow', number: 42 } }
function buildPerson(animalData){ let {address: {zipcode, street, number}} = person; console.log(zipcode, street, number); //1234 rainbow 42
}
buildPerson(person) // 1234 “rainbow” 42
---- even trickier: default params, and allow to be called with empty param function buildPerson({address: {country='USA', street, number}={} } = {} ){ console.log(country, street, number); //USA rainbow 42 }
buildPerson(person) // “USA” “rainbow” 42
buildPerson() // USA undefined undefined
buildPerson( {} ) // USA undefined undefined
What is a closure? Why are they useful?
allows javascript to emulate private methods that are found in other programming languages. Private methods are useful for restricting access to code as well as managing your global namespace
A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.
The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters. Note that the inner function cannot call the outer function’s arguments object, however, even though it can call the outer function’s parameters directly.
function showName (firstName, lastName) {
var nameIntro = "Your name is ";
function makeFullName () { return nameIntro + firstName + " " + lastName; }
return makeFullName (); }
showName (“Michael”, “Jackson”);
for..of vs for…in
For… in iterates the interable “properties” of an object, rather than the elements of the object, which is useless. For … in iterates the elements.
Iterates the object, not the collection
Template Literals
use the back tick syntax for string formatting and multiline strings
generator iterable
const myIterable = { *[Symbol.iterator]() { yield 1; yield 2; yield 3; } }
for (let value of myIterable) { console.log(value); } // 1 // 2 // 3
or
[…myIterable]; // [1, 2, 3]
difference between object.assign vs spread
not much, other than spread wasnt standerdized.
Object.is vs ===
=== doesn’t treat NaN as equal
let quantity = NaN;
console. log(quantity === quantity); // false
console. log(Object.is(quantity,quantity)); //true
What are es6 proxyz. What are common traps
Allows you to override, get, set, apply(call function), construct
what do you call:
var world ="world"; console.log( `hello ${world}`);
template literal
what do you call:
function go({one, two, three}){ console.log(`Two is eqaul to ${two}`); }
foo({one:’hello’,two:’world’,three:”there’});
de-construction
What is this?:
var add = (function () { var counter = 0; return function () {counter += 1; return counter} })();
add();
add();
add();
javascript closer. Allows ‘counter’ to act as private variable.
What an IIFE. (pronounced “Iffy”. hahha)
An Immediately-invoked Function Expression is a way to execute functions immediately, as soon as they are created. IIFEs are very useful because they don’t pollute the global object, and they are a simple way to isolate variables declarations
NOTE: THEY ONLY RUN ONCE!!! Cant be re-invoked
for(var i=1; i<10; i++){ (function(x){ setTimeout(function(){ document.write(x); }, 1000); })(i); } Output is:
123456789
IIFEs can be defined with arrow functions as well:
(() => { /* */ })()
What is this thing called?
(function() { var x = 20; var y = 20; var answer = x + y; console.log(answer); })();
IIFE. Immediately Involked Function Expression.
Usually used in libraries such as jquery to initialize library at load and protect vars.
Difference between:
31 == “31”
31 === “31”
31 == “31”. // true. auto casting. not checking type
31 === “31” //only true is value and type match
what does double exclaim, !!x do?
Hard cast to Boolean. useful when truthyness issues pop up.
What is truthyness
Weird behaviour in JS == operator.
if (x==false) //. dangerous
if(!x) // better
// instead of if (x === y) // ... // runs if x and y are identical... // except when both are NaN
// use if (!!x === !!y) // ... // runs if x and y are identical... // including when either or both are NaN
Separation of concerns
Separation of concerns is the idea that each module or layer in an application should only be responsible for one thing and should not contain code that deals with other things. Separating concerns reduces code complexity by breaking a large application down into many smaller units of encapsulated functionality.
control vs Widget vs Layer vs Tier vs
A control is a reusable GUI input that enables user interaction with your application.combo boxes, calendar inputs, sliders, buttons, switches, and knobs are all controls.
A widget is a small application which is intended to be embedded in other applications. Calendar, chat app…etc
Layers are logical groupings of functionality. Data Access layer , Data Store layer, Presentation layer, and Business layer
Tiers are the runtime environments that layers get deployed to. The computer. The OS,the runtime engine (e.g., Node, Java, or Ruby), and any configuration needed to express how the application should interact with its environment.
or
Specifically, tiers are places where layers are deployed and where layers run. In other words, tiers are the physical deployment of layers.
Flexibility:
“The ease with which a system or component can be modified for use in applications or environments other than those for which it was specifically designed.”