JavaScript Flashcards
What’s the difference between web workers, service workers and web sockets?
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.
What are the four ways to invoke a function in JS?
- Invoking it straight-up using func()
- As a method on an object, which ties the invocation to the object(OOP).
- As a constructor, which creates a brand new object
- Using apply() call()
Describe the differences betwen different positioning in CSS(static, relative, absolute, fixed)
- 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
What is REST?
Representational State Transfer, an architecture style for designing applications.
Stateless, client-server, cacheable protocol to make HTTP calls.
Explain closure in layman’s terms! And what are use cases for them?
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.
What are the basic ideas behind Redux?
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.
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
//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; } } };
What is variable hoisting?
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.
What are some of the ways to optimize SEO as a front-end developer?
- Keywords near the title tags
- Adding meta-description tags that users will find useful.
- Shorter, human-readable URLs with descriptive keywords
- Place content on same subdomain
Recommended: https://example.com/blog Less Ideal: https://blog.example.com
- Adding sitemaps
- Adding social metadata(Twitter, fb)
- Rich Snippets(Schemas for structuring data)
- Performance(Enables Web Cralwers to crawl your site)
What’s a reliable way to check for types in JavaScript?
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]
WTF is JSONP?
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.
What is the for…of loop and what problem does it solve?
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.
What’s the difference between stopPropagation() and preventDefault()?
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!
What is NaN?
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.
What does strict mode do?
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.
What are some ways to optimize performance of websites/things to consider when doing so?
- 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.
- 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.
- 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.
- 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.
- 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. - ‘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.
- Using build tools like webpack you can take advantage of code-splitting and tree-shaking.
- Server-side rendering for initial meaningful paint
- Cache-headers on HTTP’s - expires, cache-control, max-age. HTTP/2 does this automatically
- 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.
- 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.
- Use service workers to take advantage of caching and network fallbacks(offline pages).