JavaScript Flashcards Preview

Front-End > JavaScript > Flashcards

Flashcards in JavaScript Deck (42)
Loading flashcards...
1

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.

2

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

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

3

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

4

What is REST?

 

Representational State Transfer, an architecture style for designing applications.

 

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

5

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.

6

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.

 

7

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;
      }
   }
};



 

8

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.

9

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

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

5. Adding sitemaps

6. Adding social metadata(Twitter, fb)

7. Rich Snippets(Schemas for structuring data)

8. Performance(Enables Web Cralwers to crawl your site)

10

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]

11

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. 

12

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

13

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!

 

14

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.

15

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.

16

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

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.

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

3. PRPL PatternStructure 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.

4. '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.

5. Using build tools like webpack you can take advantage of code-splitting and tree-shaking. 

6. Server-side rendering for initial meaningful paint

7. Cache-headers on HTTP's - expires, cache-control, max-age. HTTP/2 does this automatically

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

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

10. Use service workers to take advantage of caching and network fallbacks(offline pages).

17

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

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

Does JavaScript pass parameters by value, or by reference?

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

What's the difference between null and undefined?

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

What information do HTTP request headers contain?

 

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

Status Code,

Content-Type,

User-Agent,

Cookie,

Post Body

21

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

We have markup of button with dataset attribute like this : 

 

 

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

What's the difference between these two :

#header.callout { }

#header .callout { }

as well as :

 

Double Class

 

.three.four { color: red; }​

 

"#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

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

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

24

Explain the four different function contexts 'this' can take in JavaScript

1. When a function is invoked just the normal way using func(). The context is global, or window.

----------------------------------------------------------------------------

2. 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");

---------------------------------------------------------------------------

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

----------------------------------------------------------------------------

4. Invoked with apply(), call()

Function contexts are explicitly set. 

25

Why would we want to use anonymous functions in JavaScript?

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

What's CORS?

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

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

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

What is the prototype chain in JavaScript?

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

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

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

Event Bubbling Phase :  IE, Firefox, Chrome and Safari bubble up to window object - start at the most specific element and flow upward toward the document. This is the default if you don't specify which one you want to deal with.
-----------------------------------------------------------------------------------------------------
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

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

Primitives : Booleans, Strings, Numbers, Null, Undefined

 vs . Objects

--------------------------------------------------------------------------------------

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