Others Flashcards

1
Q

Explain event delegation

A

Instead of attaching an event listener to each individual element, you attach a single event listener to a parent element that contains multiple child elements. This parent element acts as a “delegate” to handle events that occur on its child elements.

When an event is triggered on a child element, the event bubbles up through the DOM hierarchy and reaches the parent element. The event listener attached to the parent element then checks the event’s target (the element where the event originated) and performs the desired action based on the target element.

Event delegation offers several advantages:

1.	Efficiency: With event delegation, you only need one event listener instead of attaching listeners to each child element. This reduces memory consumption and improves performance, especially when dealing with a large number of elements.
2.	Dynamic handling: As new child elements are added or removed dynamically, the event delegation setup remains effective. Newly added elements automatically inherit the event handling without requiring additional setup.
3.	Simplicity: Event delegation simplifies event management by centralizing event handling logic in a single location. You don’t have to bind and unbind event listeners whenever elements are added or removed.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Explain how prototypal inheritance works (aka JavaScript inheritance)

A

All JavaScript objects have a __proto__ property with the exception of objects created with Object.create(null), that is a reference to another object, which is called the object’s “prototype”. When a property is accessed on an object and if the property is not found on that object, the JavaScript engine looks at the object’s __proto__, and the __proto__’s __proto__ and so on, until it finds the property defined on one of the __proto__s or until it reaches the end of the prototype chain. This behavior simulates classical inheritance, but it is really more of delegation than inheritance.

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

Describe event bubbling.

A

When an event triggers on a DOM element, it will attempt to handle the event if there is a listener attached, then the event is bubbled up to its parent and the same thing happens. This bubbling occurs up the element’s ancestors all the way to the document. Event bubbling is the mechanism behind event delegation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
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:

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
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
6
Q

Explain Function.prototype.bind.

A

Taken word-for-word from MDN:

The bind() method creates a new function that, when called, has its `this` keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

In my experience, it is most useful for binding the value of this in methods of classes that you want to pass into other functions. This is frequently done in React components.

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

When would you use document.write()?

A

document.write() writes a string of text to a document stream opened by document.open(). When document.write() is executed after the page has loaded, it will call document.open which clears the whole document (<head> and <body> removed!) and replaces the contents with the given parameter value. Hence it is usually considered dangerous and prone to misuse.

There are some answers online that explain document.write() is being used in analytics code or when you want to include styles that should only work if JavaScript is enabled. It is even being used in HTML5 boilerplate to load scripts in parallel and preserve execution order! However, I suspect those reasons might be outdated and in the modern day, they can be achieved without using document.write(). Please do correct me if I’m wrong about this.

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

What’s the difference between feature detection, feature inference, and using the UA string?

A

Feature Detection

Checks if a browser supports a certain block of code, and running different code depending on whether it does. For example:

if ('geolocation' in navigator) {
  // Can use navigator.geolocation
} else {
  // Handle lack of feature
}

Modernizr is a great library to handle feature detection.

Feature Inference

Feature inference checks for a feature just like feature detection, but uses another function because it assumes it will also exist, e.g.:

if (document.getElementsByTagName) {
  element = document.getElementById(id);
}

This is not really recommended. Feature detection is more foolproof.

UA String

This is a browser-reported string that allows the network protocol peers to identify the application type, operating system, software vendor or software version of the requesting software user agent. It can be accessed via navigator.userAgent. However, the string is tricky to parse and can be spoofed. For example, Chrome reports both as Chrome and Safari. So to detect Safari you have to check for the Safari string and the absence of the Chrome string. Avoid this method.

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

What is JavaScript templating?

A

JavaScript templating is the process of generating dynamic HTML content using JavaScript based on predefined templates. It allows you to separate the structure (HTML) from the data (JavaScript objects) and dynamically populate placeholders in the template with actual values. Templating libraries like Handlebars provide syntax and tools to facilitate this process, making it easier to generate personalized and data-driven content.

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

Describe event bubbling.

A

When an event triggers on a DOM element, it will attempt to handle the event if there is a listener attached, then the event is bubbled up to its parent and the same thing happens. This bubbling occurs up the element’s ancestors all the way to the document. Event bubbling is the mechanism behind event delegation.

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

What’s the difference between an “attribute” and a “property”?

A

Attributes are defined on the HTML markup but properties are defined on the DOM. To illustrate the difference, imagine we have this text field in our HTML: <input></input>.

const input = document.querySelector('input');
console.log(input.getAttribute('value')); // Hello
console.log(input.value); // Hello

But after you change the value of the text field by adding “World!” to it, this becomes:

console.log(input.getAttribute('value')); // Hello
console.log(input.value); // Hello World!
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
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
13
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
14
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.
Overall, I think the benefits outweigh the disadvantages, and I never had to rely on the features that strict mode blocks. I would recommend using strict mode.

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

What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?

A

Some examples of languages that compile to JavaScript include CoffeeScript, Elm, ClojureScript, PureScript, and TypeScript.

Advantages

  • Fixes some of the longstanding problems in JavaScript and discourages JavaScript anti-patterns.
  • Enables you to write shorter code, by providing some syntactic sugar on top of JavaScript, which I think ES5 lacks, but ES2015 is awesome.
  • Static types are awesome (in the case of TypeScript) for large projects that need to be maintained over time.

Disadvantages

  • Require a build/compile process as browsers only run JavaScript and your code will need to be compiled into JavaScript before being served to browsers.
  • Debugging can be a pain if your source maps do not map nicely to your pre-compiled source.
  • Most developers are not familiar with these languages and will need to learn it. There’s a ramp up cost involved for your team if you use it for your projects.
  • Smaller community (depends on the language), which means resources, tutorials, libraries, and tooling would be harder to find.
  • IDE/editor support might be lacking.
    These languages will always be behind the latest JavaScript standard.
  • Developers should be cognizant of what their code is being compiled to — because that is what would actually be running, and that is what matters in the end.

Practically, ES2015 has vastly improved JavaScript and made it much nicer to write. I don’t really see the need for CoffeeScript these days.

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

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

A

For objects

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.

For arrays

for loops - for (var i = 0; i < arr.length; i++). The common pitfall here is that var is in the function scope and not the block scope and most of the time you would want block scoped iterator variable. ES2015 introduces let which has block scope and it is recommended to use that instead. So this becomes: for (let i = 0; i < arr.length; i++).
forEach - arr.forEach(function (el, index) { … }). This construct can be more convenient at times because you do not have to use the index if all you need is the array elements. There are also the every and some methods which will allow you to terminate the iteration early.
for-of loops - for (let elem of arr) { … }. ES6 introduces a new loop, the for-of loop, that allows you to loop over objects that conform to the iterable protocol such as String, Array, Map, Set, etc. It combines the advantages of the for loop and the forEach() method. The advantage of the for loop is that you can break from it, and the advantage of forEach() is that it is more concise than the for loop because you don’t need a counter variable. With the for-of loop, you get both the ability to break from a loop and a more concise syntax.
Most of the time, I would prefer the .forEach method, but it really depends on what you are trying to do. Before ES6, we used for loops when we needed to prematurely terminate the loop using break. But now with ES6, we can do that with for-of loops. I would use for loops when I need even more flexibility, such as incrementing the iterator more than once per loop.

Also, when using the for-of loop, if you need to access both the index and value of each array element, you can do so with the ES6 Array entries() method and destructuring:

17
Q

What is a has map / hash table / dictionary?

A

A hash map is a data structure that allows efficient storage and retrieval of key-value pairs. It uses a hash function to associate keys with values and enables fast access to values based on their keys. In JavaScript, it is commonly implemented using the Map object. Hash maps provide constant-time complexity for key-based operations and are useful for managing and organizing data in JavaScript, TypeScript, and React front-end development.

Example:

// Creating a hash map
const hashMap = new Map();

// Adding key-value pairs
hashMap.set("apple", 10);
hashMap.set("banana", 5);
hashMap.set("orange", 8);

// Retrieving a value
console.log(hashMap.get("banana")); // Output: 5

// Checking if a key exists
console.log(hashMap.has("apple")); // Output: true

// Updating a value
hashMap.set("orange", 12);

// Deleting a key-value pair
hashMap.delete("apple");

// Iterating over key-value pairs
hashMap.forEach((value, key) => {
  console.log(key, value);
});