Javascript Questions Flashcards
(46 cards)
Explain event delegation
Event Delegation is a useful pattern that allows you to write cleaner code, and create fewer event listeners with similar logic, by allowing you to handle events at a higher level in the DOM tree other than the level where the event was first received.
Example:
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
document.getElementById(‘parentList’).addEventListener(‘click’, function(event) {
if (event.target.tagName === ‘LI’) {
console.log(‘Clicked:’, event.target.textContent);
}
});
Explain how prototypal inheritance works
A link between objects allowing properties to be inherited.
Example:
// Parent object constructor
function Animal(name) {
this.name = name;
}
// Prototype method
Animal.prototype.sayHello = function() {
console.log(“Hello, I’m “ + this.name);
};
// Child object constructor
function Dog(name, breed) {
// Call the parent constructor
Animal.call(this, name);
this.breed = breed;
}
// Inherit from the parent’s prototype
Dog.prototype = Object.create(Animal.prototype);
// Add a new method to the child prototype
Dog.prototype.bark = function() {
console.log(“Woof!”);
};
// Create instances of the objects
var animal = new Animal(“Generic Animal”);
var dog = new Dog(“Buddy”, “Labrador Retriever”);
// Test the inherited methods
animal.sayHello(); // Output: “Hello, I’m Generic Animal”
dog.sayHello(); // Output: “Hello, I’m Buddy”
// Test the child-specific method
dog.bark(); // Output: “Woof!”
What is an IIFE in JS
An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined and has its own scope, restricting functions and variables from becoming global.
Example:
(function() {
var message = “Hello, IIFE!”;
console.log(message);
})();
Explain why the following doesn’t work as an IIFE: function foo(){ }();. What needs to be changed to properly make it an IIFE?
(function foo() {})();
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 variable is undeclared if it has not been declared with an appropriate keyword (i.e. var, let or const). An undeclared variable will cause an error.
A variable is undefined if it hasn’t been assigned a value. To check for undefined variables, you would use typeOf.
A variable is assigned a value of null which represents the intentional absence of a value. To check for null variables, you would use == null.
https://www.30secondsofcode.org/articles/s/javascript-undeclared-undefined-null/
https://www.programiz.com/javascript/examples/check-undefined-null
What is a closure, and how/why would you use one?
A function within a function where the inner function uses the data within the scope of the outer function and allows a function to access variables from its lexical scope even after the parent function has finished executing.
Example:
var sayHello = function (name) {
var text = ‘Hello, ‘ + name;
return function () {
console.log(text);
};
};
In this code, the sayHello function takes a name parameter and creates a local variable called text which stores a string message. It then returns an anonymous function. This returned function forms a closure because it “closes over” the variables from its parent scope (the sayHello function).
When you call sayHello(‘Todd’), it creates a closure by capturing the value of the name parameter and the text variable. However, simply calling sayHello(‘Todd’) doesn’t immediately execute the closure or produce any output. It only returns the function itself.
To execute the closure and access the captured variables, you assign the returned function to a variable, like this:
var helloTodd = sayHello(‘Todd’);
Now, helloTodd contains the returned function that has access to the captured name parameter and text variable from the previous call to sayHello(‘Todd’).
To actually log the message, you call the helloTodd function:
helloTodd();
This invocation of helloTodd() executes the closure and logs the value of text, which is ‘Hello, Todd’.
In summary, closures allow a function to access variables from its lexical scope even after the parent function has finished executing. In the provided example, the closure preserves the text variable and allows it to be accessed and used later when calling the returned function.
Example:
function makeSizer(size) {
return function () {
document.body.style.fontSize = ${size}px
;
};
}
const size12 = makeSizer(12);
const size14 = makeSizer(14);
const size16 = makeSizer(16);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
Can you describe the main difference between a .forEach loop and a .map() loop and why you would pick one over the other?
Both .forEach and .map() are used to iterate over arrays.
.forEach executes a provided function over each item in the array without creating a new array. It does not alter the original array directly but can have side effects that alter the original array. Commonly used to perform some action or operation to each item in an array. Example, to update the properties in an array.
.map() creates a new array by transforming each item in the array based on a provided function, it does not alter the original array. It is often used in data manipulation, transforming each element of an array into new values and collecting the results.
What’s a typical use case for anonymous functions?
Anonymous functions, also known as lambda functions or function literals, are functions that are defined without a name. Common uses are callback functions, high-order functions, IIFE (Immediately Invoked Functional Expressions) and in functional programming.
Examples:
Callback:
document.addEventListener(‘click’, function() {
console.log(‘Click event occurred!’);
});
High-order:
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(function(number) {
return number % 2 === 0;
});
console.log(evenNumbers); // Output: [2, 4]
IIFE:
(function() {
// Code within the IIFE
})();
Functional Programming:
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(function(number) {
return number ** 2;
});
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]
How do you organize your code? Module pattern, classical inheritance?
I use the Modular Pattern ES6 (ES Modules). It uses keywords ‘import’ and ‘export’ to define dependencies and expose functionality.
What’s the difference between host objects and native objects?
Host objects are provided by the environment like ‘window’, ‘document’ and ‘setTimeout’.
Native objects, also known as built-in objects, are part of the core JS language like ‘Object’, ‘Array’, ‘Date’ and ‘Math’
Difference between: function Person(){}, var person = Person(), and var person = new Person()?
function Person(){} is a function named Person. It is a function declaration that can be used as a constructor function to create objects.
var person = Person() is not a constructor function. The Person function simply returns a value to the var person.
var person = new Person() is a constructor function. The new attached to Person() creates a new object of the Person() function allowing you to set properties and methods on the newly created object.
What is the difference between .call and .apply?
The .call() and .apply() methods in JavaScript are used to invoke functions and specify the context (the value of this) on which the function should be executed. The main difference between them lies in how arguments are passed to the function being invoked.
.call() and .apply() both take, as their first argument, the object on which the function should be invoked. This object becomes the value of this within the function. The remaining arguments differ in their format:
.call() takes the function arguments as separate arguments after the context object.
.apply() takes the function arguments as an array or an array-like object as the second argument after the context object.
Example:
const person = {
name: ‘John’,
greet: function (message, punctuation) {
console.log(${message} ${this.name}${punctuation}
);
},
};
person.greet(‘Hello’, ‘!’); // Output: Hello John!
person.greet.call(person, ‘Hola’, ‘!’); // Output: Hola John!
person.greet.apply(person, [‘Bonjour’, ‘!’]); // Output: Bonjour John!
Explain function.prototype.bind.
The Function.prototype.bind() method in JavaScript allows you to create a new function that, when called, has a specified this value and optional arguments fixed or pre-set.
Example:
const person = {
firstName: ‘John’,
lastName: ‘Doe’,
getFullName: function() {
return this.firstName + ‘ ‘ + this.lastName;
}
};
const fullName = person.getFullName;
console.log(fullName()); // Output: undefined undefined
const boundFullName = fullName.bind(person);
console.log(boundFullName()); // Output: John Doe
When would you use document.write()?
The document.write() method in JavaScript is used to write dynamic content directly into the HTML document. It allows you to generate content on the fly and insert it at the location where the document.write() statement is placed. You could use it in situations such as simple scripts, demos, or specific edge cases where it’s essential to modify the document during parsing.
What’s the difference between feature detection, feature inference, and using the UA string?
Feature Detection: Feature detection involves directly testing for the presence or support of a particular feature before using it (conditional statements or methods like typeof, instanceof, or in to check if a feature is available before using it).
if (typeof localStorage !== ‘undefined’) {
// localStorage is supported, perform actions using it
} else {
// localStorage is not supported, provide an alternative approach
}d
Feature inference involves making assumptions about the support of a feature based on the availability of related features or properties.
if (‘geolocation’ in navigator) {
// Geolocation is supported, perform actions using it
} else {
// Geolocation is not supported, provide an alternative approach
}
User Agent (UA) String: The User Agent (UA) String is a string provided by the browser, which contains information about the browser’s name, version, and the operating system it is running on.
const userAgent = navigator.userAgent;
if (userAgent.includes(‘Chrome’)) {
// Code specific to Google Chrome browser
} else if (userAgent.includes(‘Firefox’)) {
// Code specific to Mozilla Firefox browser
} else {
// Code for other browsers
}
What is AJAX?
AJAX is a technique that enables asynchronous communication between a web browser and a server, allowing for dynamic updates and data exchange without requiring full page reloads.
What are the advantages and disadvantages of using AJAX?
Advantages include an improved user experience by updating specific parts of a web page without refreshing the entire page, creating a smooth and interactive web experience. Reduced data transfer and asynchronous behavior allows for only necessary data to be transferred between the browser and the server while allowing other tasks to be completed simultaneously.
Disadvantages include not all browsers supporting modern AJAX techniques and security concerns.
What is hoisting?
Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their containing scope during the compilation phase, before the code is executed. This means that regardless of where variables and functions are declared in the code, they are conceptually moved to the top of their respective scopes. Hoisting applies to both variable declarations (using var, not let or const) and function declarations. However, it’s important to note that only the declarations are hoisted, not the initializations or assignments.
Describe event bubbling.
When an event is triggered, such as a click event, the browser checks if there is an event handler attached to the target element. If there is, it executes that event handler. Then, it moves up to the parent element and checks if there is an event handler attached to it. If found, it executes that event handler as well. This process continues until it reaches the root element of the document (usually the html or body element). To stop the event from bubbling further up the DOM hierarchy, you can use the event.stopPropagation() method within an event handler.
What’s the difference between an attribute and a property?
Attributes are defined in HTML markup and provide initial values for properties, <input></input>.
Properties reflect the current state or value of an element and can be read from and written to, value, textContent, checked, className, src, href.
Why is extending built-in JS objects not a good idea?
Extending built-in JavaScript objects refers to adding or modifying properties and methods of existing native object prototypes such as Array.prototype, String.prototype, etc. Reasons to avoid include: compatibility, name clashes, readability and maintainability.
How do you extend a built-in object in JS?
You can extend a built-in object by adding new properties or methods to its prototype.
Example:
Array.prototype.customMethod = function() {
// Custom logic here
};
const myArray = [1, 2, 3];
myArray.customMethod();
Difference between document load event and document DOMContentLoaded event?
The load event waits for all resources to be loaded, while the DOMContentLoaded event triggers as soon as the initial HTML document has been parsed and the DOM is ready for manipulation.
What is the difference between == and ===?
The == operator performs type coercion, which means it allows for automatic type conversion between values of different types before making the comparison.
The === operator performs strict equality comparison without type coercion.