es6 javascript Flashcards

1
Q

Symbol.Iterator

A

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}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What does bind() do

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

difference between call and apply

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Array.from()

A

es6 only. Useful for converting array-type objects (DOM lists) into real arrays

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Function.prototype.call()

A

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”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

why doesnt document.getElementsByTagName().shift() work

A

Not an real array. DOM lists are “array type objects”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What does console.log(arguments.constructor) print?

A

Object() //. it’s an “array type object”

vs

Array()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Array.prototype.slice

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How does the ‘auguments’ keyword work

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the ‘rest’ parameter

A
function sum(...args) {
    let total = 0;
    for (const a of args) {
        total += a;
    }
    return total;
}

sum(1, 2, 3);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Give example of spread operator

A

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/

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Object literals

A
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Different between Array and Set

A

Sets are hashtable; they dont allow duplicates.

tricky:
var arr = Array.from("123"); //  ['1','2','3']
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

create an array with no duplicates from[1,2,2,3,2,4]

A

const myArray = [‘a’, 1, ‘a’, 2, ‘1’];

const unique = […new Set(myArray)];

// old
const unique = Array.from(new Set(myArray) )
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

how to determine if var a = [1,2,3] contains a 2

A
var a = [1,2,3] 
var exists = a.indexOf(2) != -1;

var exists = a.includes(2); // Not supported by IE

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

how to determine if var a = new Set([1,2,3]) contains a 2

A
var a = new Set([1,2,3]) 
var exists =  a.has(2)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Add and remove element to array:

1: append to end
2: pre-append to front
3: remove last
4: remove first

A

a = [1,2,3]

a. push(4). //[1,2,34]
a. unshift(0) // [0,1,2,3,4]
a. pop() // 4
a. shift() // 0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

what does splice do?

A

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]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

explain var hoisting

A

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;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is es6 Object de-structuring

A
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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is a closure? Why are they useful?

A

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”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

for..of vs for…in

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Template Literals

A

use the back tick syntax for string formatting and multiline strings

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

generator iterable

A
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]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

difference between object.assign vs spread

A

not much, other than spread wasnt standerdized.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

Object.is vs ===

A

=== doesn’t treat NaN as equal

let quantity = NaN;

console. log(quantity === quantity); // false
console. log(Object.is(quantity,quantity)); //true

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What are es6 proxyz. What are common traps

A

Allows you to override, get, set, apply(call function), construct

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

what do you call:

var world ="world";
console.log( `hello ${world}`);
A

template literal

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

what do you call:

function go({one, two, three}){
console.log(`Two is eqaul to ${two}`);
}

foo({one:’hello’,two:’world’,three:”there’});

A

de-construction

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What is this?:

var add = (function () {
  var counter = 0;
  return function () {counter += 1; return counter}
})();

add();
add();
add();

A

javascript closer. Allows ‘counter’ to act as private variable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What an IIFE. (pronounced “Iffy”. hahha)

A

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:

(() => {
  /* */
})()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What is this thing called?

(function() {
 var x = 20;
 var y = 20;
 var answer = x + y;
 console.log(answer);
 })();
A

IIFE. Immediately Involked Function Expression.

Usually used in libraries such as jquery to initialize library at load and protect vars.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

Difference between:

31 == “31”

31 === “31”

A

31 == “31”. // true. auto casting. not checking type

31 === “31” //only true is value and type match

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

what does double exclaim, !!x do?

A

Hard cast to Boolean. useful when truthyness issues pop up.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What is truthyness

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

Separation of concerns

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q
control
vs
Widget
vs
Layer
vs
Tier
vs
A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

Flexibility:

A

“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.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

Maintainability

A

“The ease with which a software system or component can be modified to correct faults, improve performance, or other attributes, or adapt to a changed environment.”:

40
Q

Reusability:

A

“The degree to which a software module or other work product can be used in more than one computing program or software system.”

41
Q

Scalability:

A

“The ease with which a system or component can adjust to changing load.”

42
Q

What is a module “Sandbox”

A

a base layer of functionality that other modules can safely use

43
Q

Difference between Container and component in React

A

Containers are aware of application state.

Component display “dumb” data.

If you need it to be smart and aware of the state (whenever data changes) in the application then make it a container.

44
Q

Higher Order Component

A

Use HOC to enhance components. Allows you to re-use logic (funciton or props) across multiple components. takes a component as a param and returns a new extended component.

import React from ‘react’;

const withSecretToLife = (WrappedComponent) => {
  class HOC extends React.Component {
    render() {
      return (
  );
}   }

return HOC;
};

export default withSecretToLife;

45
Q

How React works? How Virtual-DOM works in React?

A

Runs a diff on a virtual DOM in memory (much faster then manipulating actual DOM) Then only updates actual DOM with diffs

46
Q

What is ReactDOM and what is the difference between ReactDOM and React?

A

Brokebn out from React library. Mounts virtual to actual DOM. useful feature of ReactDOM is ReactDOM.findDOMNode()

47
Q

Q5. What are the differences between a class component and functional component?

A

Class components has access to state and lifecycle Functions are “dump” or “presentation components

48
Q

difference between state and props

A

Sate is internal and mutable. props are passed in from above and immutable.

49
Q

controlled component

A

When a component called parent function to store state. Usually in cases where “lifting state up” is necessary because multiple component need to respond to the state change.

controlled: Form data is stored in React this.state. uncontrolled: Data is left in HTML elements DOM and accessed via ref.

How React handles data. All controls store values in State, and Reac handles submit

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);   }

handleChange(event) {
this.setState({value: event.target.value});
}

handleSubmit(event) {
alert(‘A name was submitted: ‘ + this.state.value);
event.preventDefault();
}

render() {
return (

      Name:

);   } }
50
Q

What is Redux

A

All application state is in a single store. Can only be modified via actions which get reduced. The store is a closure, making it private.

Makes app consistent, easier to test, and easier to deploy

51
Q

What is Redux Thunk used for

A

Allows use to create asyncronous reduc actions. But sags (based on generators instead of promises) are better and cleaner.

52
Q

PureComponent

A

Optimization where component validates, the state or prop change that comes into shouldComponentUpdate really necessitates a Render()

53
Q

How different is React’s ES6 syntax when compared to ES5?

A
require vs import
// ES5
var React = require('react');
 // ES6
import React from 'react';
export vs exports
// ES5
module.exports = Component;
// ES6
export default Component;
component and function
// ES5
var MyComponent = React.createClass({
    render: function() {
        return

<h3>Hello Edureka!</h3>

;
}
});

// ES6
class MyComponent extends React.Component {
    render() {
        return

<h3>Hello Edureka!</h3>

;
}
}

props
// ES5
var App = React.createClass({
    propTypes: { name: React.PropTypes.string },
    render: function() {
        return

<h3>Hello, {this.props.name}!</h3>

;
}
});

// ES6
class App extends React.Component {
    render() {
        return

<h3>Hello, {this.props.name}!</h3>

;
}
}

state

// ES5
var App = React.createClass({
    getInitialState: function() {
        return { name: 'world' };
    },
    render: function() {
        return

<h3>Hello, {this.state.name}!</h3>

;
}
});

// ES6
class App extends React.Component {
    constructor() {
        super();
        this.state = { name: 'world' };
    }
    render() {
        return

<h3>Hello, {this.state.name}!</h3>

;
}
}

54
Q

REACT LifeCYCLE

A

constructor(),
getDerivedStateFromProps(),
render(),
componentDidMount()

getDerivedStateFromProps(), 
shouldComponentUpdate(), 
render(), 
getSnapshotBeforeUpdate() 
componentDidUpdate()

Unmounting: In this last phase, the component is not needed and get unmounted from the browser DOM. This phase includes componentWillUnmount() lifecycle method.

componentWillMount()
componentDidMount()

componentWillReceiveProps()

shouldComponentUpdate()
componentWillUpdate()
componentDidUpdate()

componentWillUnmount()

55
Q

react thunk

A

Promise based middleware for hanlding async Redux Actions

56
Q

react events. synthetic events in React?

A

todo

Sytnhetic events handle cross browser issues.

57
Q
A

Allows you to package multiple components in a return, without having to add a bogus DIV

58
Q

event listeners

A

componentDidMount() {
window.addEventListener(‘resize’, this.handleResize)
}

componentDidUnmount() {
window.removeEventListener(‘resize’, this.handleResize)
}

59
Q

React Context

A

todo: ask Brian

function-as-child pattern

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

For example, authenticated user, locale preference, UI theme need to be accessed in the application by many components.

const {Provider, Consumer} = React.createContext(defaultValue)

60
Q

React Hooks

A

todo: ask Brian

61
Q

why do we need to import React from ‘react’ on the top of the file even if we don’t use React

A

Becuase JSX is syntatic sugar the babbel will expand to code that has explicit React references.

62
Q

why can’t the component directly return multiple elements.

A

React need a tree structure for reconciliation. React.Fragment can solve the issue.

63
Q

why do the Component names in JSX start with capital letter?

A

How react knows whether its a Component or a HTML DOM element

64
Q

What are the main 2 types of components you can declare in React, and when would you use one over another.

A

Class Component (React.Component) vs function components.

65
Q

Which lifecycle function is best to place a request for data from the API?

A

componentDidMount is the best place to put calls to fetch data, for two reasons:

  1. Using didMount makes it clear that data won’t be loaded until after the initial render. This reminds you to set up initial state properly, so you don’t end up with undefined state that causes errors.
  2. If you ever need to render your app on the server (a.k.a. server-side-rendering/SSR with Next.js or similar), componentWillMount will actually be called twice – once on the server, and again on the client – which is probably not what you want. Putting your API call code in componentDidMount will ensure that data is only fetched from the client, where it should be.
66
Q

Why not fetch data in constructor

A

“the data will not be there before render happens” — although not the main reason, it shows you that the person understands the way components are handled; “with the new asynchronous rendering in React Fiber …”

67
Q

What is React Fiber

A

reconciliation algorithm in React. I dont care. hahaha

Its headline feature is incremental rendering: the ability to split rendering work into chunks and spread it out over multiple frames.

68
Q

how would you go about making sure the data is not re-fetched when the component is re-mounted?

A

Best to utilize an framework like GraphQL. Regardless avoid coupling the UI and other layers in an application.

69
Q

Can you explain the idea of “lifting the state up”?

A

Neccessary when Several components need to reflect the same changing data.

sharing state is accomplished by moving it up to the closest common ancestor of the components that need it.

Answers ranging from “it allows to pass data between siblings” to “it allows you to have more pure-presentational components, which make re-usability easier” are preferred. Redux might get mentioned here

70
Q

How to test a string is a number

A

(Number.isNaN(input)) {

71
Q

How would you go about debugging an issue in React code; what tools have you used? How would you go about investigating why a component does not re-render?

A

(eslint, jslint) and debuggers (React Developer Tools).

Using RDT to debug the issue by checking if the component state/props are properly set is a good answer, mentioning using the Developer Tools to setup breakpoints is also a good one.

72
Q

What the debugger called

A

RDT React Developer Tools. There’s also Redux DevTools Extension

73
Q

How to debug React regressions via Github

A

git bisect.

Bisection is a type of search where the search space is halved on every search. The way it works is as follows:

First, you tell Git which version was a good one (meaning it worked) using git bisect good.

Start the process with git bisect start. Git will check out the middlemost revision and then ask you if the current revision is good or bad. (Answer with git bisect good or git bisect bad.) Before answering, you should inspect your application visually to determine this.

Eventually, you should reach a result as Git is able to pinpoint where the functionality broke. Now that you know where things went wrong, you can check the changes introduced in the commit and be able to reason better why it broke the functionality.

74
Q

What is snapshot. testing.

A

First test renders the DOM of a component and then saves it to a file that is checked in. Each time the test is re-run, a diff is run against this “approved” snapshot.

75
Q

inline conditional expressions

A

used to conditional not render some snippet of JSX. Must be wrapped by curlys

const MyComponent = ({ name, address }) => (
  <div>
    <h2>{name}</h2>
    {address &amp;&amp;
      <p>{address}</p>
    }
  </div>
)

<h1>Hello!</h1>

{
messages.length > 0 && !isLogin?
<h2>
You have {messages.length} unread messages.
</h2>
:
<h2>
You don’t have unread messages.
</h2>
}

76
Q

How to create refs?

A

class MyComponent extends React.Component {

  render() {
   Name:  this.inputDemo = input} />
            Click 
  }
}
77
Q

getDerivedStateFromProps

A

arguments to getDerivedStateFromProps are props and state and not nextProps and prevProps

we need to store prevPropsState in state, in order to detect changes.

static getDerivedStateFromProps(props, state) {
    // Note we need to store prevPropsState to detect changes.
    if (
      props.myPropsState !== state.prevPropsState
    ) {
      return {
        prevPropsState: state.myState,
        myState: props.myPropsState
      };
    }
    return null;
  }
78
Q

best lifecycle to add global event handlers

A

componentDidMount() {
window.addEventListener(‘resize’, this.handleResize)
}

79
Q

getSnapshotBeforeUpdate. When is it called in lfecycle. What’s it sued for.

A

After render but before pushing to the DOM. Consider it HTML staging

80
Q

What a portal

A

render children into a DOM node that exists outside the DOM hierarchy of the parent component

render() {
  // React does *not* create a new div. It renders the children into `domNode`.
  // `domNode` is any valid DOM node, regardless of its location in the DOM.
  return ReactDOM.createPortal(
    this.props.children,
    domNode
  );
}
81
Q

Is lazy function supports named exports?

A
No, currently React.lazy function supports default exports only. If you would like to import modules which are named exports, you can create an intermediate module that reexports it as the default. It also ensures that tree shaking keeps working and don’t pull unused components. Let's take a component file which exports multiple named components,
// MoreComponents.js
export const SomeComponent = /* ... */;
export const UnusedComponent = /* ... */;
and reexport MoreComponents.js components in an intermediate file IntermediateComponent.js
// IntermediateComponent.js
export { SomeComponent as default } from "./MoreComponents.js";
Now you can import the module using lazy function as below,
import React, { lazy } from 'react';
const SomeComponent = lazy(() => import("./IntermediateComponent.js"));
82
Q

React.memo

A

Allows you to create PureComponent from functional components (since they dont have access to componentShoudUpdate() )

83
Q

Do Hooks replace render props and higher order components?

A

Both render props and higher-order components render only a single child but in most of the cases Hooks are a simpler way to serve this by reducing nesting in your tree.

84
Q

What is React proptype array with shape?

A

ReactComponent.propTypes = {
arrayWithShape: React.PropTypes.arrayOf(React.PropTypes.shape({
color: React.PropTypes.string.isRequired,
fontSize: React.PropTypes.number.isRequired
})).isRequired
}

85
Q

how does Array destructuring remind you of python?

A
var a = 1, b = 2;
[a , b] = [b , a]
// a=2, b=1
86
Q

func programing: filter()

A

returns the new array of the elements in the array that satisfies the provided testing function.

function isBigEnough(element) {
  return element >= 15;
}

[12, 5, 8, 130, 150].filter(isBigEnough); // [130, 150]

87
Q

func programming: find()

A
returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.
function isBigEnough(element) {
  return element >= 15;
}

[12, 5, 8, 130, 150].find(isBigEnough); // 130

88
Q

func programming: REduce()

A

sum of all elements of an array
var arr = [0, 1, 2, 3, 4]
arr.reduce( (prev, curr) => prev + curr )
//10
arr.reduce( (prev, curr) => prev + curr , 20)
//30

89
Q

Func: Some()

A

[2, 5, 8, 1, 4].some(x => x > 10); // false

[12, 5, 8, 1, 4].some(x => x > 10); // true

90
Q

Func sort()

A
var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers);

// [1, 2, 3, 4, 5]

91
Q

Promise chain via resolve

A
//resolve square of input
var square = function(para) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      console.log('para: ', para)
      resolve(para * para)
    }, 1000)
  })
}
square(2)
   .then(square)
   .then(square)
// para:  2
// para:  4
// para:  16
92
Q

Object.entries (enumerating [key, val] of Obj)

A
const myObj = {id: "mockId", name: "peter"}
Object.entries(myObj).map(([key, value]) => 
    console.log(`${key} : ${value}`)
)
// id : mockId
// name : peter
93
Q

Conditionally adding keys to objects

A
const buildAnObjectFromAQuery = query => ({
  ...query.foo &amp;&amp; { foo: query.foo },
  ...query.bar &amp;&amp; { bar: query.bar },
});
94
Q

REact: shorthand for defaults props to tru

A

as same as

95
Q

List some of the cases when you should use Refs.

A

manage focus, select text or media playback

96
Q

Whats this called? (a>10)?true:false;

A

Ternary