Interview Questions 2 Flashcards

1
Q

Why is extending built-in JavaScript objects not a good idea?

A

Extending a built-in/native JavaScript object means adding properties/functions to its prototype. While this may seem like a good idea at first, it is dangerous in practice. Imagine your code uses a few libraries that both extend the Array.prototype by adding the same contains method, the implementations will overwrite each other and your code will break if the behavior of these two methods is not the same.

The only time you may want to extend a native object is when you want to create a polyfill, essentially providing your own implementation for a method that is part of the JavaScript specification but might not exist in the user’s browser due to it being an older browser.

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

Difference between document load event and document DOMContentLoaded event?

A

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

window’s load event is only fired after the DOM and all dependent resources and assets have loaded.

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

What is the difference between == and ===?

A

== is the abstract equality operator while === is the strict equality operator. The == operator will compare for equality after doing any necessary type conversions. The === operator will not do type conversion, so if two values are not the same type === will simply return false. When using ==, funky things can happen, such as:
1 == ‘1’; // true
1 == [1]; // true
1 == true; // true
0 == ‘’; // true
0 == ‘0’; // true
0 == false; // true

My advice is never to use the == operator, except for convenience when comparing against null or undefined, where a == null will return true if a is null or undefined.

var a = null;
console.log(a == null); // true
console.log(a == undefined); // true

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

Explain the same-origin policy with regards to JavaScript.

A

The same-origin policy prevents JavaScript from making requests across domain boundaries. An origin is defined as a combination of URI scheme, hostname, and port number. This policy prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page’s Document Object Model.

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

duplicate([1, 2, 3, 4, 5]); // [1,2,3,4,5,1,2,3,4,5]

A

function duplicate(arr) {
return arr.concat(arr);
}
OR
const duplicate = (arr) => […arr, …arr];

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

Why is it called a Ternary expression, what does the word “Ternary” indicate?

A

“Ternary” indicates three, and a ternary expression accepts three operands, the test condition, the “then” expression and the “else” expression. Ternary expressions are not specific to JavaScript and I’m not sure why it is even in this list.

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

What is “use strict”;? What are the advantages and disadvantages to using it?

A

‘use strict’ is a statement used to enable strict mode to entire scripts or individual functions. Strict mode is a way to opt into a restricted variant of JavaScript.

Advantages:

Makes it impossible to accidentally create global variables.
Makes assignments which would otherwise silently fail to throw an exception.
Makes attempts to delete undeletable properties throw an exception (where before the attempt would simply have no effect).
Requires that function parameter names be unique.
this is undefined in the global context.
It catches some common coding bloopers, throwing exceptions.
It disables features that are confusing or poorly thought out.
Disadvantages:

Many missing features that some developers might be used to.
No more access to function.caller and function.arguments.
Concatenation of scripts written in different strict modes might cause issues.

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

Create a for loop that iterates up to 100 while outputting “fizz” at multiples of 3, “buzz” at multiples of 5 and “fizzbuzz” at multiples of 3 and 5.

A

function fizzBuzz(n) {
for (let i = 0; i <= n; ++i) {
let element = “”;

  if (i % 3 === 0) {
      element = "Fizz";            
  }
  if (i % 5 === 0) {
      element += "Buzz";
  }
  if (element.length === 0) {
      element = "" + i;
  }
  console.log(element);
} };

fizzBuzz(100);

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

Why is it, in general, a good idea to leave the global scope of a website as-is and never touch it?

A

Every script has access to the global scope, and if everyone uses the global namespace to define their variables, collisions will likely occur. Use the module pattern (IIFEs) to encapsulate your variables within a local namespace.

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

Why would you use something like the load event? Does this event have disadvantages? Do you know any alternatives, and why would you use those?

A

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.

The DOM event DOMContentLoaded will fire after the DOM for the page has been constructed, but do not wait for other resources to finish loading. This is preferred in certain cases when you do not need the full page to be loaded before initializing.

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

Explain what a single page app is and how to make one SEO-friendly.

A

Web developers these days refer to the products they build as web apps, rather than websites. While there is no strict difference between the two terms, web apps tend to be highly interactive and dynamic, allowing the user to perform actions and receive a response to their action. Traditionally, the browser receives HTML from the server and renders it. When the user navigates to another URL, a full-page refresh is required and the server sends fresh new HTML to the new page. This is called server-side rendering.

However, in modern SPAs, client-side rendering is used instead. The browser loads the initial page from the server, along with the scripts (frameworks, libraries, app code) and stylesheets required for the whole app. When the user navigates to other pages, a page refresh is not triggered. The URL of the page is updated via the HTML5 History API. New data required for the new page, usually in JSON format, is retrieved by the browser via AJAX requests to the server. The SPA then dynamically updates the page with the data via JavaScript, which it has already downloaded in the initial page load. This model is similar to how native mobile apps work.

The benefits:

The app feels more responsive and users do not see the flash between page navigations due to full-page refreshes.
Fewer HTTP requests are made to the server, as the same assets do not have to be downloaded again for each page load.
Clear separation of the concerns between the client and the server; you can easily build new clients for different platforms (e.g. mobile, chatbots, smart watches) without having to modify the server code. You can also modify the technology stack on the client and server independently, as long as the API contract is not broken.
The downsides:

Heavier initial page load due to the loading of framework, app code, and assets required for multiple pages.
There’s an additional step to be done on your server which is to configure it to route all requests to a single entry point and allow client-side routing to take over from there.
SPAs are reliant on JavaScript to render content, but not all search engines execute JavaScript during crawling, and they may see empty content on your page. This inadvertently hurts the Search Engine Optimization (SEO) of your app. However, most of the time, when you are building apps, SEO is not the most important factor, as not all the content needs to be indexable by search engines. To overcome this, you can either server-side render your app or use services such as Prerender to “render your javascript in a browser, save the static HTML, and return that to the crawlers”.

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

What is the extent of your experience with Promises and/or their polyfills?

A

Possess working knowledge of it. A promise is an object that may produce a single value sometime in the future: either a resolved value or a reason that it’s not resolved (e.g., a network error occurred).

A promise may be in one of 3 possible states: fulfilled, rejected, or pending. Promise users can attach callbacks to handle the fulfilled value or the reason for rejection.

Some common polyfills are $.deferred, Q and Bluebird but not all of them comply with the specification. ES2015 supports Promises out of the box and polyfills are typically not needed these days.

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

What are the pros and cons of using Promises instead of callbacks

A

Pros

Avoid callback hell which can be unreadable.
Makes it easy to write sequential asynchronous code that is readable with .then().
Makes it easy to write parallel asynchronous code with Promise.all().
With promises, these scenarios which are present in callbacks-only coding, will not happen:
Call the callback too early
Call the callback too late (or never)
Call the callback too few or too many times
Fail to pass along any necessary environment/parameters
Swallow any errors/exceptions that may happen
Cons

Slightly more complex code (debatable).
In older browsers where ES2015 is not supported, you need to load a polyfill in order to use it.

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

What language constructions do you use for iterating over object properties?

A

*for-of preferred
for-in loops - for (var property in obj) { console.log(property); }. However, this will also iterate through its inherited properties, and you will add an obj.hasOwnProperty(property) check before using it.

Object.keys() - Object.keys(obj).forEach(function (property)
{ … }). Object.keys() is a static method that will lists all enumerable properties of the object that you pass it.

Object.getOwnPropertyNames() - Object.getOwnPropertyNames(obj).forEach(function (property) { … }). Object.getOwnPropertyNames() is a static method that will lists all enumerable and non-enumerable properties of the object that you pass it.

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

Explain the difference between mutable and immutable objects.

A

Immutability is a core principle in functional programming, and has lots to offer to object-oriented programs as well. A mutable object is an object whose state can be modified after it is created.

An immutable object is an object whose state cannot be modified after it is created.

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

What is an example of an immutable object in JavaScript?

A

In JavaScript, some built-in types (numbers, strings) are immutable, but custom objects are generally mutable.

Some built-in immutable JavaScript objects are Math, Date.

Here are a few ways to add/simulate immutability on plain JavaScript objects.

17
Q

Object Constant Properties

A

By combining writable: false and configurable: false, you can essentially create a constant (cannot be changed, redefined or deleted) as an object property, like:

let myObject = {};
Object.defineProperty(myObject, ‘number’, {
value: 42,
writable: false,
configurable: false,
});
console.log(myObject.number); // 42
myObject.number = 43;
console.log(myObject.number); // 42

18
Q

Prevent Extensions

A

If you want to prevent an object from having new properties added to it, but otherwise leave the rest of the object’s properties alone, call Object.preventExtensions(…):

var myObject = {
a: 2,
};

Object.preventExtensions(myObject);

myObject.b = 3;
myObject.b; // undefined

In non-strict mode, the creation of b fails silently. In strict mode, it throws a TypeError.

19
Q

Seal An Object

A

Object.seal() creates a “sealed” object, which means it takes an existing object and essentially calls Object.preventExtensions() on it, but also marks all its existing properties as configurable: false.

So, not only can you not add any more properties, but you also cannot reconfigure or delete any existing properties (though you can still modify their values).

20
Q

Freeze an Object

A

Object.freeze() creates a frozen object, which means it takes an existing object and essentially calls Object.seal() on it, but it also marks all “data accessor” properties as writable:false, so that their values cannot be changed.

This approach is the highest level of immutability that you can attain for an object itself, as it prevents any changes to the object or to any of its direct properties (though, as mentioned above, the contents of any referenced other objects are unaffected).

var immutable = Object.freeze({});

Freezing an object does not allow new properties to be added to an object and prevents from removing or altering the existing properties. Object.freeze() preserves the enumerability, configurability, writability and the prototype of the object. It returns the passed object and does not create a frozen copy.