Miscallaneous 4 Flashcards

1
Q

undefined vs not defined

can you check if it’s undefined or not defined

boolean(undefined) vs number(undefined)

A

undefined is not the same as not defined (when you don’t declare the var, so it’s not in the memory), it’s a value that takes up memory space, which you can check for if (a === undefined)

Boolean(undefined) // false
Number(undefined) // NaN

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

Why do you need immutable state?

A

Immutability is about values
Immutability means that change is not done on the same object,structure, but change is represented in new one. And this is because reference represents value not only memory pointer. Every change creates new value and doesn’t touch the old one. Such clear rules gives back the trust and code predictability. Functions are safe to use because instead of mutation, they deal with own versions with own values.

Using values instead of memory containers gives certainty that every object represents specific unchangeable value and it is safe to use it.

Immutable structures are representing values.

https: //www.youtube.com/watch?v=4LzcQyZ9JOU
- —

Predictability

Mutation hides change, which create (unexpected) side effects, which can cause nasty bugs. When you enforce immutability you can keep your application architecture and mental model simple, which makes it easier to reason about your application.

Performance

Even though a new instance needs to be created where existing values need to be copied and new values need to be added to the new Object which cost memory, immutable Objects can make use of structural sharing to reduce memory overhead.

All updates return new values, but internally structures are shared to drastically reduce memory usage (and GC thrashing). This means that if you append to a vector with 1000 elements, it does not actually create a new vector 1001-elements long. Most likely, internally only a few small objects are allocated.

You can read more about this here.

Mutation Tracking

Besides reduced memory usage, immutability allows you to optimize your application by making use of reference- and value equality. This makes it really easy to see if anything has changed. For example a state change in a react component. You can use shouldComponentUpdate to check if the state is identical by comparing state Objects and prevent unnecessary rendering. You can read more about this here.

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

state

A
  • immutable state - you cannot reassign your state value, you have to use set state which creates new instance of a state and then assigns the new property to it
  • setting state is asynchronous, console.log logs the previous state of what is on the screen.
  • state is local to component, can’t be accessed in another one, so you can have different states for name for each input
  • global state - state var that all components can access - data flow passed down the chain; the parent is not changed from below, but below changes from parent. You can’t skip a level.

Creating a global state in React is one of the first signs that you may need Redux (or another state management library such as MobX) in your application, because in React the local state is located on a component level. Hence you cannot have a real global state in React.

An object is never updated, but copied before changing it.

This applies to React in many places.

For example, you should never mutate the state property of a component directly, but only through the setState() method.

In Redux, you never mutate the state directly, but only through reducers, which are functions.

The question is, why?

There are various reasons, the most important of which are:

Mutations can be centralized, like in the case of Redux, which improves your debugging capabilities and reduces sources of errors.

Code looks cleaner and simpler to understand. You never expect a function to change some value without you knowing, which gives you predictability. When a function does not mutate objects but just returns a new object, it’s called a pure function.

The library can optimize the code because for example JavaScript is faster when swapping an old object reference for an entirely new object, rather than mutating an existing object. This gives you performance.

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

redux or context API

A
  • If you are using Redux only to avoid passing props down to deeply nested components, then you could replace Redux with the Context API. It is exactly intended for this use case.
  • On the other hand, if you are using Redux for everything else (having a predictable state container, handling your application’s logic outside of your components, centralizing your application’s state, using Redux DevTools to track when, where, why, and how your application’s state changed, or using plugins such as Redux Form, Redux Saga, Redux Undo, Redux Persist, Redux Logger, etc…), then there is absolutely no reason for you to abandon Redux. The Context API doesn’t provide any of this.
  • And I personally believe that the Redux DevTools extension is an amazing, underestimated debugging tool, which justifies by itself to keep using Redux.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

useEffect and http request

A
  • useEffect is to manage side effects; http request is a typical side effect
  • get executed after every render cycle
  • if you fetch in the body of the component you’ll end up with infinite state, because the component rerenders every time you update state, same in useEffect, unless you put the second argument, an empty array. This makes it function like componentDidMount and it only renders on mount once.
  • the second argument of array usually holds a dependency, change of which should trigger rerender

see component lifecycle image

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

Array.from()

Array like objects

A

The Array.from() static method creates a new, shallow-copied Array instance from an array-like or iterable object.

It’s not constructed by Array or with an Array literal [], and so (usually) won’t inherit from Array.prototype.

Some objects in JavaScript look like an array, but they aren’t one. That usually means that they have indexed access and a length property, but none of the array methods. Examples include the special variable arguments, DOM node lists, and strings.

For instance, strings are both iterable (for..of works on them) and array-like (they have numeric indexes and length).

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

.reduce examples

arguments

initial value

A

.reduce(function(accumulator, currentValue) {
return accumulator + currentValue
})

const average = euros.reduce((total, amount, index, array) => {
  total += amount
  return total/array.length
}, 0);

The accumulator starts as initialValue.
If you don’t pass initial value it uses the first element of the array as the accumulator and starts at the second element.

You can tally an array. 
const fruitBasket = ['banana', 'cherry', 'orange', 'apple', 'cherry', 'orange', 'apple', 'banana', 'cherry', 'orange', 'fig' ];
const count = fruitBasket.reduce( (tally, fruit) => {
  tally[fruit] = (tally[fruit] || 0) + 1 ;
  return tally;
} , {})

count // { banana: 2, cherry: 3, orange: 3, apple: 2, fig: 1 }

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

How to get the index of an iteration in a for-of loop in JavaScript

A

A for-of loop, introduced in ES6, is a great way to iterate over an array:

for (const v of [‘a’, ‘b’, ‘c’]) {
console.log(v)
}
How can you get the index of an iteration?

The loop does not offer any syntax to do this, but you can combine the destructuring syntax introduced in ES6 with calling the entries() method on the array:

for (const [i, v] of [‘a’, ‘b’, ‘c’].entries()) {
console.log(i, v)
}

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

side effect

application state vs session state vs db

why not have side effects

A

Application state is a data repository available to all classes. Application state is stored in memory on the server and is faster than storing and retrieving information in a database. Unlike session state, which is specific to a single user session, application state applies to all users and sessions. Therefore, application state is a useful place to store small amounts of often-used data that does not change from one user to another.

A side effect is any application state change that is observable outside the called function other than its return value. Side effects include:
Modifying any external variable or object property (e.g., a global variable, or a variable in the parent function scope chain)
Logging to the console
Writing to the screen
Writing to a file
Writing to the network
Triggering any external process
Calling any other functions with side-effects
Side effects are mostly avoided in functional programming, which makes the effects of a program much easier to understand, and much easier to test.

Master the JavaScript Interview: What is Functional Programming?
Eric Elliott

can affect performance
cause unnecessary rerender cycles in react

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

pure function

A

A pure function are a foundation of the functional programming.

  1. The function always returns the same result if the same arguments are passed in. It does not depend on any state, or data, change during a program’s execution. It must only depend on its input arguments.
  2. The function does not produce any observable side effects such as network requests, input and output devices, or data mutation.

example of non pure:
let array = [1, 2, 3]
function add(el){
return array.push(el)
}
takes something outside of function and modifies it
1. has side effects - mutates the array 2. depends something outside of it

shouldn’t use anything that’s not an input, like a global function
if you add array as an argument, you remove 2nd issue, but not 1st

inputs should be immutable

In a pure function context, the mutation of variables is considered a side effect and therefore a function where the mutation occurs, especially of variables that live beyond the execution of the function, is not pure.

if you return […array, el]
it will return a new array

usually same input always produces same output
except
Math.random()
so this can’t be used anywhere in a pure function

easy to use and test
you can change a pure function anytime and it won’t influence anything
simple to unit test, no mocks to create

downside: can’t access db, or files
need to try to write to pure function, impure only if you need to interact with something.
https://www.youtube.com/watch?v=fYbhD_KMCOg

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

a || a ===0
false || true
undefined || ’string’

A
  • a || a ===0 triple equal has higher precedence than or, so it will run first
  • false || true will evaluate to true
  • because the above returns true, undefined || ’string’ will return the string, because that can be coerced to true
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

object literal

A

In plain English, an object literal is a comma-separated list of name-value pairs inside of curly braces. Those values can be properties and functions. Here’s a snippet of an object literal with one property and one function.

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

namespace

A

A namespace is a container which allows developers to bundle up functionality under a unique, application-specific name. In JavaScript a namespace is just another object containing methods, properties, and objects.

It’s important to note that in JavaScript there’s no language-level difference between regular objects and namespaces.

Is just saying that this means a “namespace” is just a object used as a “namespace”.

There are no “real” namespaces in JS.

You can make objects as different languages that have greet on it, but call them as english.greet vs spanish.greet

js doesn’t have namespace, we fake it to make sure we don’t have namespace collisions = 2 things named the same

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

json

convert to object and back

A

object notation vs object literal
xml = wasted download bandwidth, repeated tags etc
* string of data that looks like object literal, but properties have to be wrapped in quotes - json is subset of object literal syntax, meaning all json is valid object literal syntax but not the other way around
* JSON.stringify(object) will convert the object to json string
JSON.parse() convert string to object
* and the opposite

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

what happens to function expression in execution phase

A

the function expression evaluates to a value that’s put in the variable

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

memoize

A

React.memo

  • why is default rerendering static child?
  • memoize only works on static child
  • if you change props it will not work
  • styles passed to child will rerender if memoized, because js can’t compare objects, and styles are objects
  • if you pass in functions same will happen
  • you can fix this by passing setIncrement in and set function inside the child
  • if you set a function and pass it in the return within parent it will still rerender - inline function, because the function is still recreated, because when you update increment, the entire function body gets called again
  • unless you use useCallback
    see image here
  • if you compare objects, it’s comparing the pointers and it will be false because pointers are different
  • shallow vs deep comparison?
  • same for arrays, as arrays are objects
  • if you pass in another component, it will turn into an object
  • objects that are defined outside of your component will not rerender
  • moved to function from classes; realistically classes don’t exist in js; movement towards functional programming
  • react doesn’t have 2 way data binding?
17
Q

non destructive vs destructive methods in js

A
concat()
filter()
find()
forEach()
includes()
join()
map()
reduce()
slice()
sort()
toString()
slice()

spread operator
with slice, instead of push

For object literals (new in ECMAScript 2018):
let objClone = { ...obj }; // pass all key:value pairs from an object 
let newObj = {...obj, key: value}

destructive:

pop()
push()
reverse()
shift()
unshift()

https://www.youtube.com/watch?v=4LzcQyZ9JOU