Javascript Questions Flashcards

1
Q

Explain event delegation

A

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);
}
});

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

Explain how prototypal inheritance works

A

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!”

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

What is an IIFE in JS

A

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);
})();

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

(function foo() {})();

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

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

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

A

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

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

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

A

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.

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

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

I use the Modular Pattern ES6 (ES Modules). It uses keywords ‘import’ and ‘export’ to define dependencies and expose functionality.

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

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’

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

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

What is the difference between .call and .apply?

A

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!

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

Explain function.prototype.bind.

A

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

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

When would you use document.write()?

A

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.

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

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

What is AJAX?

A

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.

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

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.

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

What is hoisting?

A

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.

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

Describe event bubbling.

A

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.

20
Q

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

A

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.

21
Q

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

A

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.

22
Q

How do you extend a built-in object in JS?

A

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();

23
Q

Difference between document load event and document DOMContentLoaded event?

A

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.

24
Q

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

A

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.

25
Q

Explain the same-origin policy with regards to JavaScript.

A

The same-origin policy is a security mechanism enforced by web browsers that restricts JavaScript code running in a web page from accessing resources (such as data or methods) on a different origin (combination of protocol, domain, and port) than the one from which the script originated. The purpose of this policy is to prevent malicious websites from tampering with or stealing data from other websites without permission.

Under the same-origin policy, JavaScript code can only access resources (such as making AJAX requests, modifying the DOM, or accessing cookies) from the same origin as the web page that hosts the script.

26
Q

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

A

function duplicate(arr){
arr.forEach(item => {
arr.push(item)
})
return arr
}

27
Q

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

A

The use of the word “ternary” in “ternary expression” highlights the fact that it involves three parts: the condition, the expression when the condition is true, and the expression when the condition is false. It takes the form of condition ? expression1 : expression2, where the condition is evaluated first, and if it’s true, expression1 is executed and becomes the result of the expression. If the condition is false, expression2 is executed and becomes the result.

28
Q

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

A

In general, using “use strict” is recommended for modern JavaScript development. It helps catch errors, promotes better coding practices, and improves code quality. However, it’s important to carefully evaluate the impact on existing codebases and consider the browser or environment compatibility requirements before enabling strict mode.

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 = 0; i < 100; i++){
if (i % 3 == 0 && i % 5 == 0){
return ‘fizzbuzz’}
else if (i % 3 == 0){
return ‘fizz’}
else if (i % 5 == 0){
return ‘buzz’}
else return (i)}}

30
Q

What is global scope?

A

Global scope refers to the outermost scope in JavaScript, which is not enclosed within any function or block. Variables declared in the global scope are accessible from anywhere within the codebase.

Example:
var globalVariable = ‘I am in the global scope’;

function foo() {
console.log(globalVariable); // Output: I am in the global scope
}

foo();
console.log(globalVariable); // Output: I am in the global scope

31
Q

What is scope?

A

Scope refers to the current context of your code. Scopes can be globally or locally defined.

32
Q

What are the different types of local scope?

A

These are the main different types of local scope used depending on where the variables are declared: function scope, lexical scope, block scope and module scope.

Function Scope: Variables declared within a function are function-scoped and have local scope within that function. They are accessible only within the function and not outside of it.

function myFunction() {
var localVar = ‘I am a function-scoped variable’;
console.log(localVar); // Output: I am a function-scoped variable
}

console.log(localVar); // ReferenceError: localVar is not defined (not accessible in the global scope)

myFunction();

Block Scope (Introduced in ES6): Variables declared with let and const within a block (e.g., within curly braces {}) are block-scoped. This includes variables declared within if statements, for loops, while loops, and any other block structures. Block-scoped variables are accessible only within the block in which they are defined.

function myFunction() {
if (true) {
let blockVar = ‘I am a block-scoped variable’;
console.log(blockVar); // Output: I am a block-scoped variable
}
console.log(blockVar); // ReferenceError: blockVar is not defined (not accessible outside the block)
}

myFunction();

Module Scope: When working with modules (using import and export), variables declared within a module file have module-level scope. They are not accessible outside the module unless explicitly exported.

// module.js
let moduleVar = ‘I am a module-scoped variable’;

export { moduleVar };

// main.js
import { moduleVar } from ‘./module.js’;

console.log(moduleVar); // Output: I am a module-scoped variable
console.log(window.moduleVar); // undefined (not accessible as a global variable)

Lexical Scope (Closure): Lexical scope refers to the scope determined by the physical placement of code in the source code file. It allows functions to access variables from their parent scope, even after the parent function has finished executing. This behavior is achieved through closures.

function outerFunction() {
var outerVar = ‘I am in the outer scope’;

function innerFunction() {
console.log(outerVar); // Output: I am in the outer scope
}

innerFunction();
}

outerFunction();

In this example, the innerFunction has access to the outerVar variable from its parent scope (outerFunction) due to lexical scoping.

33
Q

What is scope chain?

A

Scope chains establish the scope for a given function. Each function defined has its own nested scope as we know, and any function defined within another function has a local scope which is linked to the outer function - this link is called the chain. It’s always the position in the code that defines the scope. When resolving a variable, JavaScript starts at the innermost scope and searches outwards until it finds the variable/object/function it was looking for.

34
Q

Explain scope and ‘this’.

A

Each scope binds a different value of this depending on how the function is invoked. We’ve all used the this keyword, but not all of us understand it and how it differs when invoked. By default this refers to the outer most global object, the window.

Here are some common scenarios that determine the value of this:

Global scope: When this is referenced outside of any function or object, it refers to the global object, which is window in a browser environment or global in Node.js.

Function invocation: When a function is called without any context, such as a standalone function call, this refers to the global object (window or global). However, if you are in strict mode (‘use strict’), this will be undefined instead of the global object.

var myFunction = function () {
console.log(this); // this = global, [object Window]
};
myFunction();

Here, the myFunction is a regular function that is called directly. In this case, this refers to the global object, which is window in a browser environment. Therefore, this inside myFunction refers to the global window object, and console.log(this) will output [object Window].

Object method invocation: When a function is called as a method of an object using dot notation, such as object.method(), this refers to the object on which the method is called. The object becomes the context for this.

var myObject = {};
myObject.myMethod = function () {
console.log(this); // this = Object { myObject }
};

Here, we have an object myObject with a method myMethod. When myMethod is called as a method of myObject (e.g., myObject.myMethod()), this refers to the object itself. In this case, this inside myMethod refers to the myObject object, and console.log(this) will output Object { myObject }.

Constructor invocation: When a function is used as a constructor function with the new keyword, this refers to the newly created object being constructed.

function Person(name, age) {
this.name = name;
this.age = age;
}

var person1 = new Person(‘Alice’, 25);
console.log(person1.name); // Output: Alice
console.log(person1.age); // Output: 25

var person2 = new Person(‘Bob’, 30);
console.log(person2.name); // Output: Bob
console.log(person2.age); // Output: 30

In this example, we have a constructor function called Person that takes two parameters: name and age. Inside the constructor function, we use the this keyword to assign the passed values to the respective properties of the newly created object.

When we invoke the Person function with the new keyword, it creates a new object and sets this to refer to that new object. The properties name and age are assigned to the newly created object using this.name and this.age.

After creating two instances of Person using the new keyword (person1 and person2), we can access their properties using dot notation (person1.name, person1.age, etc.). Each instance has its own unique set of name and age properties, as defined by the constructor function.

Event handler invocation: When a function is used as an event handler, such as in an event listener, this refers to the element on which the event occurred.

var nav = document.querySelector(‘.nav’); // <nav class="nav">
var toggleNav = function () {
console.log(this); // this = <nav> element
};
nav.addEventListener(‘click’, toggleNav, false);

In this example, we have an HTML element <nav class="nav">, which is stored in the nav variable using document.querySelector(). We also have a function toggleNav that serves as an event listener callback function. When the click event occurs on the nav element, the toggleNav function is invoked as an event handler. In this case, this refers to the element on which the event occurred. So, inside the toggleNav function, this refers to the <nav> element itself, and console.log(this) will output the <nav> element.

35
Q

What does e.preventDefault() do?

A

By calling e.preventDefault(), the default behavior of form submission, which typically involves a page refresh or navigating to a new URL, is prevented. Instead, you have the opportunity to handle the form submission in a custom manner, such as performing validation, making an AJAX request, or updating the state of a React component.

By including e.preventDefault(), you can take control of the form submission event and define your own logic without the browser’s default behavior interfering.

36
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

Here are some reasons why you might use the “load” event:

Resource Dependency: You may want to perform certain actions or display content only after a specific resource has finished loading. For example, if you have an image gallery, you may want to ensure that all the images are loaded before displaying them to the user.

Initialization: You can use the “load” event to initialize or set up certain parts of your application after all the required resources have been loaded. This ensures that your application is in a consistent state before interacting with the user.

Handling Errors: The “load” event can also be used to handle errors when a resource fails to load. In such cases, you can provide alternative content or take appropriate action to handle the error condition.

While the “load” event is widely used and useful in many scenarios, it does have some disadvantages:

Delayed Execution: The “load” event is triggered after the resource has finished loading, which means there can be a delay before the associated code executes. This delay can be noticeable, especially for larger resources or slower network connections.

Limited Support for Error Handling: While the “load” event can handle successful loading, it has limited support for error handling. In some cases, errors may not trigger the “load” event, and you might need to use alternative approaches like the “error” event or error handling mechanisms specific to the resource being loaded.

Alternatives to the “load” event depend on the specific use case and the type of resource being loaded:

Promises: Promises provide a more flexible and robust way to handle asynchronous operations, including resource loading. You can use promises to handle successful loading, errors, and perform further actions when the promises resolve or reject.

Modern APIs: Many modern APIs, such as the Fetch API for network requests or the Intersection Observer API for observing element visibility, provide built-in mechanisms to handle loading and error conditions. These APIs offer more fine-grained control and options for error handling and resource loading.

37
Q

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

A

A single page application (SPA) is a web application that operates within a single HTML page. Unlike traditional multi-page applications, where each interaction triggers a server request and a full page reload, SPAs load the initial HTML, CSS, and JavaScript resources once and then dynamically update the content on the page as users interact with it.

SPAs provide a more responsive and interactive user experience since they can update the content without requiring a full page reload. Server-Side Rendering (SSR): SSR generates HTML on the server and sends it to the client, making the initial page load SEO-friendly. Frameworks like Next.js and Nuxt.js enable SSR for React and Vue.js applications, respectively.

38
Q

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

A

It’s important to consider the context, requirements, and constraints of your project when choosing between Promises and callbacks. Promises are generally considered a more modern and preferred approach for handling asynchronous operations due to their advantages in readability, error handling, and composition. However, if you need to support older environments or work with existing code that heavily relies on callbacks, using callbacks might be more appropriate.

39
Q

What tools and techniques do you use debugging JavaScript code?

A

Console.log(), error messages and stack traces

40
Q

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

A
  1. For…in loop (Object iteration):
    The for...in loop is used to iterate over the enumerable properties of an object. It iterates over each property name and allows you to access the corresponding property value using the property name. However, it’s important to note that the for...in loop also iterates over inherited properties and should be used with caution.Example:
    const obj = { a: 1, b: 2, c: 3 };for (const key in obj) {
    console.log(key, obj[key]);
    }
  2. Object.keys() method (Object iteration):
    The Object.keys() method returns an array of enumerable property names of an object. You can then use other array iteration methods like forEach, map, or reduce to iterate over the property names and access the corresponding property values.Example:
    const obj = { a: 1, b: 2, c: 3 };Object.keys(obj).forEach((key) => {
    console.log(key, obj[key]);
    });
  3. For…of loop (Array iteration):
    The for...of loop is used to iterate over iterable objects, including arrays. It allows you to directly access the array items without needing to access them by index. This loop is especially useful for iterating over arrays.Example:
    const arr = [1, 2, 3];for (const item of arr) {
    console.log(item);
    }
  4. Array.forEach() method (Array iteration):
    The forEach() method is available on arrays and allows you to iterate over each item of an array. It executes a provided callback function for each element, passing the current element, index, and the entire array as arguments.Example:
    const arr = [1, 2, 3];arr.forEach((item, index) => {
    console.log(item, index);
    });
  5. Other array iteration methods:
    JavaScript arrays have several other built-in iteration methods like map(), filter(), reduce(), and find() that allow you to perform specific operations on array items while iterating over them. These methods provide a concise and functional programming approach to array iteration.Example:
    const arr = [1, 2, 3];const doubledArr = arr.map((item) => item * 2);
    console.log(doubledArr);const filteredArr = arr.filter((item) => item > 1);
    console.log(filteredArr);const sum = arr.reduce((acc, item) => acc + item, 0);
    console.log(sum);
41
Q

Explain the difference between mutable and immutable objects.

A
  1. Mutable Objects:
    Mutable objects are objects whose state or data can be modified after they are created. This means that you can change the values of their properties, add or remove properties, or modify their internal state. Examples of mutable objects in JavaScript include arrays, objects (plain objects and instances of classes), and some built-in objects like Date and RegExp.Example of modifying a mutable object:
    const arr = [1, 2, 3];
    arr.push(4); // Modifying the array by adding a new element
    console.log(arr); // Output: [1, 2, 3, 4]Mutable objects can be convenient when you need to change the object’s state or update its properties. However, they can also introduce complexity, especially in large applications, as the state of mutable objects can be modified from multiple parts of the program, leading to potential bugs or unintended side effects.
  2. Immutable Objects:
    Immutable objects, on the other hand, are objects whose state cannot be changed after they are created. Once an immutable object is created, its state remains constant and cannot be modified. Instead of changing the object, any operation that appears to modify an immutable object actually creates a new object with the updated state. Examples of immutable objects in JavaScript include strings, numbers, and boolean values.Example of creating a new immutable object:
    const str = ‘Hello’;
    const newStr = str + ‘ World’; // Creating a new string object
    console.log(newStr); // Output: “Hello World”Immutable objects offer several benefits, such as simplicity, predictability, and easier debugging. Since their state cannot be modified, they are inherently thread-safe and can be safely shared across multiple parts of a program without worrying about unwanted changes.It’s important to note that while an immutable object itself cannot be changed, it doesn’t mean that the variables holding references to immutable objects cannot be reassigned. The immutability refers to the object’s internal state.

In summary, mutable objects allow modifications to their state, while immutable objects maintain a fixed state and require creating new objects when changes are needed. The choice between mutable and immutable objects depends on the specific requirements of your application, considering factors such as performance, simplicity, and the need for shared or isolated state.

42
Q

How to make an object immutable?

A

In JavaScript, objects are mutable by default, meaning their properties can be modified directly. However, you can implement immutability by following certain approaches. Here are a few techniques to make an object immutable:

  1. Object.assign:
    const originalObject = { key: ‘value’ };
    const immutableObject = Object.assign({}, originalObject);
  2. Spread syntax:
    const originalObject = { key: ‘value’ };
    const immutableObject = { …originalObject };
  3. Immutable.js:
    Immutable.js is a library that provides immutable data structures. You can create immutable objects using the Map data structure provided by Immutable.js.import { Map } from ‘immutable’;const originalObject = Map({ key: ‘value’ });
    const immutableObject = originalObject.set(‘newKey’, ‘newValue’);
  4. Readonly properties (ES6):
    In ECMAScript 6 (ES6), you can use the Object.freeze() method to make an object read-only. However, note that this only makes the top-level properties read-only, and any nested objects or arrays within the object can still be modified.const originalObject = { key: ‘value’ };
    const immutableObject = Object.freeze(originalObject);

It’s important to note that these techniques create a new object with the updated properties rather than modifying the original object directly. This ensures that the original object remains unchanged and helps enforce immutability.

43
Q

What are the differences between Var, Let and Const?

A

https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/

  1. Scope:
    • var has function scope. Variables declared with var are accessible throughout the entire function in which they are declared, regardless of block scope.
    • let and const have block scope. Variables declared with let and const are only accessible within the block they are declared in, such as within a loop or an if statement.
  2. Hoisting:
    • var declarations are hoisted to the top of their scope. This means that you can access and use a var variable before it is declared in the code but not it’s value resulting in ‘Output: undefined’
    • let and const declarations are hoisted as well, but they are not initialized. You cannot access let and const variables before their declaration or it returns ‘Error: ReferenceError: y is not defined’
  3. Reassignment:
    • var and let variables can be reassigned new values.
    • const variables are read-only and cannot be reassigned once they are initialized. However, for objects and arrays declared with const, their properties or elements can still be modified.
  4. Block scoping:
    • var variables are not block-scoped, meaning they are accessible outside of the block they are declared in.
    • let and const variables are block-scoped, meaning they are limited to the block they are declared in and not accessible outside of it.
  5. Redeclaration:
    • var allows for redeclaration of variables within the same scope.
    • let and const do not allow redeclaration of variables within the same scope. You will get an error if you try to redeclare a variable with let or const in the same block.
  6. Temporal Dead Zone (TDZ):
    • let and const variables are hoisted to the top of their block but remain in the TDZ until the point of declaration. Accessing them before their declaration results in a ReferenceError.

Overall, let and const provide more predictable scoping behavior and better support for block scoping compared to var. It is generally recommended to use let and const over var to avoid potential issues caused by hoisting and function scoping. Additionally, using const for variables that should not be reassigned can help enforce immutability and improve code maintainability.

44
Q

What are the differences between statically-typed and dynamically-typed variables?

A

Statically-typed variables are assigned based on their value and cannot be changed.
int number = 10; number can only be integers.

Dynamically-typed variables, depending on the variable they are declared with can be changed.
let number = 10; number = ‘a’

45
Q

What are high-order functions?

A

There are two main types of higher-order functions:

Functions that take other functions as arguments: These functions accept one or more functions as parameters, allowing you to customize their behavior. Examples of higher-order functions that take other functions as arguments are map, filter, and reduce in JavaScript.

// Example of map function that takes a function as an argument
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map((num) => num ** 2);
// Here, the map function takes the callback function (num => num ** 2) as an argument.
// The map function applies the callback function to each element in the ‘numbers’ array.
// The ‘squaredNumbers’ array will contain [1, 4, 9, 16, 25].

Functions that return another function: These functions generate and return new functions based on their internal logic or configurations. These functions are often used to create reusable behavior or to implement currying, a technique in which a function with multiple arguments is transformed into a sequence of functions with a single argument each.

// Example of a function that returns another function
function multiplier(factor) {
return function (number) {
return number * factor;
}
}
const multiplyByTwo = multiplier(2);
const multiplyByThree = multiplier(3);

console.log(multiplyByTwo(5)); // Output: 10
console.log(multiplyByThree(5)); // Output: 15

In this example, the multiplier function takes a factor as an argument and returns a new function that multiplies any given number by the specified factor. By calling multiplier(2), we obtain a function multiplyByTwo that multiplies numbers by 2. Similarly, calling multiplier(3) gives us a function multiplyByThree that multiplies numbers by 3.

46
Q

What are dependencies in programming?

A

In software development, dependencies refer to external components, libraries, or modules that a particular piece of code relies on to function correctly. These dependencies are essential for the code to work as intended and often provide additional functionality, utility, or resources to the application.