Questions I Flashcards

1
Q

Which JS array methods change the original array?

A

pop(): Removes the last element from the array.

shift(): Removes the first element from the array.

unshift(): Adds one or more elements to the beginning of the array.

splice(): Changes the contents of an array by removing or replacing existing elements and/or adding new elements.

sort(): Sorts the elements of the array in place.

reverse(): Reverses the order of the elements in the array.

fill(): Fills all the elements of the array with a static value.

copyWithin(): Shallow copies part of an array to another location in the same array.

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

What is the easiest way to convert an array to an object?

A

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

Object.assign({}, [‘a’,’b’,’c’]); // {0:”a”, 1:”b”, 2:”c”}

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

What is the difference between var, let and const?

A

var:
Scope: Function-scoped or globally scoped.
Re-declaration: Allowed within the same scope.
Initialization: Can be declared without initialization (undefined).
Hoisting: Hoisted and initialized as undefined.
Global Object: Creates a property on the global object.

let:
Scope: Block-scoped.
Re-declaration: Not allowed in the same scope.
Initialization: Can be declared without initialization (undefined).
Hoisting: NOT Hoisted but not initialized (temporal dead zone).
Global Object: Does not create a property on the global object.

const:
Scope: Block-scoped.
Re-declaration: Not allowed in the same scope.
Initialization: Must be initialized at the time of declaration.
Hoisting: NOT Hoisted but not initialized (temporal dead zone).
Global Object: Does not create a property on the global object and cannot be reassigned.

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

What is a Temporal Dead Zone?

A

The Temporal Dead Zone (TDZ) is a concept in JavaScript that refers to the time period during which a variable is in scope but cannot be accessed. This occurs when a variable is declared using let or const but has not yet been initialized. Here’s a breakdown of the key aspects:

THROWS REFERENCE ERROR VARIABLE IS NOT INITIALIZED

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

What are the ways to create object in JavaScript?

A

1. Object Literal Syntax
This is the simplest and most straightforward way to create an object. You define the object using curly braces, {}, and specify key-value pairs.

const obj = {
key1: value1,
key2: value2,
};

2. Using the new Object() Syntax

const obj = new Object();
obj.key1 = value1;
obj.key2 = value2;

**3. Constructor Functions

  1. Object.create()
  2. JSON Parsing**
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do you copy properties from one object to other?

A
  1. Object.assign()
    The Object.assign() method copies the values of all enumerable own properties from one or more source objects to a target object. It returns the target object.
  2. Spread Syntax
    The spread syntax (…) allows you to create a new object by copying properties from existing objects. This method is concise and commonly used in modern JavaScript.
  3. For…in Loop
    You can use a for…in loop to iterate over the properties of the source object and copy them to the target object.
  4. JSON Methods
    You can use JSON.stringify() and JSON.parse() to create a deep copy of an object. This method works for simple objects but does not handle functions, dates, or undefined values.
  5. Object.entries() and Object.fromEntries()
    You can use Object.entries() to convert an object into an array of key-value pairs, and then use Object.fromEntries() to create a new object.
  6. Lodash Library
    If you are using the Lodash library, you can use the _.assign() method, which is similar to Object.assign() but may have additional functionality.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What do you understand by “this” keyword in JavaScript?

A

The this keyword in JavaScript is a special identifier that refers to the context in which a function is executed. Its value can change depending on how a function is called, and understanding its behavior is crucial for effective JavaScript programming. Here are the key points about this:

Key Points about this in JavaScript

Global Context:
In the global scope (outside of any function), this refers to the global object.
In browsers, this is typically the window object.

Function Context:
In a regular function (non-strict mode), this refers to the global object if the function is called without an object context.

Method Context:
When a function is called as a method of an object, this refers to the object through which the method is called.

Constructor Function Context:
When a function is called with the new keyword, this refers to the newly created object.

Event Handlers:
In event handler functions, this refers to the element that fired the event.

Explicit Binding:
You can control the value of this using call(), apply(), and bind().
call() and apply() invoke the function with a specific this value, while** bind() returns a new function** with this permanently set to a specified value.

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

What is currying?

A

Currying is a functional programming technique in which a function with multiple arguments is transformed into a sequence of functions, each taking a single argument. Instead of accepting all parameters at once, a curried function takes the first argument and returns another function that takes the second argument, and so on, until all arguments have been supplied.

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

const addFive = add(5); // returns a function that adds 5 to its argument
console.log(addFive(3)); // Output: 8
console.log(add(10)(20)); // Output: 30

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

What is the difference between regular functions and arrow functions?

A

Syntax: Regular functions use the function keyword, while arrow functions have a shorter syntax using the => operator.

this Binding: Regular functions have their own this context, which depends on how they are called. In contrast, arrow functions lexically bind this from the surrounding context, meaning they inherit this from where they are defined.

Arguments Object: Regular functions have access to the arguments object, which contains all arguments passed to the function. Arrow functions do not have their own arguments object; instead, you can use rest parameters (…args) to gather arguments.

Constructor: Regular functions can be used as constructors with the new keyword, while arrow functions cannot be used as constructors and will throw an error if you try to invoke them with new.

Method Definition: Regular functions are suitable for defining methods on objects, whereas arrow functions are not ideal for this purpose due to their handling of this.

Function Hoisting: Regular functions are hoisted, meaning they can be called before their definition in the code. Arrow functions are not hoisted and must be defined before they can be used.

Return Statement: If a regular function does not explicitly return a value, it returns undefined. Arrow functions implicitly return the result of a single expression without needing a return statement.

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

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

A

The difference between the == (equality) operator and the === (strict equality) operator in JavaScript lies in how they compare values.

Type Coercion:

== (Equality): Performs type coercion, meaning it converts the operands to the same type before making the comparison. This can lead to unexpected results.

Example: 0 == ‘0’ evaluates to true because the string ‘0’ is converted to the number 0 for the comparison.

=== (Strict Equality): Does not perform type coercion. Both the value and the type must be the same for the comparison to be true.

Example: 0 === ‘0’ evaluates to false because the types (number vs. string) are different.

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

Explain Implicit Type Coercion in JavaScript

A

Implicit type coercion in JavaScript refers to the automatic conversion of values from one type to another when performing operations. This behavior occurs when operators or functions encounter operands of different types. JavaScript tries to convert the values to a compatible type before executing the operation. While this feature can make code more flexible, it can also lead to unexpected results or bugs if not properly understood.

Using Operators:

Certain operators, like the arithmetic operators (+, -, *, /), can trigger coercion.
For example, when using the + operator, if one of the operands is a string, JavaScript will convert the other operand to a string:

console.log(‘5’ + 2); // “52” (number 2 is coerced to string)
console.log(5 + 2); // 7 (both operands are numbers)

Comparison Operators:
When using the equality operator (==), JavaScript performs coercion to compare different types:

console.log(0 == ‘0’); // true (string ‘0’ is converted to number 0)
console.log(false == 0); // true (false is coerced to number 0)

Logical Operators:
Logical operators (&&, ||, !) also perform type coercion:
console.log(true || 0); // true (0 is coerced to false)
console.log(false && ‘hello’); // false (short-circuit evaluation)

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

What are the various statements in error handling?

A
  1. try Statement
    The try statement is used to wrap code that may potentially throw an error. If an error occurs within the try block, the control is transferred to the corresponding catch block.
  2. catch Statement
    The catch statement is used to define a block of code that executes if an error occurs in the associated try block. It can also capture the error object for further processing.
  3. finally Statement
    The finally statement is used to define a block of code that executes after the try and catch blocks, regardless of whether an error occurred or not. This is useful for cleanup activities, such as closing files or releasing resources.
  4. throw Statement
    The throw statement is used to create a custom error. When an error is thrown, the control is transferred to the nearest catch block, if present. You can throw built-in errors or create your own error objects.
  5. Error Object
    JavaScript provides built-in error objects, such as Error, TypeError, ReferenceError, and others. You can instantiate these error objects and throw them for more specific error handling.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are the various statements in error handling- key differences

A

try: Wraps code that may throw an error.

catch: Handles errors thrown in the try block.

finally: Executes cleanup code regardless of error occurrence.

throw: Creates a custom error to be caught by catch.

Error Object: Built-in objects representing different types of errors for better specificity.

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

What is the purpose of Error object?

A

-> Error Representation
-> Debugging
-> Custom Errors
-> Error Propagation
-> Information Sharing

Built-in Error Types:
-> TypeError: Represents an error when a value is not of the expected type.
-> ReferenceError: Thrown when trying to access a variable that is not declared.
-> SyntaxError: Occurs when the code does not conform to the syntax rules.
-> RangeError: Indicates a number is outside a valid range.

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

What are the 3 states of promise?

A

A Promise in JavaScript represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises have three distinct states:

  1. Pending
    Definition: The initial state of a Promise. It indicates that the asynchronous operation has not yet completed; the outcome is still unknown.
  2. Fulfilled
    Definition: The state of a Promise when the asynchronous operation has completed successfully.
    Characteristics: When a Promise is fulfilled, it means that the operation completed without any errors, and it has a resolved value. The then method can be used to handle the successful outcome.
  3. Rejected
    Definition: The state of a Promise when the asynchronous operation has failed.
    Characteristics: When a Promise is rejected, it indicates that an error occurred during the operation, and it has a reason for the failure (often an error object). The catch method can be used to handle the error.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is an async function?

A

An async function in JavaScript is a special type of function that allows you to work with asynchronous code more easily and intuitively. It is defined using the async keyword before the function declaration. Here’s a detailed overview of what async functions are and how they work:

Key Features of Async Functions
Simplified Syntax for Asynchronous Operations:

Async functions enable you to write asynchronous code that looks and behaves like synchronous code, making it easier to read and maintain.
Return Value:

An async function always returns a Promise. If the function returns a value, that value is automatically wrapped in a resolved Promise. If it throws an error, the returned Promise will be rejected.

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

What is a prototype? What is the difference between __proto__ and prototype?

A

A prototype is an object from which other objects inherit properties and methods. Every JavaScript object has an internal property called [[Prototype]], which can be accessed through the __proto__ property (more on this below). This prototype chain allows for inheritance, enabling objects to share methods and properties without needing to define them repeatedly.

prototype:
The prototype property is found on constructor functions (and classes). It is an object that is used as a template for instances created from that constructor. Any properties or methods defined on prototype will be available to all instances of that constructor.

__proto__:
The __proto__ property is an accessor property (a property that can be read or written to) on all objects. It refers to the object’s prototype (the [[Prototype]] internal property). When you access object.__proto__, you get the prototype object from which the object was constructed.

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

Prototype vs __proto__

A

Prototype: Refers to the object that serves as a template for instances of a constructor. It is used for inheritance and is a property of constructor functions (or classes).

__proto__: An internal property of all objects that points to the prototype from which the object was instantiated. It allows you to access the prototype chain at runtime.

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

What is an event loop?

A

The event loop is a fundamental concept in JavaScript that allows it to perform non-blocking operations despite being single-threaded. It enables asynchronous programming by managing the execution of code, collecting events, and processing the event queue. Here’s a detailed overview of how the event loop works:

20
Q

What is destructuring assignment (array, object)?

A

Destructuring assignment is a convenient syntax in JavaScript that allows unpacking values from arrays or properties from objects into distinct variables. This feature improves code readability and reduces the need for repetitive code when accessing multiple properties or elements. Let’s explore both array and object destructuring assignments.

Array destructuring allows you to extract values from an array and assign them to individual variables. The syntax uses square brackets ([]).

const fruits = [‘apple’, ‘banana’, ‘cherry’];
// Destructuring assignment
const [firstFruit, secondFruit] = fruits;
console.log(firstFruit); // Output: “apple”
console.log(secondFruit); // Output: “banana”

Destructuring Assignment for Objects
Object destructuring allows you to extract properties from an object and assign them to variables. The syntax uses curly braces ({}).

const person = {
name: ‘Alice’,
age: 30,
city: ‘New York’
};

// Destructuring assignment
const { name, age } = person;

21
Q

What are the differences between cookie, local storage and session storage?

A

Cookies:

Purpose: Mainly for server-side session management and tracking.
Capacity: About 4 KB per cookie.
Expiration: Can be set with specific expiration; deleted when the session ends if not set.
Accessibility: Accessible by both server and client; sent with every HTTP request.

Local Storage:

Purpose: For long-term client-side data storage.
Capacity: 5-10 MB per origin.
Expiration: Data persists until explicitly deleted.
Accessibility: Accessible only through JavaScript; not sent with HTTP requests.

Session Storage:

Purpose: For short-term storage within a single browser session.
Capacity: Similar to local storage (about 5-10 MB per origin).
Expiration: Data is cleared when the tab or window is closed.
Accessibility: Accessible only through JavaScript; not sent with HTTP requests.

22
Q

What are the different ways of adding event listener to an element?

A

Using addEventListener Method
This is the most common and modern way to attach an event listener to an element.

const button = document.getElementById(‘myButton’);
button.addEventListener(‘click’, function() {
console.log(‘Button clicked!’);
});

Using HTML Attributes
You can directly add event handlers in HTML using attributes.

<button>Click me!</button>

23
Q

What is an event delegation?

A

Event delegation is a technique in JavaScript that allows you to manage events efficiently by attaching a single event listener to a parent element instead of multiple listeners to individual child elements. This approach takes advantage of event bubbling, where an event triggered on a child element propagates (bubbles) up to its parent elements in the DOM hierarchy.

Event Bubbling:
When an event occurs on an element, it first triggers the event on that element and then propagates up to its parent elements (and their ancestors) until it reaches the root of the DOM. This bubbling mechanism allows parent elements to listen for events that occur on their children.

Single Event Listener:
**Instead of adding separate event listeners to multiple child elements, **you can add one listener to a common parent. This reduces memory usage and improves performance, especially when dealing with a large number of child elements.

Dynamic Elements:
Event delegation is particularly useful when working with dynamically generated elements. If new child elements are added to the DOM after the event listener is set up, they will still be able to trigger the parent’s event listener.

24
Q

What are the possible ways to create objects in JavaScript

A

Object literal syntax:

Object constructor:

Object’s create method:

Function constructor:

Function constructor with prototype

Object’s assign method:

25
Q

What is the difference between Call, Apply and Bind

A

Call: The call() method invokes a function with a given this value and arguments provided one by one

Apply: Invokes the function with a given this value and allows you to pass in arguments as an array

CALL AND APPLY CALLS THE FUNCTIONS

BIND RETURNS A NEW FUNCTION

Bind: returns a new function, allowing you to pass any number of arguments

26
Q

What is JSON and its common operations

A

JSON is a text-based data format following JavaScript object syntax,

Parsing: Converting a string to a native object

Stringification: Converting a native object to a string so that it can be transmitted across the network

27
Q

What is the purpose of the array slice method

A

The slice() method returns the selected elements in an array as a new array object. It selects the elements starting at the given start argument, and ends at the given optional end argument without including the last element

28
Q

What is the purpose of the array splice method

A

The splice() method adds/removes items to/from an array, and then returns the removed item.

29
Q

How do you compare Object and Map?

A

Objects are similar to Maps in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Due to this reason, Objects have been used as Maps historically. But there are important differences that make using a Map preferable in certain cases:

The keys of an Object can be Strings and Symbols, whereas they can be any value for a Map, including functions, objects, and any primitive type.

MAP CAN HAVE A KEY OF ANY TYPE

The keys in a Map are ordered while keys added to Object are not. Thus, when iterating over it, a Map object returns keys in the order of insertion.

THE KEYS IN MAP ARE ORDERED

You can get the size of a Map easily with the size property, while the number of properties in an Object must be determined manually.

OBJECT DOESNT HAVE SIZE

A Map is an iterable and can thus be directly iterated, whereas iterating over an Object requires obtaining its keys in some fashion and iterating over them.

MAP IS ITERABLE

An Object has a prototype, so there are default keys in an object that could collide with your keys if you’re not careful. As of ES5 this can be bypassed by creating an object(which can be called a map) using Object.create(null), but this practice is seldom done.

A Map may perform better in scenarios involving frequent addition and removal of key pairs.

30
Q

What is the difference between == and === operators

A

JavaScript provides both strict(===, !==) and type-converting(==, !=) equality comparison. The strict operators take type of variable in consideration, while non-strict operators make type correction/conversion based upon values of variables. The strict operators follow the below conditions for different types,

31
Q

What are lambda expressions or arrow functions

A

An arrow function is a shorter/concise syntax for a function expression and does not have its own this, arguments, super, or new.target. These functions are best suited for non-method functions, and they cannot be used as constructors.

32
Q

What is a first class function

A

In Javascript, functions are first class objects. First-class functions means when functions in that language are treated like any other variable.

33
Q

What is a higher order function

A

A higher-order function is a function that accepts another function as an argument or returns a function as a return value or both. The syntactic structure of higher order function will be as follows,

34
Q

What is a unary function

A

A unary function (i.e. monadic) is a function that accepts exactly one argument. It stands for a single argument accepted by a function.

35
Q

What is the currying function

A

Currying is the process of taking a function with multiple arguments and turning it into a sequence of functions each with only a single argument. Currying is named after a mathematician Haskell Curry. By applying currying, an n-ary function turns into a unary function.

36
Q

What is a pure function

A

A Pure function is a function where the return value is only determined by its arguments without any side effects. i.e,

If you call a function with the same arguments ‘n’ number of times and ‘n’ number of places in the application then it will always return the same value.

37
Q

What is an IIFE (Immediately Invoked Function Expression)

A

IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. The signature of it would be as below,

(function () {
// logic here
})();

38
Q

What is memoization

A

Memoization is a functional programming technique which attempts to increase a function’s performance by caching its previously computed results.

Each time a memoized function is called, its parameters are used to index the cache.

If the data is present, then it can be returned, without executing the entire function. Otherwise the function is executed and then the result is added to the cache.

39
Q

What are closures

A

A closure is the combination of a function bundled(enclosed) together with its lexical environment within which that function was declared. i.e, It is an inner function that has access to the outer or enclosing function’s variables, functions and other data even after the outer function has finished its execution. The closure has three scope chains.

FUNCTION + LEXICAL ENVIROMENT

Own scope where variables defined between its curly brackets
Outer function’s variables
Global variables

40
Q

What is scope in javascript

A

Scope is the accessibility of variables, functions, and objects in some particular part of your code during runtime.

In other words, scope determines the visibility of variables and other resources in areas of your code.

41
Q

What is a service worker

A

A Service worker is basically a script (JavaScript file) that runs in the background, separate from a web page and provides features that don’t need a web page or user interaction.

42
Q

What is a Cookie

A

A cookie is a piece of data that is stored on your computer to be accessed by your browser. Cookies are saved as key/value pairs.

43
Q

What are the differences between cookie, local storage and session storage

A

Cookie: Both server-side & client-side. The set-cookie HTTP response header is used by server inorder to send it to user.

44
Q

What is a promise

A

A promise is an object that may produce a single value some time in the future with either a resolved value or a reason that it’s not resolved
(for example, network error). It will be in one of the 3 possible states: fulfilled, rejected, or pending.

Pending
-> fullfill
-> reject

Promises are used to handle asynchronous operations. They provide an alternative approach for callbacks by reducing the callback hell and writing the cleaner code.

45
Q

What are the three states of promise

A

Promises have three states:

Pending: This is an initial state of the Promise before an operation begins

Fulfilled: This state indicates that the specified operation was completed.

Rejected: This state indicates that the operation did not complete. In this case an error value will be thrown.

46
Q

What is a callback function

A

A callback function is a function passed into another function as an argument. This function is invoked inside the outer function to complete an action. Let’s take a simple example of how to use callback function

47
Q

What is promise.all

A

Promise.all is a promise that takes an array of promises as an input (an iterable), and it gets resolved when all the promises get resolved or any one of them gets rejected.