JS Flashcards

1
Q

What is event delegation?

A

Event delegation is an event handling pattern that allows events to be handled at higher levels of the DOM tree other than where the event was first received.

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

How does event delegation work?

A

Event delegation works because of event bubbling, which allows events to propagate up through the DOM tree to the root. Because of this, events can be handled on any ancestor element of the element where the event was received.

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

Explain why the following doesn’t work as an IIFE: function foo(){ }();. What needs to be changed to properly make it an IIFE?

A

An IIFE is an anonymous function, thus cannot be named. To make the function an IIFE the name ‘foo’ must be dropped to make it anonymous and the function must be enclosed within a grouping operator. (function () {})()

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

What is an IIFE in JS?

A

An IIFE is an immediately invoked function expression meaning that it is a function that is runs as soon as it is defined.

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

What’s the difference between a variable that is: null, undefined or undeclared? How would you go about checking for any of these states?

A

A variable that is undeclared has not been created yet. A variable that is undefined has been declared, but does not have a value. A variable that is null has been declared and has a value of nothing.

To check is a variable is undeclared, one could console.log the variable. If it does not exist a ReferenceError will be thrown.

To check for undefined or null, one could compare the variable with the primative values of undefined or null using the ‘===’.

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

What is a closure? How/Why would you use one?

A

A closure is the combination of a function bundled together with references to its surrounding state. A closure gives access to an outer function’s scope from an inner function.

Closures are useful because they associate data with a function that operates on that data. You can use closures anywhere that might normally use an object with only a single method.

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

Describe the main difference between a .forEach() loop and a .map() loop. Why you would pick one versus the other?

A

The main difference is that a forEach loop mutates the calling array while a map loop utilizes return values and returns a new Array of the same size.

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

What’s a typical use case for anonymous functions?

A

A typical use case for an anonymous function would be an IIFE, where a function is created and then immediately run.

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

How do you organize your code? (module pattern, classical inheritance?)

A

no answer yet

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

What’s the difference between host objects and native objects?

A

Native objects are standard javascript objects provided by javascript itself. They are also know as built-in objects, pre-defined objects, or global objects. (ex: String(), Number(), true).

Host objects are environment-specific javascript objects, and may vary as per the environment of the machine in which the javascript is being used. Host objects are host specific and may differ from one host to another. (ex: window, NodeList, console).

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

Difference between: function Person(){}, var person = Person(), and var person = new Person()?

A

function Person() {} is a declarative function, which does not execute but is registered into the global namespace.

var person = Person() is a function expression, where var contains a reference to a Person function. This can also be an anonymous function.

var person = new Person() is a function constructor, which instantiates a new new object of the Person class constructor.

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

What’s the difference between .call and .apply?

A

The difference is that call() takes arguments separately and apply() takes arguments as an array.

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

Explain Function.prototype.bind().

A

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

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

When would you use document.write()?

A

Conventional wisdom would deem using document.write() as bad practice as using it after a page load would replace all the content of the page with whatever is placed as a parameter. A possible ‘approved’ time would be for third party code to add their scripts to a page.

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

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

A

Feature detection tries to verify if a feature exists, such as geolocation.

Feature inference infers if A exists that it can be assumed that B exists. Geolocation exists so the user must be using a modern browser.

UA string helps identify which browser is used by the user.

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

What is AJAX?

A

AJAX stands for Asynchronous Javascript and XML and it allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This makes it possible to update parts of a web page without reloading the whole page.

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

What are the advantages and disadvantages of using AJAX?

A

The advantages of using AJAX:
1. Can use asynchronous calls to reload parts of a web page without having to reload the whole page.
2. Can reduce server traffic and increase speed by allowing applications to render without data.
3. XMLHttpRequest transfers and manipulates the XML data to and from a web service using HTTP. Its purpos is to establish an independent connection between the webpage’s client-side and server.
4. Can reduce bandwidth usage by fetching particle contents instead of transmitting the entire page’s content; meaning you can bring data from the db and store it into the db to perform background without reloading the page.
5. AJAX method enables precise and immediate form validation.

The disadvantages of using AJAX:
1. Open-source making it less secure than other technologies.
2. Search engines cannot index AJAX pages.
3. AJAX can cause difficulties for web pages to debug as well as make them prone to security issues in the future.
4. AJAX has a dependency on JS, so only browsers that support JS or XMLHttpRequest can use AJAX techniques.
5. Bookmarking a specific state can be challenging due to the dynamic web page.
6. If clicking the browser back button, the page may not return to the previous state because successive AJAX requests are unable to register with the browser’s history.

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

What is hoisting?

A

Hoisting is the built-in behavior of the language through which declarations of functions, variables, and classes are moved to the top of their scope before code execution.

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

Describe event bubbling.

A

Event bubbling happens when an element receives an event, and that event propagates to its parent and ancestor elements in the DOM tree until it gets to the root element. This is default behavior and can be prevented by using the ‘stopPropagation’ method of the event object.

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

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

A

Attributes:
1. Defined by the HTML and are used to customize a tag.
2. Value is constant.
3. Used to initialize the DOM properties.

Properties:
1. Defined by the DOM
2. Value is variable
3. No job is defined

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

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

A

Extending built-in JS objects is not a good idea because of future-proofing. If a browser decides to implement its own version of a method, a custom extension might get overridden, leading to unexpected behavior or conflicts.

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

How do you extend built-in objects in JS?

A

You can extend a built-in object by adding properties and functions to its prototype.

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

What is the difference between the document load event and document DOMContentLoaded event?

A

The difference between the document load event and the document DOMContentLoaded event is that the load event is fired when the entire web page has been loaded in, including the page DOM and all dependent resources such as scripts, stylesheets and images. The document DOMContentLoaded event fires when the page DOM has been loaded and all deferred scripts have been loaded and executed.

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

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

A

The difference between “==” and “===” is that “==” represents a loose equality in which it performs type coercion before making a comparison, meaning that if the datatypes are different, the JS engine will automatically convert of the operands to the same datatype to make the comparison possible. Whereas === is a more strict comparison and does not convert the types of the operands if the datatypes are different before comparing.

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

Explain the same-origin policy with regards to JS.

A

The same-origin policy is a mechanism that restricts a resource that is loaded in one particular origin from another origin. Two origins are considered the same if their URLs have the same hostname, port and protocol. As it pertains to JS the async requesting mechanisms like AXIOS, AJAX and FETCH show an error message on a request from some other origin. A JS exception is the script tag with no error indications.

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

Make this work: duplicate([1,2,3,4,5]); result: [1,2,3,4,5,1,2,3,4,5]

A

function duplicate(array) {
let duplicatedArr = array.push(…array);
return duplicatedArr
}

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

Why is it called a ternary expression? What does the word ternary indicate?

A

It’s called a ternary expression because the expression accepts three operands, the test condition, the ‘then’ expression and the ‘else’ expression.

28
Q

What is ‘use strict’? What are the advantages and disadvantages to using it?

A

The ‘use strict’ directive enables JS strict mode which enforces stricter parsing and error handling on the code at runtime. It helps create cleaner code and catch errors and bugs that might otherwise be missed.

Some advantages are that it can help prevent accidental creation of global variables, catch typing mistakes in variable names, prevent accidental deleting, prevent duplicating parameter names in a function, prevent writing to read-only properties.

Some disadvantages are compatibility issues, inability to delete variables, performance overhead, limitations with function declarations, inability to use eval and arguments objects.

29
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

for(let i = 1; i < 100; i++) {
if( i % 3 === 0 && i % 5 === 0 ) {
console.log(‘fizzbuzz’);
} else if ( i % 3 === 0 ) {
console.log(‘fizz’);
} else if ( i % 5 === 0 ) {
console.log(‘buzz’);
};
};

30
Q

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

A

Helps prevent naming conflicts, helps cluttering the global namespace, helps prevent scope leaks, for modularity and encapsulation purposes, for security concerns and for compatibility and portability.

31
Q

What is global scope?

A

Global scope is the scope that contains, and is visible in, all other scopes. In client-side JS, the global scope is generally the web page inside which all the code is being executed.

32
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
33
Q

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

A

A SPA is a web app implementation that loads only a single web document and then updates the body content of that single document via JS APIs such as Fetch when different content is to be shown.

A SPA can be made more SEO-friendly by utilizing server-side rendering, improving meta tags with titles, descriptions and keywords, using a sitemap, using feature detection, lazy loading content.

34
Q

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

A
35
Q

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

A

Promises offer a cleaner alternative to callbacks, helping to avoid callback hell and making async code more readable. They facilitate writing sequential and parallel async operations with ease. However, using promises may introduce more complex code.

36
Q

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

A

Some advantages include: fixing some of the longstanding problems in JS and discourages JS anti-patterns. Enables writing shorter code, by providing some syntactic sugar on top of JS. Using static types for large projects that need to be maintained over time.

Some disadvantages include: requiring a build/compile process before being served to browsers. Debugging can be an issue if the source maps do not map correctly to the pre-compiled source. Ramp us cost for team usage if dev team is not familiar with a language. Smaller community so additional resources are harder to find. IDE/editor support may be lacking. Languages are always behind the latest JS standard.

37
Q

What tools and techniques do you use debugging JS code?

A
38
Q

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

A
39
Q

Explain the difference between mutable and immutable objects.

A

Mutable objects are objects that can be changed after they are created. Immutable objects cannot be changed after they are created.

40
Q

How do you make an object immutable?

A

To create an immutable object an object can be passed to the function Object.freeze(obj). The freeze() method returns the same object that has now become immutable.

41
Q

Explain the difference between synchronous and asynchronous functions.

A

Synchronous functions run in sequence one after the next blocking other code from executing until the function has finished running. Asynchronous functions allow other code to run as it is still being executed.

42
Q

What is the event loop? What is the difference between call stack and task queue?

A
43
Q

Explain the differences on the usage of foo between function foo() {} and var foo = function() {}.

A

Fuction foo is a function definition while var foo is a function expression. The main difference between them being function declarations are hoisted while function expressions are not. Trying to invoke a function expression before it is declared will result in a TypeError.

44
Q

What are the differences between variables created using let, var and const?

A

The var keyword has function scope is hoisted and no longer used all that much anymore. The let and const keywords have block scope, with const requiring an initial value and prevents reassignment.

45
Q

What are the differences between ES6 class and ES5 function constructors?

A

ES6 class constructors creates objects by adding function to their prototypes, it ensures that ‘this’ keyword used by the dev is referring to the object being created, syntax is similar to object creation in other oop languages, syntax bas for constructor functions and instantiate objects using a new operator.

ES5 function constructors create objects along with inheritance property, any function can be used as a function constructor and it primarily focuses on the creation of reusable object creation code, syntax is unique and is not generally found in other oop languages, also uses a new operator for object creation but focuses on how the objects are being instantiated.

46
Q

Can you offer a use case for the arrow function syntax? How does this differ from other functions?

A

Some use cases where it’s advantages to use an arrow function is when you want to write a short function in a more straightforward manner, like a single-line function, or when you do not want the ‘this’ keyword bound to the function.

answer second part

47
Q

What advantage is there for using the arrow syntax for a method in a constructor?

A

The main advantage is that the ‘this’ value gets set at the time of the function creation and can’t change after that. Whereas ‘this’ can be changed for a normal function.

48
Q

What is the definition of a higher-order function?

A

Higher order functions that can either accept other functions as an argument, return a function as a result or both.

49
Q

Can you give an example of destructuring an object or an array?

A
50
Q

ES6 template literals offer a lot of flexibility in generating strings, can you give an example?

A
51
Q

Can you give an example of a curry function and why this syntax offers an advantage?

A

So, currying is a pattern where a function with more than one parameter is broken into multiple functions that, when called in series, will accumulate all of the required parameters one at a time. An advantage of using currying is that it can help make code written in a functional style easier to read and compose.

function curry(fn) {
if (fn.length === 0) {
return fn;
}

function _curried(depth, args) {
return function (newArgument) {
if (depth - 1 === 0) {
return fn(…args, newArgument);
}
return _curried(depth - 1, […args, newArgument]);
};
}

return _curried(fn.length, []);
}

function add(a, b) {
return a + b;
}

var curriedAdd = curry(add);
var addFive = curriedAdd(5);

var result = [0, 1, 2, 3, 4, 5].map(addFive); // [5, 6, 7, 8, 9, 10]

52
Q

What are the benefits of using spread syntax and how is it different from rest syntax?

A

Spread syntax allows for the expansion of arrays and objects into elements for arrays and key-value pairs for objects. Some benefits of using this syntax: allows us to inclued all elements of an array or object in a list of some kind. It can expand an object or an array and store all values in a new variable of the same datatype. it allows copying all elements of an already existing array into a new array and perform push, pop operations without disturbing the original array. It can concat a string or merge two or more arrays without using concat() function. It allows Math functions on an array. It allows changes to be made in nested objects without reflecting in the original object.

The rest operator is used to collect data and store that data into a single variable which we can further pass to a function or other code as a variable.

53
Q

How can you share code between files?

A

Here are a few ways to share code between files: Use the ‘export’ and ‘import’ keywords, using named exports and default exports, combining exports from multiple files using the export * from statement, using dynamic imports with the import() function, destructuring assignment for imports.

54
Q

Why would you want to create static class members?

A

Static class members are useful for: namespace organization for defining constants or config values that are specific to a class. Using as helper functions that operate on the class itself or its instances improving readability and maintainability. Using a singleton pattern where only one instance of a class ever exists.

55
Q

Can you name two programming paradigms important to JS app developers?

A

Two paradigms important to JS developers are OOP and functional programming.

56
Q

What is functional programming?

A

Functional programming in JS is about treating code as a set of independent, reusable functions that operate on data without side effects.

57
Q

What is the difference between classical inheritance and prototypal inheritance?

A

Classical inheritance classes are immutable, classes may or may not support multiple inheritance, verbose and complicated with abstract classes, final classes, interfaces, etc.

Prototypal inheritance prototypes are flexible, objects can inherit from multiple prototypes, simple only having objects and extending objects is the only operation required.

58
Q

What are the pros and cons of functional programming vs object-oriented programming?

A

The benefits of using functional programming are: uses immutability, focuses on functions as first-class citizens to make code more modular, reusable and easier to test, recursion and higher-order functions makes it easier to write elegant and expressive code, emphasis on referential transparency can make it easier to reason about behavior of code.

The cons of using functional programming are: can lead to code that is more complex and harder to understand, immutability can make it less efficient when working with large data sets, heavy use of recursion can make it harder to write concurrent and parallel code, use of higher-order functions and closures can make it more difficult to reason about the behavior of code.

59
Q

What are two-way data bindings and one-way data flow and how are they different?

A

One-way data binding is a unidirectional data flow, where changes in the data model are reflected in the UI, but changes in the UI do not affect the data model.

Two-way data binding is bidirectional data flow, where changes in the data model are reflected in the UI and changes in the UI are reflected in the data model.

The primary difference between the two is the direction of data flow and the level of control over data synchronization. One-way is simpler and more straightforward since the data only flows in one direction and the UI is solely dependent on the data model. Where two-way offers more flexibility and interactivity, as changes in both the data and the UI are reflected in each other.

60
Q

What is a closure?

A

A closure is a function within another function having access to the parent function’s scope, even after the parent function has closed.

61
Q

What is a Promise?

A

A Promise is an object that will produce a single value sometime in the future.

62
Q

What is a callback?

A

A callback function is a function passed as an argument to another function. This allows a function to call another function after a function has finished. Great to use with async functions.

63
Q

What is a cookie? What are the differences between cookies, localStorage and sessionStorage?

A

Cookies are text files with small pieces of data that are used to identify your computer as you use a network.

The difference between Cookies, Local and Session storage is that cookies can store on the client or server, hold a very small amount of data comparatively, can be accessed by any window and expiration can be set manually. Local storage can store the most amount of data on the client only, can be accessed in any window and never expires. Session storage can store more data than a cookie but less than local store, is only accessible in the tab in which it was created and automatically expires when the tab is closed.

64
Q

What is prototypal inheritance?

A

Prototypal inheritance is the linking of prototypes of a parent object to a child object to share and utilize the properties of the parent class using a child class.

65
Q

What is the DOM?

A

The DOM stands for Document Object Model and is the data representation of the objects that comprise the structure and content of a document on the web. This allows programs to change the document structure, style and content.