JavaScript Flashcards

1
Q

What’s the difference between web workers, service workers and web sockets?

A

Service Worker:
Background service that handles network requests. Ideal for dealing with offline situations and background syncs or push notifications. Cannot directly interact with the DOM. Communication must go through the Service Worker’s postMessage method.

Web Worker:
Mimics multithreading, allowing intensive scripts to be run in the background so they do not block other scripts from running. Ideal for keeping your UI responsive while also performing processor-intensive functions. Cannot directly interact with the DOM. Communication must go through the Web Worker’s postMessage method.

WebSocket:
Creates an open connection between a client and a server, allowing persistent two-way communication over a single connection. Ideal for any situation where you currently use long-polling such as chat apps, online games, or sports tickers. Can directly interact with the DOM. Communication is handled through the WebSocket’s send method.

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

What are the four ways to invoke a function in JS?

A
  1. Invoking it straight-up using func()
  2. As a method on an object, which ties the invocation to the object(OOP).
  3. As a constructor, which creates a brand new object
  4. Using apply() call()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Describe the differences betwen different positioning in CSS(static, relative, absolute, fixed)

A
  • static : default
  • relative : you can set it to wherever you want relative to where it would’ve been in the document flow
  • top, bottom, right, left
  • absolute : positions an item relative to the viewport, or the next parent element that has positioning context
  • use relative on container to create positioning context
  • works when you know the dimensions of container & element(header relative to logo, etc)
  • fixed : fix relative to the viewport while the content scrolls as normal
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is REST?

A

Representational State Transfer, an architecture style for designing applications.

Stateless, client-server, cacheable protocol to make HTTP calls.

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

Explain closure in layman’s terms! And what are use cases for them?

A

1. When you create a function inside another, not only are you creating the function but also a closure that encompasses all the environment variables in the scope(“Safety Bubble”)

2. This safety bubble stays around and isn’t garbage-collected as long as the function itself exists

3. Function Parameters are also included in the safety bubble of closures!!!

4. All variables in the scope, even those declared after the function declaration are included.

Private Variables, Event Handlers, Ajax onSuccess Callbacks, Using callbacks inside loops, Recursion.

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

What are the basic ideas behind Redux?

A

All the application data is stored in a data structure called the state, which is stored in the store

Your app reads the state from this store

The state is never mutated outside the store

Views emit actions that describe what happened

A new state is created by combining the old state and the action by a function called the
reducer

When the store receives an action from the views, the store uses a reducer function to process the action. The store provides the reducer function with the current state and the action. The reducer function returns the new state.

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

Write a sum method which will work properly when invoked using either syntax below :

console. log(sum(2,3)); // Outputs 5
console. log(sum(2)(3)); // Outputs 5

A

//return function if one argument is passed in, otherwise just compute sum.

const sum = function(a) {
 if (arguments.length === 2) {
 return arguments[0] + arguments[1];
 } else if (arguments.length === 1) {
 return function(secondNum) {
 return a + secondNum;
 }
 }
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is variable hoisting?

A
console.log(a);

const a = 1;

This actually prints out undefined, instead of throwing an error.

This is because JavaScript, under the hood, splits the code into declarations and assignments.

So it moves all the declarations(functions and variables) to the top of the code before anything happens.

This exhibits the same behavior inside the function as well(Function scope inside), so it hoists the declarations to the top of the function.

`````````

func();
const func = function() {
 console.log('hey');
};

````````

The following code will throw an error, saying func is not a function. Meaning it has been declared as a variable, but on the first line, the code doesn’t yet know that it’s a function since its body hasn’t been assigned to func variable yet.

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

What are some of the ways to optimize SEO as a front-end developer?

A
  1. Keywords near the title tags
  2. Adding meta-description tags that users will find useful.
  3. Shorter, human-readable URLs with descriptive keywords
  4. Place content on same subdomain

Recommended: https://example.com/blog Less Ideal: https://blog.example.com

  1. Adding sitemaps
  2. Adding social metadata(Twitter, fb)
  3. Rich Snippets(Schemas for structuring data)
  4. Performance(Enables Web Cralwers to crawl your site)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What’s a reliable way to check for types in JavaScript?

A

typeof(null) returns object, so typeof is completely broken.
Instead, we use Object.prototype.toString.call(), which can distinguish between undefined, null, functions, objects, arrays, strings, regex, dates, booleans.

Object.prototype.toString.call(true); // [object Boolean] Object.prototype.toString.call(null); // [object Null] Object.prototype.toString.call(); // [object Undefined]

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

WTF is JSONP?

A

Workaround pre-CORS to get resource from other domains. Only works with JSONP. All you do is provide a callback, and the API will generate a JS file that passes data into that function when it gets run in your browser.

Very limited, limited to GET requests only since scripts can only be GET. Best used for fetching light read-only data, like Weather or News API’s.

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

What is the for…of loop and what problem does it solve?

A

var list = [8, 3, 11, 9, 6], i; // DON’T DO THIS!!!!

for (i in list) {

console.log(list[i]);

}

for-in was exclusively intended for iterating over the enumerable keys of an object, and is not for iterating over arrays. That means iterating over a list with for-in might iterate in arbitrary order. Plus the iteration variable i will be a string.

With the new for..of, we have the ability to break, continue, and we can iterate over iterable collections. DOES NOT work with Objects because they are not ‘iterable’. They have a [Symbol.iterator] property. Nodelists, arguments objects, and strings also work with for..of.

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

What’s the difference between stopPropagation() and preventDefault()?

A

StopPropagation() stops capturing/bubbling. No listeners will be invoked after stopPropagation().

preventDefault prevents the default action the browser makes on that event.(Anchor tag going to link), but it will still bubble up!

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

What is NaN?

A

NaN’s type is number(*Shock*), and represents a number that isn’t really a number, often times the result of a bad calculation.

Ex) “abc”/4

NaN === NaN returns false!

Comparing it against itself returns false. So use isNaN(NaN) instead.

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

What does strict mode do?

A

Strict Mode

Allows the program to run in a ‘strict’ context, and makes debugging easier. - To enable it just type ‘use strict’; at the top of the javaScript file.

You can apply to parts of your code by wrapping it around a function

function newCode() {

“use strict”;

//write code here

}

In strict mode, using a variable that hasn’t been declared previously fails. Without strict mode, JavaScript creates a global variable

testing = 1;

console.log(testing); // logs 1

Can’t use reserved words in future versions of JavaScript

Can’t delete variables or functions

Can’t delete arguments to functions

function moo(arg) {

delete args; // FAILS

}

eval() doesn’t leak out anymore in strict mode. What eval() does is you can pass javaScript expressions as strings and it will be evaluated but in non-strict mode the variables leak!!! so it can cause some headaches.

1. It makes debugging easier.

2. Prevents accidental globals.

3. Eliminates this coercion. Without strict mode, this value of null or undefined is automatically coerced to the global. In strict mode, by default this is undefined.

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

What are some ways to optimize performance of websites/things to consider when doing so?

A
  1. First measure/track. Then you can take a pro-active approach to figuring out the pain points for your users. Use a tool like Lighthouse that recommends best practices.
  2. How do browsers render a web page :

When the user requests a page, the browser fetches the HTML and constructs the DOM, then fetches the CSS and constructs the CSSOM, and then generates a rendering tree by matching the DOM and CSSOM. If any JavaScript needs to be resolved, the browser won’t start rendering the page until it’s resolved, thus delaying rendering.

  • Undertstand the critical rendering path :
  • Constructing the DOM Tree(HTML Path)*
  • Constructing the CSSOM Tree(CSS Path)*
  • Running JavaScript*
  • Creating the Render Tree*
  • Generating the Layout*
  • Painting*

So the critical path essentially relies on three factors: The HTML, CSS and the Javascript.

  1. CSS is render-blocking, but only on current device(You can specify device using media attribute). Why put CSS in the head vs. an external stylesheet file? It’s because we want to reduce or rather try and keep much of the CSS as possible off the critical path by downloading it as quick as possible. When a network request is made, there is latency involved (the dark green, orange and light green blocks). This is something we cannot really eliminate unless the technology for transferring information makes a significant leap. So the point of putting the CSS in the head is to eliminate the latency in the network request, ie there is no network request for the CSS — so it the CSSOM building starts immediately.
  1. Serving assets from a CDN

2. Optimizing images, now you can use srcsets and images to serve different image files and different resolutions. You can use WebP images.

  1. PRPL Pattern - Structure for Progressive Web Apps which emphasizes performance. So Push the critical resources for the initial URL route, Render the initial URL route Pre-Cache the remaining routes, Lazy-Load and create remaining routes on demand.
    - Main entry point of the app : Served from every route. This is small in sizes, and can be cached, cached, cached.
    - App shell : Top-level app logic/router/
    - Rest of the fragments : Lazy-loaded.
  2. ‘Cutting-the-mustard technique’ : DOMContentLoaded(When DOM is constructed) vs. onload(When the entire application is loaded). So load the core experience on DOMContentLoaded, and ‘layer’ on the extras later. Feature detection can also work here.
  3. Using build tools like webpack you can take advantage of code-splitting and tree-shaking.
  4. Server-side rendering for initial meaningful paint
  5. Cache-headers on HTTP’s - expires, cache-control, max-age. HTTP/2 does this automatically
  6. Prefer to load JavaScript asynchronously. Prefer DEFER over ASYNC. This is because even though neither blocks the HTML parser, they can block rendering. ASYNC scripts are parsed and executed as soon as resource is done downloading, but DEFER scripts don’t execute until the HTML document is done parsed. ASYNC can load out-of-order, but DEFER executes in the order they appear in the markup.
  7. Push Critical CSS quickly - So the ‘above-the-fold’ CSS can be added inline in the head of the page so that you don’t have to make a separate request for it.
  8. Use service workers to take advantage of caching and network fallbacks(offline pages).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Describe the structure of a basic web app and what each part does

A

Client, Server, Database

Client : What users interact with - the structure, look, feel and interactivity of the web app

Server : What listens to requests from the client. An HTTP server would listen to a port(Different channels on each computer) number.

Database : Place to store information so it can be accessed/managed/updated.

18
Q

Does JavaScript pass parameters by value, or by reference?

A

Primitives are passed by value(Strings, booleans, numbers). Objects are passed by reference.

  • **You can only change the properties of the objects being passed by reference, NOT what the variable points to.**
    ~~~
    var a = {‘moo’: ‘too’};
    function foo(a) {
    a = {‘too’: ‘moo’};
    };
    foo(a);
    console.log(a); //{‘moo’: ‘too’};
    ~~~
19
Q

What’s the difference between null and undefined?

A

Undefined is a type the JavaScript engine sets to variables that have been initialized but don’t have a value assigned to them.

Only a program will set a value to null. Null represents the absence of a value

20
Q

What information do HTTP request headers contain?

A

Request type(GET/POST/PUT/DELETE),

Status Code,

Content-Type,

User-Agent,

Cookie,

Post Body

21
Q

How would you implement a tooltip that shows up on mousehover like this :

We have markup of button with dataset attribute like this :

<button>Short button</button>

<button>One more button</button>

A

We use event delegation: set up two handlers on document to track all “overs” and “outs” from elements with data-tooltip and manage tooltips from there.

mouseover triggers when a pointer comes over an element.

mouseout triggers when a pointer leaves an element.

Full Script :

let tooltipElem;

**document.onmouseover = function(event) {
 let target = event.target;**
**// if we have tooltip HTML...
 let tooltipHtml = target.dataset.tooltip;
 if (!tooltipHtml) return;**

// …create the tooltip element

tooltipElem = document.createElement(‘div’);
tooltipElem.className = ‘tooltip’;
tooltipElem.innerHTML = tooltipHtml;
document.body.append(tooltipElem);

**// position it above the annotated element (top-center)
 let coords = target.getBoundingClientRect();**
**let left = coords.left + (target.offsetWidth - tooltipElem.offsetWidth) / 2;
 if (left \< 0) left = 0; // don't cross the left window edge**
**let top = coords.top - tooltipElem.offsetHeight - 5;
 if (top \< 0) { // if crossing the top window edge, show below instead
 top = coords.top + target.offsetHeight + 5;
 }**

tooltipElem.style.left = left + ‘px’;
tooltipElem.style.top = top + ‘px’;
};

document.onmouseout = function(e) {

if (tooltipElem) {
tooltipElem.remove();
tooltipElem = null;
}

};

22
Q

What’s the difference between these two :

#header.callout { }

#header .callout { }

as well as :

Double Class

.three.four { color: red; }​

A

“#header .callout”:

Select all elements with the class name callout that are decendents of the element with an ID of header.

“#header.callout”:

Select the element which has an ID of header and also a class name of callout.

23
Q

What’s the difference between == and ===?

A

=== checks for value and type. JavaScript is loosely typed so == only checks for value and results in type coercion before comparing

24
Q

Explain the four different function contexts ‘this’ can take in JavaScript

A
  1. When a function is invoked just the normal way using func(). The context is global, or window.
  1. Invoked as a method - That object left to the method call dot at call time is the function context.

Ex)

function creep(){ return this; }

assert(creep() === window,

“Creeping in the window”);

var ninja1 = {

skulk: creep

};

assert(ninja1.skulk() === ninja1,

“The 1st ninja is skulking”);

  1. Invoked as a constructor using ‘new’

What happens when an object is created using a constructor ?

a) New empty object is created
b) That object is passed to the parameter as the this keyword, and becomes the function context
c) If there isn’t an explicit return value, this object is returned

  1. Invoked with apply(), call()

Function contexts are explicitly set.

25
Q

Why would we want to use anonymous functions in JavaScript?

A

We want to store them in a variable for later use, and pass them around as arguments, etc.

Or, we’re making methods on an object.

Or, we’re using it as a callback in an event handler.

You can actually name them(Called inline names)

26
Q

What’s CORS?

A

CORS(Cross-Origin Resource Sharing) : Workaround for the same-origin policy. It’s usually enabled on the server-side. Same-origin policy ensures that scripts in one website doesn’t execute in another.

A resource makes a cross-origin HTTP request when it requests a resource from a different domain, protocol, or port to its own. For example, an HTML page served from http://domain-a.com makes an src request for http://domain-b.com/image.jpg. Many pages on the web today load resources like CSS stylesheets, images, and scripts from separate domains.

It’s the response that’s blocked.

It works differently with PUT/POST/DELETE - A pre-flight request is an HTTP request with options(Access-Control-Request-Method), basically asking “I want to send a PUT request, is this allowed?”. Then the server sends a response back with (Access-Control-Allow-Methods: PUT) if it’s allowed. If this pre-flight handshake, only then does it actually issue its original request.

This is because if there were no pre-flight checks, with PUT requests, since the response is the only thing that’s blocked the issued request would successfully make changes on the server, but the response wouldn’t come back. To prevent this, we have pre-flight checks.

27
Q

What happens when you enter google.com on a browser?

A

1) The browser takes your URL, communicates with your ISP to do a DNS lookup of the IP address for the web server that hosts google.com

2) The DNS server sends the IP address back to the ISP, ISP sends it back to your browser
3) The browser takes the IP address & given port number from the URL and opens a TCP socket conncetion. Your browser & the web server are connected.
4) Browser sends a HTTP request to the web server for index.html
5) Web server sends back the html, which the browser takes it, parses it and looks for assets. Then the browser loads the page and closes the connection.

28
Q

What is the prototype chain in JavaScript?

A

Prototypes are containers you can delegate property lookups to, if the lookup fails on the original object.

All functions have the prototype property, which initially is an empty object. It doesn’t serve much use until called with a constructor.

29
Q

What’s event delegation, bubbling and capturing, and what are their benefits?

A

The event is fired by the root node and goes all the way down to the target, then BACK UP from target —-> root. (BTW, what’s the difference between target and currentTarget)? currentTarget is the element that listens to the event(The outer element the event bubbles to), target is the actually clicked element.

Event Capturing Phase : bubbling ‘down’ from the document all the way to the specific node, Generally not used because of lack of support in older browsers

Capturing and bubbling allow to implement event delegation. So the idea is that if we have a lot of elements handled in similar fashion, instead of assigning handlers to each element, we put a single one on the common ancestor.

Basic Algorithm :

  1. Put a single handler on the container.
  2. In the handler – check the source element event.target.
  3. If the event happened inside an element that interests us, then handle the event.

Benefits :

  1. Simplifies initialization and saves memory: no need to add many handlers.
  2. Less code: when adding or removing elements, no need to add/remove handlers.
  3. DOM modifications: we can mass add/remove elements with innerHTML and alike.
30
Q

What are the different types in JavaScript, and what’s the best way to check for type?

A

Primitives : Booleans, Strings, Numbers, Null, Undefined

vs . Objects

using typeof() doesn’t work because it returns ‘Object’ for null.

31
Q

What is a query string and what does it do?

A

A way to maintain state inside a URL.

URLs can be broken down into protocol, location of the file, and query string.

When a user makes a query according to certain criteria, the querystring is automatically input into the URL.

Protocol is almost alwyas HTTP.
Location is the form of hostname + filename(www.google.com/index.html)
And query string is what follows the ?

32
Q

What’s a CDN?

A

Content Delivery Network,

It’s a large distributed system of ‘proxy’ servers deployed across mahny data centers in the world. It’s a server that acts as an intermediary between a client and server.

33
Q

What are some of the ways we can make our website accessible?

A

1 - Perceivable

Four broad categories from Web Accessibility Initiative:

1. Perceivable : Information should be presentable to users.

2. Operable : UI Components and navigation must be operable.

3. Understandable : Information and UI must be understandable.

  • *4. Robust** : Content must be able to be interpreted by different user-agents(Assistive technologies).
  • Images(Altattributes), Video/Audio(Trackelements to provide transcriptions),Labels for UI Components.
  • Semantic Markup/ Site should have a logical flow without any CSS.
  • Meaningful information should not be conveyed solely via sensory characteristics.(ex : Delete button with ‘Delete’ vs. just a trash icon)
  • Contrast ratio of text/background, resizable text.
  • All functionality should be operable from a keyboard
  • Ensure all functional elements have a clear focus state.
  • Browsers do this by default, don’t override it.
  • Outline around buttons, input, etc. Can use pseudo-selectors :focus to change
  • Provide information about current location, provide navigation
  • Specify language
  • Input Assistance
  • Provide labels and instructions
  • Error messages/Error prevention/Form validation

Rules for using ARIA :

  • ARIA roles are added to HTML markup like an attribute. They define the type of element and suggest what purpose it serves.
  • -* Aria attributes : Two types -
    1. The value of states are bound to change as a result of user interaction.
    2. The value of properties is less likely to change.
  • For example, you’re using a instead of a checkbox .

aria-checked=”true” tabindex=”0” id=”simulatedcheckbox”>

  • Use Semantic Markup As Much As Possible
34
Q

What’s the JavaScript event loop?

A

JavaScript I/O is non-blocking(This includes HTTP requests, database operations and disk reads and writes) :

35
Q

What is debounce, throttle and explain the differences as well as use cases for each one.

A

Debounce technique allows us to ‘group’ multiple sequential calls(Sudden burst of events, like keystrokes or clicks) into a single one.

It will essentially return a function, that, as long as it continues to be invoked, will NOT be triggered. The function will be called AFTER it stops being called for the ‘threshold’ miliseconds.

If ‘immediate’ is passed, trigger the function on the leading edge, instead of the trailing.

//Example : Resizing a browser window, we're only interested in the final value after the user STOPS resizing.
//Making ajax request on keypress on autocomplete form, we want to WAIT to the last letter typed
//Form validation for "Your password is too short".

Two types of debouncing :
1. Waits before triggering the function, until the events stop happening so rapidly.

  1. Triggers the function immediately. (Use a “leading” flag)

Throttle prevents our function from executing more than once EVERY X miliseconds.

Example : Infinite Scrolling. We want to check how far from the bottom the user is, and render more content to the page. If we used _debounce, it would trigger only when the user stops scrolling. But with throttle, we can check ever 200ms(for example) your scroll position to trigger an event.

const debounce = function(fn, threshold, immediate) {
 let timer;
 //return a fuction that clears previous timeout, saves the function's context, and invokes it immediately OR with a delay depending on the flag
return function() {
 const context = this;
 const args = arguments;
//If the function is NOT already in a timeout, and immediate is true, we have to call it now.
 const callNow = immediate && !timer;
const later = () =\> {
 //clear it because we want to let the next execution run when in 'immediate' mode.
 timer = null;

if (!immediate) {
fn.apply(context, args);
}
};

//Each time the timer is called within threshold, it will be cleared(which is what we want).
 clearTimeout(timer);
//make a new timer
 timer = setTimeout(later, threshold || 200);
//Normally, we want the function to WAIT for the threshold and then execute(On the trailing side). If we want to fire RIGHT away,
 if (callNow) fn.apply(context, args);
 };
};

const throttle = function(fn, threshold) {
let timer;
let lastCalledTime;
let args;
let context;

return function() {
 args = arguments;
 context = this;
//check if we're within the threshold by calculating current date - lastCalledTime and comparing it to threshold
 let pastThreshold = new Date() - lastCalledTime \> threshold;
if (!lastCalledTime || (pastThreshold && !timer)) {
 //reset lastcalledtime
 lastCalledTime = new Date();
 //call right away
 return fn.apply(context, args);
 } else {
 if (!timer) {
 timer = setTimeout(() =\> {
 lastCalledTime = new Date();
 fn.apply(context, args);
 //set it to null.
 timer = null;
 }, threshold);
 }
 }
 };
};
36
Q

What’s a Single-Page-App and its benefits/cons vs. a multi-page-web application?

A
  1. Enhanced user experience - The most famous SPA, Gmail, it doesn’t refresh based on each user interaction. Instead, with SPAs you don’t have to request HTML all the way to the server and back, but only data gets sent back and forth through the wire(Usually in JSON). So there is a lot less bandwidth and time spent, and there is no full page reload. The initial request might be slower, because the browser has to fetch one HTML/CSS/bundled up JavaScript, but after that it’s just a bunch of API calls.
  2. Easier to deploy in production(client part at least). We only need a static server to serve index.html, CSS bundle, and JavaScript bundle.
  3. You can make it work offline.

Disadvantages

Client MUST have JavaScript enabled for SPA’s to even work.

SEO issues - Google recently released that the crawlers CAN crawl SPA’s, but there are reports that indicate otherwise. Hence, ‘universal’ or ‘isomorphic’ applications - sends pre-rendered HTML from the server before delegating to client-side.

Performance - Amazon 100ms 1% revenue, Twitter spent 1 year and 40 engineers to do server-side rendering vs. client-side rendering

Conclusion : If your app is mostly data-driven(Gmail), SPA’s are the way to go. If it’s a service page, and mostly for display, static websites ftw!

37
Q

Explain MVC, MVP and MVVW and the differences between each one.

A

An architectural design pattern that organizes an application through separatino of concerns. So it isolates the Model(Business Data) from the UI(View) and a Controller that manages the business logic.

Model : Business Data

  • When model changes, it notifies its observers that a change occurred so the view can react accordingly.
  • Example : In a JavaScript photo gallery application, a photo would be a model of its own. A specific photo would be stored as an instance of a model. You can also group multiple models into ‘Collections’(Photo Gallery for example)

View : UI

  • Visual representation of the model that present a view of the current state.
  • Templatings are important here because templating for markup containing variables can be convenient here. And data can be dynamically injected.
  • Views are dumb, and rely on the controller to handel any user-interactions.

Controller : Managing logic & User-Input, Handling user interaction

  • Intermediary between Model & View
  • Update the model when the user manipulates the view

MVC Benefits :

  1. Unit tests for business logic is straight-forward
  2. Developers can work on the application simultaneously because one person can work on the business logic, the other on theUI, etc

MVP(Presenter) : It’s a component that containst he UI-business logic for the view. Presenters sit at the same level as views, listening to events from both the View and Model.
MVVW(ViewModel) : You create view-specific Model which contains state & logic information, so there is no need to expose the entire Model to a View. The View can bind to properties on the ViewModel. With MVVW you don’t have to expose an entire model to the view like you do in MVC, so it’s a bit more secure.

38
Q

How do you create modules in JavaScript? Why do you need to bundle them? What’s tree-shaking?

A

Just like how good authors divide their books into chapters and sections, programmers divide their code into modules.

Native module patterns :

  1. IIFEs
  2. Global Import(jQuery as an example) : We pass in globals as parameters, and expose the methods by extending the globals while hiding away the implementation inside separate scope.
  3. Object interface & Revealing module pattern : Return an object containing only the interface/API you want to expose

CommonJS & AMD

  1. CommonJS(module.exports & require). Syntax is simple and easy to use, but it loads it synchronously, one by one. In the browser, if a module is loading, the browser can’t do anything else. Imports are also copies of exports and not ‘live’.
  2. AMD - For loading modules asynchronously. Doesn’t support file I/O though.
  3. ES6 native modules : Imports are resolved at compile time, unlike CommonJS & AMD, so we can actually get rid of exports that aren’t used by other modules before we run the code.

Module Bundling

  • You bundle your modules into one so that when a user visits your website, their browser only has to make one request for one JavaScript file, versus multiple modules.
  • If you’re using modules that the native browser can’t understand(ES6 modules, CommonJS, etc), you need a bundler like Browserify, Webpack.
  • For bundling CommonJS, browserify does a recursive search(Probably with DFS under the hood) to find all dependencies.
  • Webpack! It provides ‘code-splitting’ : A way to split your codebase into chunks, and load it based on demand however you want. You can choose to load only the parts that are needed instead of having the users deal with the payload of downloading everything.

Tree-Shaking

  • Looks at your code to see which of the imports you’re actually using, and the tree-shaken code only includes code from the imports that you actually need and use.

How to use ES6 imports(Not supported in the browser yet)

  • Use babel, rollup, or webpack
  • ES6 module loader API.
39
Q

What’s the difference between GET vs POST request?

A

So first of all, with GET you’re requesting data from a resource whereas with POST you can send data to a resource.

You CAN send data through a GET - but it has to be done through the URL(so it’s cached and saved in the browser history, as well as server logs). So it is far less secure - Also only ASCII characters are allowed.

With POST there is no limitation on the data-type, the parameters are NOT saved in the browser history. So it’s best to use POST for sending sensitive information like user credentials.

40
Q

What’s the CAP Theorem?

A

Consistency, Availability, and Partition Tolerance.
CAP Theorem : It’s impossible for a distributed software system to simultaneously provide more than two out of these three.
So tradeoff among CAP is the first thing we want to consider.

**Consistency :** All users see the same data at the same time. Every read receives the most recent write/error. This is a matter of synchronizing the data across all our servers.

  • Patterns include :
  • Weak consistency : After a write, reads may or may not see it. Best effort approach is taken. Ex : You’re on the phone and lose reception for a few seconds - when you regain connection you don’t hear what was spoken during connection loss.
  • Eventual consistency : After a write, reads will eventually see it(within milliseconds). Data is replicated asynchronously. Ex : **DNS & Email, Amazon S3, SMTP, Search Engine Indexing**
  • Strong consistency : After a write, reads will see it. Data is replicated right away & synchronously. This approach is seen in file systems and Relational Database Manage Systems. Strong consistency works well in systems that need transactions.
  • Transfer $$$ from A ===> B
  • What if something happens in between?
    **Availability :** Every request gets a response on success/failure. Availability is achieved by replicating the data across different servers.
  • Patterns Include :
  • Data Replication(Master-Slave, Master-Master, Tree, Buddy Replication)
  • Fail-over(Active-Active, Active-Passive)
  • _Disadvantages_ : Needs more hardware & Additional complexity. Potential for data loss if active system FAILS before data replication happens
    **Partition Tolerance :** System continues to work despire partial failure/message loss. It can sustain any amount of network failure that doesn’t result in failure of the entire network. Data is sufficiently replicated across combinations of nodes and networks to keep the system up through outages.

**BRILLIANT article explained through a simple Husband & Wife Company : **

  • http://ksat.me/a-plain-english-introduction-to-cap-theorem/
  • Consistency: You customers, once they have updated information with you, will always get the most updated information when they call subsequently. No matter how quickly they call back
  • Availability: Remembrance Inc will always be available for calls until any one of you(you or your wife) report to work.
  • Partition Tolerance: Remembrance Inc will work even if there is a communication loss between you and your wife!
41
Q

What are some ways to query the DOM? Explain the tradeoffs between each approach.

A

.querySelectorAll() or .getElementsByClassName().

The difference is that .querySelectorAll() returns a static NodeList that’s not live.

.getElementsByClassName() returns a live HTMLCollection. Both are array-like objects.

42
Q

What’s the difference between localStorage, sessionStorage, cookies, and indexedDB

A

localStorage & sessionStorage are part of HTML5 Web Storage API.

localStorage : Good for small amounts of data, SYNCHRONOUS, Strings-Only key-value storage. Good for things like user sessions. It WILL block requests and make users wait. It survives reloads.

SessionStorage : Similar to localStorage but is destroyed when the tab is closed.

Cookies : Good for authentication, much more secure since HTTP-only flag prevents external JavaScript from accessing it. So tokens can be hashed and saved as cookies. Included with EVERY HTTP request, can slow down connections. Limited to 4KB.

IndexedDB : The new child on the block, it’s a full DB that can store much more data. It’s asynchronous and provides indexes as well. It can serve all the data your app needs to WORK OFFLINE, for example. The API is slightly more complex as a result.