JavaScript Questions Flashcards

1
Q

Explain event delegation

A

Explanation: Setting an event listener on a parent element and having events that happen on a child element bubble up to the parent.
Use: When you want some code to run when the user interacts with any one of a large number of child elements.
Example:

<div>
<div></div>
</div>

<script>
container.addEventListener('click', (event) => (event.target.style.backgroundColor = bgChange()));
</script>

Event Delegation is basically a pattern to handle events efficiently. Instead of adding an event listener to each and every similar element, we can add an event listener to a parent element and call an event on a particular target using the .target property of the event object.

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

Explain how this works in JavaScript

A

Explanation: this references an object. When inside of a constructor function or class it will reference the object on instantiation.
Use: It is used to assign properties and values to an object on instantiation.
Example:
class MyThing {
constructor(passThisIn) {
this.passThisIn = passThisIn;
}
}

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

Explain how prototypal inheritance works

A

Explanation: All JavaScript objects have a __proto__ property that is a reference to another object, which is called the object’s “prototype”. If a property is accessed on an object, but not found, the JavaScript engine check’s that object prototype. If again it’s not found, it checks that prototype’s prototype on up the chain until it reaches the top of the chain.
Use: It can help reduce redundant code.

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

What do you think of AMD vs CommonJS?

A

AMD and CommonJS are both Javascript module loader. They accomplish the same task but works different.
AMD is better for browser, hence, the name ‘Asynchronous’, as it loads each distinct module in async manner instead of loading in one large file. No extra steps are required to use AMD, it works out-of-the-box. In my opinion, as it is its in Asynchronous nature, it makes alot of async http requests and may not be as performant as described by other devs.
While, CommonJS, is a standard, mostly used in servers and it loads modules synchronously, though extra step is required if you want your JS file size to be minified and compressed.

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

Explanation: The parser reads it as two seperate statements. First the function declaration function foo(){ } and then a blank function call attempt (); The best way to fix this would be to add another set of parenthesis wrapping the function declaration (function foo(){ })() This changes it from a function declaration to a function expression.

An IIFE (pronouced as ‘iffy’) is an abbreviation for Immediately Invoked Function Expression.

For the above code to be considered an IIFE, it needs to be an anonymous function, a function without a name, this is because IIFE needs to be Invoked Immediately without invoking it a function name. We also need to wrap the anonymous function with parenthesis, so the Javascript parser treats our anonymous function as a function expression.

(function() {}());

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

Explanation:
null: the value is intentionally absent (points to nothing in memory).
undefined: not yet assigned a value or not yet declared.
undeclared: improperly declared without let/const/var
Use: null can be used to assign the primitive value of null to a variable. undeclared throws an error where as null and undefined can be checked with a conditional
Example: null and undefined can be checked using strict equality ===. Undeclared will throw it’s own error so you could use try…catch

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

What is a closure, and how/why would you use one?

A

Explanation: Closure allows you to use an outer function’s scope (go into a parent, grandparent function, etc.) from within an inner function. In JavaScript a closure is created every time a function is created.
Use: It allows you to combine data with the function that will operate on that data. It is similar to OOP.
Example:
function init() {
var name = ‘Mozilla’; // name is a local variable created by init
function displayName() {
// displayName() is the inner function, a closure
alert(name); // use variable declared in the parent function
}
displayName();
}
init();

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

Can you describe the main difference between a .forEach loop and a .map() loop and why you would pick one versus the other?

A

Explanation: .forEach() executes a callback function on each element, but does not return a value. .map() executes a callback function on each element and “maps” the result to a new array. The new array is returned.
Use: If you need the result and don’t want to mutate the original array, use map. If you only need to iterate over the array then forEach can be used.

Example: .forEach():
const a = [1, 2, 3];
const doubled = a.forEach((num, index) => {
// Do something with num and/or index.
});
// doubled = undefined

.map():

const a = [1, 2, 3];
const doubled = a.map((num) => {
return num * 2;
});
// doubled = [2, 4, 6]

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

What’s a typical use case for anonymous functions?

A

Explanation: I’ve typically encountered them as callback functions that don’t need to be used anywhere else.
Use: Essentially when you don’t need a named function and the function is bound to some other action.
Example:
setTimeout(function () {
console.log(‘Hello world!’);
}, 1000);

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

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

A

Explanation: My preference is to use ES6 Modules to organize my code.
Easier to reuse code
You can keep different parts of your code cleanly separated, which makes writing and maintaining your code much easier and less error-prone.

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

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

A

Explanation: Native objects are part of the language as defined by ECMAScript specification. Host objects are those provided by the runtime (browser or Node).
Example: Some native objects are String, Math, RegExp, and Object. A couple of host objects are window and console

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

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

A

function Person(){} is just a normal function declaration. It is likely being used as a constructor.

var person = new Person() is instantiated a new Person object as person. It creates an instance of the Person object using the new operator, which inherits from Person.prototype.

var person = Person() invokes the Person as a function, and not as a constructor. It is not correct and would likely return undefined. To create a new instance you would need to use the new operator as above.

Example:
function Person(name) {
this.name = name;
}

var person = Person(‘John’);
console.log(person); // undefined
console.log(person.name); // Uncaught TypeError: Cannot read property ‘name’ of undefined

var person = new Person(‘John’);
console.log(person); // Person { name: “John” }
console.log(person.name); // “john”

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

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

A

Explanation: They are both used to invoke functions the difference is in how they take arguments. .call() takes them as comma-separated values and .apply() takes them as an array.

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

Explain Function.prototype.bind.

A

Explanation: Creates a new function that, when called, has its this keyword set to the provided value.
Use: 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
15
Q

When would you use document.write()?

A

When document.write() is executed after page load, it replaces the entire header and body tag with the given parameter value in string. An invocation could look like this:
document.write(‘<h1>hello world</h1>’);
When working with web application, it is uncommon task to overwrite an entire page, hence why using document.write() is bad practice.

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

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

A

Explanation:
Feature Detection: Working out whether a browser supports a certain block of code, and running different code depending on whether it does, so that the browser can provide a working experience rather crashing/erroring in some browsers.
Feature Inference: Checks for a feature just like feature detection, but uses another function because it assumes it will also exist. Feature Detection is the better approach.
UA String: A browser-reported string that allows the network protocol peers to identify various properties of the system. It’s tricky to parse and can be spoofed so it’s best to avoid this method.

Example: Using feature detection:
if (‘geolocation’ in navigator) {
// Can use navigator.geolocation
} else {
// Handle lack of feature
}

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

Explain Ajax in as much detail as possible.

A

Explanation: Ajax (asynchronous JavaScript and XML) is a set of web development techniques using many web technologies on the client side to create asynchronous web applications. With Ajax, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page.
Use: By decoupling the data interchange layer from the presentation layer, Ajax allows for web pages, and by extension web applications, to change content dynamically without the need to reload the entire page. In practice, modern implementations commonly use JSON instead of XML, due to the advantages of JSON being native to JavaScript.
Example: The fetch API is typically used nowadays for asynchronous communication.

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

What are the advantages and disadvantages of using Ajax?

A

Advantages:
Better interactivity. New content from the server can be changed dynamically without the need to reload the entire page.
Reduce connections to the server since scripts and stylesheets only have to be requested once.
State can be maintained on a page. JavaScript variables and DOM state will persist because the main container page was not reloaded.

Disadvantages:
Dynamic webpages are harder to bookmark.
Does not work if JavaScript has been disabled in the browser.
Some webcrawlers do not execute JavaScript and would not see content that has been loaded by JavaScript.
JavaScript will have to be parsed and executed on the browser, and low-end mobile devices might struggle with this.

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

Explain how JSONP works (and how it’s not really Ajax).

A

Explanation: JSONP (JSON with Padding) is a method commonly used to bypass the cross-domain policies in web browsers because Ajax requests from the current page to a cross-origin domain is not allowed.

Use: JSONP can be unsafe as it can do everything else JavaScript can so you need to trust the provider of data. These days, CORS is the recommended approach and JSONP is seen as a hack.

Example:
<!-- https://mydomain.com -->


function printData(data) {
console.log(`My name is ${data.name}!`);
}

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

Have you ever used JavaScript templating? If so, what libraries have you used?

A

Explanation: The only one I’ve used is JSX in React, which I don’t think it quite javascript templating.

Use: It’s more of an extension to ECMAScript that allows you to easily structure components with familiar HTML syntax.

Example:
const name = ‘Josh Perez’;
const element = <h1>Hello, {name}</h1>;

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

Explain “hoisting”.

A

Explanation: It’s the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code. Think of it as moving the code up to the top. Note that the assignment stays where it is despite this.
Use: Allows you to execute code before they’re declared. Function declaration and var are initialized before delaration whereas const, let, and function expressions are not. This means the first two can be accessed globally and the last 3 only after they’ve been declared.
Example:
eat() //this hoisting works b.c it’s a function declaration below

function eat(){
console.log(‘eat’)
}

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

Describe event bubbling.

A

Explanation & Use: When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors. The most deeply nested element that caused the event is called a target element, accessible as event.target.
Example:

<style>

  body * {
    margin: 10px;
    border: 1px solid blue;
  }
</style>

<form>
FORM
<div>
DIV
<p>P</p>
</div>
</form>

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
23
Q

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

A

Explanation & Use: Attributes are defined on the HTML markup but properties are defined on the DOM. An attribute is the initial state when rendered in the DOM. A property is the current state.
Example:
const input = document.querySelector(‘input’);
console.log(input.getAttribute(‘value’)); // Hello
console.log(input.value); // Hello
Notice how the property updates after adding “World” to the input.

console.log(input.getAttribute(‘value’)); // Hello
console.log(input.value); // Hello World!

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
24
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
25
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.

26
Q

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

A

Explanation: == checks for value equality while === checks for value and data type equality
Use: == should generally be avoided unless for null or undefined

Example:
1 == ‘1’; // true
1 == [1]; // true
1 == true; // true
0 == ‘’; // true
0 == ‘0’; // true
0 == false; // true

== 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:

27
Q

Explain the same-origin policy with regards to JavaScript.

A

Explanation: The same-origin policy prevents JavaScript from making requests across domain boundaries only allowing one webpage to access another webpage if they have the same origin . 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.

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.

28
Q

Make this work: 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 with ES6:

const duplicate = (arr) => […arr, …arr];

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

29
Q

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

A

Explanation: “Ternary” means “composed of three parts”, as the expression accepts 3 operands. First, a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy.
Use: Can simplify code over if…else statements.

Example:
const age = 26;
const beverage = age >= 21 ? ‘Beer’ : ‘Juice’;

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

30
Q

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

A

Explanation: ‘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. 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.

Use:

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.

31
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() {
for (let i = 1; i <= 100; i++) {
if (i % 5 === 0 && i % 3 === 0) {
console.log(i, ‘FizzBuzz’);
} else if (i % 3 === 0) {
console.log(i, ‘Fizz’);
} else if (i % 5 === 0) {
console.log(i, ‘Buzz’);
}
}
}

32
Q

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

A

Explanation: 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.

33
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

Explanation: load fires when the entire page is finished loading (HTML, CSS, Scripts, etc.). You might want to use DOMContentLoaded which fires when the DOM is loaded, but before stylesheets, scripts, etc. are loaded.
Use: It depends on the context, but perhaps there is some non-blocking resource that is a large file which you would wait to load until the entire page is done.

34
Q

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

A

Explanation: SPA’s render the page client side instead of server side. The server sends the initial page, but subsequent changes to the page do not initiate a page refresh. The data on the page is typically updated via an AJAX request which is then used to dynamically update the page via JavaScript.
Use: A reason to use a SPA is that it feels more responsive to the user, fewer HTTP request are made so assets don t have to be downloaded multiple times and there is a clear separation between client and server. As long as the API is the same either side can be modified without affecting the other. Some downsides would be heavier initial page load, additional server config needed and SEO can be more difficult. To overcome the SEO problem you could render your pages server side or use a service such as Prerender.

35
Q

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

A

Explanation: I’ve used Promises extensively as they are a main component in modern asynchronous JavaScript. They are used for operations that will produce a resolved value in the future. I haven’t used polyfills much as they aren’t required much these days.

36
Q

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

A

Pros:
Avoid callback
Easy to write sequential asynchronous code that is readable with .then().
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).
Older browsers may require a polyfill.

37
Q

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

A

Advantages:
Adds some syntatic sugar allowing you to write shorter code.
Static types may be available which helps for large projects that need to be maintainable.
Discourages JavaScript anti-patterns.
Disadvantages:
Requires a build/compile step.
Another language to learn so requires additional training for developers new to the project.
Less resources due to smaller communities.
Behind the latest features of the up to date ECMAScript standards.
Debugging may be difficult if mapping from compiled to pre-compiled code is not done well.
Example: Some more well known examples of these types of languages are CoffeeScript and TypeScript.

38
Q

What tools and techniques do you use debugging JavaScript code?

A

Explanation & Use: I typically will watch variables as they change over time to make sure they are carrying the correct values or states. The three most common tools I use are:
Browser Devtools (Typically Chrome & Firefox)
console.log
debugger statement

39
Q

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

A

Objects:
for…in loops: When I don’t need to access properties that are non-enumerable and that are keyed by Symbols.
Object.keys(): Only when I need to access the enumerable properties.
Object.getOwnPropertyNames(): When I need to access all properties.
Arrays:
for loops: I use them when I need to iterate through the array in steps larger than one.
forEach(): I use it when I don’t need to reference the index as it requires less code.
for…of loops: I use them when I might need to break from the loop.

40
Q

Explain the difference between mutable and immutable objects.

A

Explanation: 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.
Use: Immutable objects make it easier to detect changes, make programs less complicated to think about and sharing is easy with references. If immutable objects are setup incorrectly though it could lead to poor performance due to multiple copies being made.
Example: To make an object immutable you could Object.freeze() which prevents new properties from being added and existing properties from being altered or removed.

41
Q

Explain the difference between synchronous and asynchronous functions.

A

Explanation: Synchronous functions are blocking while asynchronous functions are not. In synchronous functions, statements complete before the next statement is run. In this case, the program is evaluated exactly in order of the statements and execution of the program is paused if one of the statements take a very long time.
Use: Note that JavaScript is synchronous and it’s actually the browser and Node.js that’s actually asynchronous (think callbacks and promises)
Example:
function f1() {
// Some code //synchronous
}
function main() {
console.log(‘main’);
setTimeout(f1, 0); // async, with a callback of f1 function
f2();
}

42
Q

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

A

Explanation: The event loop is a single-threaded loop that monitors the call stack and checks if there is any work to be done in the task queue. If the call stack is empty and there are callback functions in the task queue, a function is dequeued and pushed onto the call stack to be executed.

43
Q

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

A

Explanation: The former is a function declaration while the latter is a function expression.
Use: The function declaration is hoisted and can therefore be accessed from anywhere, whereas the function expression can only be accessed after it’s been defined.
Example:
console.log(name(‘Curtis’)) // can be accessed before initialization (hoisted)

function name (str){ // function declaration
return str
}

console.log(nameTwo(‘Curtis’)) // cannot be accused before initialization (not hoisted)

const nameTwo = function (str) { // expression
return str
}

44
Q

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

A

Explanation: Variables declared using the var keyword are scoped to the function in which they are created, or if created outside of any function, to the global object. let and const are block scoped, meaning they are only accessible within the nearest set of curly braces (function, if-else block, or for-loop).
Use: var is hoisted and can be redeclared, whereas let and const cannot be redeclared. let and var can be reassigned, but const cannot be.
Example:
if (true) {
var thing1 = ‘bar’;
let thing2 = ‘baz’;
const thing3 = ‘qux’;
}

// var declared variables are accessible anywhere in the function scope.
console.log(thing1); // bar
// let and const defined variables are not accessible outside of the block they were defined in.
console.log(thing2); // ReferenceError: baz is not defined
console.log(thing3); // ReferenceErro

45
Q

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

A

Explanation & Example: Simple constructors are fairly similar in length and ease of use. The main difference in the constructor comes when using inheritance. If we want to create a Student class that subclasses Person and add a studentId field, this is what we have to do:
// ES5 Function Constructor
function Student(name, studentId) {
// Call constructor of superclass to initialize superclass-derived members.
Person.call(this, name);

// Initialize subclass’s own members.
this.studentId = studentId;
}

Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;

// ES6 Class
class Student extends Person {
constructor(name, studentId) {
super(name);
this.studentId = studentId;
}
}

46
Q

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

A

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

Explanation & Use: It simplifies the syntax needed to create functions and this is lexically bound meaning it uses this from the code that contains the arrow function.
Example: Notice that you do not need to .bind(this) for the below to work.
var obj = {
id: 42,
counter: function counter() {
setTimeout(() => {
console.log(this.id);
}, 1000);
},
};

47
Q

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

A

Explanation & Use: The main advantage is that the value of this gets set at the time of the function creation and can’t change after that. This is helpful in React class components when for example you may pass a click handler down into a child component as a prop.
Example:
const Person = function (firstName) {
this.firstName = firstName;
this.sayName1 = function () {
console.log(this.firstName);
};
this.sayName2 = () => {
console.log(this.firstName);
};
};
const john = new Person(‘John’);
const dave = new Person(‘Dave’);

john.sayName1(); // John
john.sayName2(); // John

// The regular function can have its ‘this’ value changed, but the arrow function cannot
john.sayName1.call(dave); // Dave (because “this” is now the dave object)
john.sayName2.call(dave); // John

john.sayName1.apply(dave); // Dave (because ‘this’ is now the dave object)
john.sayName2.apply(dave); // John

john.sayName1.bind(dave)(); // Dave (because ‘this’ is now the dave object)
john.sayName2.bind(dave)(); // Jo

48
Q

What is the definition of a higher-order function?

A

Explanation: A higher-order function is any function that takes one or more functions as arguments, which it uses to operate on some data, and/or returns a function as a result.
Use: To abstract some operation that is performed repeatedly.
Example: The classic example of this is map, which takes an array and a function as arguments. map then uses this function to transform each item in the array, returning a new array with the transformed data.

49
Q

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

A

Explanation: Destructuring is an expression that enables a convenient way to extract properties from Objects and values from Arrays and place them into distinct variables.
Use: It’s a more concise way to assign values to variables and can be particularly handy when passing function arguments.
Example: An example of destructing a simple object:
// Variable assignment
const o = { p: 42, q: true };
const { p, q } = o;

console.log(p); // 42
console.log(q); // true

50
Q

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

A

Explanation: Template literals are a way to do string interpolation, or to include variables in a string.
Use: It is simpler and more readable than using concatenation methods prior to ES2015.
Example:
// Prior to ES2015
‘Hi, my name is ‘ + person.name + ‘ and I am ‘ + person.age + ‘ years old!’;

// Using template literals
`Hi, my name is ${person.name} and I am ${person.age} y

51
Q

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

A

Explanation: Currying is a pattern where a function with more than one parameter is broken into multiple functions taking a single parameter each that, when called in series, will accumulate all of the required parameters one at a time.
Use: This technique can be useful for making code written in a functional style easier to read and compose.
Example:
// regular function
function sum3(x, y, z) {
return x + y + z;
}

// curried version
function sum3(x) {
return (y) => {
return (z) => {
return x + y + z;
};
};
}

52
Q

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

A

Explanation: Spread syntax is used to “unpack” data from an array, while rest syntax is the opposite and is used to put data into an array.
Use: When coding in a functional paradigm it is easier to create copies of arrays or objects with spread syntax versus using Object.create, slice, or a library function. Rest syntax is useful when used as a function parameter where there will be an arbitrary number of arguments.
Example:
// Copying an object
const person = {
name: ‘Todd’,
age: 29,
};

const copyOfTodd = { …person };

53
Q

How can you share code between files?

A

Explanation: With ES6 modules via the import … export syntax. Prior to ES6 modules you could use Asynchronous Module Definition for the client side scripts or CommonJS for server side scripts.
Use: To better organize and abstract code bases.
Example:
// file square.js
export { name, draw, reportArea, reportPerimeter };

// file index.js
import { name, draw, reportArea, reportPerimeter } fro

54
Q

Why you might want to create static class members?

A

Explanation: Static class members are properties and methods that do not change.
Use: You would use them for properties that stay the same throughout the application and every instance of the object needs to know that property. They could also be used for utility functions so they can be called without instantiating any object.

55
Q

Can you name two programming paradigms important for JavaScript app developers?

A

OOP and Functional Programming are the most often used. OOP allows inheritance via different “classes”. Functional is pure-functions without side effects.

56
Q

What is functional programming?

A

Explanation: Using pure functions with no side effects to compose your program.
Use: You avoid mutable data and shared states and instead make use of simple functions. It makes the code more predictable.
Example: Instead of having a function with two parameters that does two tasks, you break it into two functions. Each function would have a single parameter and do a single task.

57
Q

What is the difference between classical inheritance and prototypal inheritance?

A

Explanation: Classical instances inherit from class “templates” and create sub-class relationships. They are typically instantiated via constructor functions or the class keyword. Prototypal instances inherit directly from other objects and typically instantiated via factory functions or the Object.create() method.
Use: It’s generally considered better practice to use Prototypal inheritance for a few reasons:
Protoypes are more flexible than classes
The abstraction is only a single level deep
It’s less verbose than using classical inheritance

58
Q

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

A

Object-Oriented Programming and Functional Programming can be used intertwined throughout your coding and don’t need to be solely heralded as enemies. However, they each have their pros and cons and it’s important as a JavaScript developer to understand those. Let’s dive in!
OOP Pros:
— Objects and methods are very readable and understandable.
— OOP utilizes an imperative style, in which code reads like a straight-forward set of instructions as a computer would read it.
OOP Cons:
— OOP commonly depends upon shareable state. The unfortunate result of so many objects and methods existing within the same state and being accessed in an entirely undetermined order can lead the pre-discussed concept of “race conditions”.
FP Pros:
— Utilizing pure functions, leads to reliable functions with no side effects that accomplish and return exactly what you expect them to.
— FP utilizes a more declarative style, which focuses more on what to do and less about how it’s being done. This places the emphasis on performance and optimization, leaving the door to refactor without completely reworking your code.
FP Cons:
— Functional programming is a newer paradigm. It’s much easier to find documentation and information on the OOP approach.
— Similar to one of OOP’s strengths, functional programming can lack readability at times. Sometimes functions can become very verbose and become difficult to follow comparatively to the object-oriented style.
You saw a simple example of this in the Person object and createPerson function we discussed earlier.

The Conclusion
Too often do we pit paradigms, languages, and other competitive programming concepts against one another. Often times, the best approach is that of the hybrid approach. Utilize Object-Oriented Programming in moments where its strengths can best shines. Utilize Functional Programming in moments where its strengths can best shine as well.
The goal for all developers is to become as well-rounded as possible and be able to not only understand a concept at a high-level, but to also be able to understand the advantages and drawbacks of different approaches and to be able to speak to them.

59
Q

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

A

Explanation:
Two-way data: UI fields are bound to model data dynamically. When a UI field changes, the model data changes with it and vice-versa. Side effects can occur.
One-way data: The model is the single source of truth. Changes in the UI signal user intent to the model (or “store” in React). Only the model has the access to change the app’s state. The effect is that data always flows in a single direction. It is deterministic meaning no side effects will occur.
Use: React is a popular framework which uses one-way data flow. Angular on the other hand uses two-way data binding.

60
Q

What is asynchronous programming, and why is it important in JavaScript?

A

Explanation: It allows you to run blocking code outside of the single thread so that the program can continue to run while it waits for the blocking code to complete. Javascript is synchronous by nature, but the runtime (browser or node) has an event loop which allows developers to write asynchronous programs.
Use: It is important for user interfaces, where you are waiting for user input, and for network requests, where you are waiting for some data back from a server.
Example: Using async…await and fetch to fetch resources from an API is a common implementation of async programming.