Questions I Flashcards
Which JS array methods change the original array?
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.
What is the easiest way to convert an array to an object?
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”}
What is the difference between var, let and const?
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.
What is a Temporal Dead Zone?
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
What are the ways to create object in JavaScript?
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
- Object.create()
- JSON Parsing**
How do you copy properties from one object to other?
-
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. -
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. - 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. -
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. - 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. -
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.
What do you understand by “this” keyword in JavaScript?
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.
What is currying?
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
What is the difference between regular functions and arrow functions?
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.
What is the difference between “==” and “===” operators?
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.
Explain Implicit Type Coercion in JavaScript
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)
What are the various statements in error handling?
- 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. - 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. - 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. - 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. - 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.
What are the various statements in error handling- key differences
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.
What is the purpose of Error object?
-> 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.
What are the 3 states of promise?
A Promise in JavaScript represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises have three distinct states:
- Pending
Definition: The initial state of a Promise. It indicates that the asynchronous operation has not yet completed; the outcome is still unknown. - 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. - 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.
What is an async function?
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.
What is a prototype? What is the difference between __proto__ and prototype?
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.
Prototype vs __proto__
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.