Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

JavaScript

The document provides a comprehensive overview of key JavaScript concepts, including data types, closures, equality operators, promises, hoisting, the 'this' keyword, and the differences between 'null' and 'undefined'. Each concept is defined, accompanied by use case scenarios, benefits, and examples to illustrate their importance in writing efficient and bug-free code. Understanding these concepts is crucial for developers to enhance their coding skills and avoid common pitfalls in JavaScript.

Uploaded by

mddilnawaz7300
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

JavaScript

The document provides a comprehensive overview of key JavaScript concepts, including data types, closures, equality operators, promises, hoisting, the 'this' keyword, and the differences between 'null' and 'undefined'. Each concept is defined, accompanied by use case scenarios, benefits, and examples to illustrate their importance in writing efficient and bug-free code. Understanding these concepts is crucial for developers to enhance their coding skills and avoid common pitfalls in JavaScript.

Uploaded by

mddilnawaz7300
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

🎓

Know where you stand: Masai


self-rating interview preparation
[Javascript]

1. What are the different data types in JavaScript?

Answer

1. Definition: Data types in JavaScript are the classifications of data that determine
the kind of values a variable can hold. JavaScript has two categories of data
types: primitive and non-primitive (also known as reference types).

Know where you stand: Masai self-rating interview preparation [Javascript] 1


2. Use case scenarios: Each data type is suited for representing different kinds of
values in your code. Understanding the various data types helps you choose
the appropriate one for your needs and ensures proper data manipulation and
storage.

3. Benefits: Knowing the different data types in JavaScript enables you to:

Write efficient and accurate code.

Properly store and manipulate data.

Prevent type-related errors and bugs.

4. Extra information: The different data types in JavaScript are:

Primitive data types:

1. Number: Represents numerical values, including integers and floating-


point numbers.

2. String: Represents a sequence of characters, used for storing and


manipulating text.

3. Boolean: Represents a true or false value, often used for conditional


statements and control structures.

4. Undefined: Represents a variable that has been declared but not


assigned a value.

5. Null: Represents an intentional absence of any object value, often used


to indicate that a variable should have no value or reference.

6. BigInt: Represents large integers that cannot be safely represented by


the standard Number data type.

7. Symbol: Represents a unique, immutable identifier used as a key for


object properties.

Non-primitive (reference) data types:

1. Object: A collection of key-value pairs, used to store and organize


complex data structures.

2. Array: A special type of object that represents an ordered collection of


elements, accessible via index.

Know where you stand: Masai self-rating interview preparation [Javascript] 2


3. Function: A reusable block of code that can be invoked with a set of
arguments, and may return a value.

Understanding the different data types in JavaScript allows you to write more
efficient, accurate, and bug-free code by selecting the appropriate data type for
each specific use case.

2. What are closures in JavaScript and why are they


important?

Answer

1. Definition: A closure is the combination of a function bundled together


(enclosed) with references to its surrounding state (the lexical
environment). In other words, a closure gives you access to an outer function's
scope from an inner function even after the outer function has completed
execution. This allows the inner function to continue using the variables and
parameters of the outer function, even if they are no longer in scope.

2. Use case scenarios: Closures are useful in various scenarios, such as:

Know where you stand: Masai self-rating interview preparation [Javascript] 3


Creating private variables that are only accessible within a specific function
scope, providing data encapsulation.

Implementing decorators, which are higher-order functions that can modify


the behavior of other functions.

Creating function factories, which are functions that generate and return
new functions with specific behaviors.

Implementing asynchronous programming patterns, such as callbacks,


where a function needs to access its surrounding scope even after the outer
function has completed execution.

3. Benefits: Closures offer several benefits in JavaScript, including:

Encapsulation: By creating private variables, closures enable data privacy


and help prevent unintended manipulation of data from external code.

Flexibility: Closures provide the ability to create dynamic functions that can
retain state, allowing for more flexible and reusable code.

Improved code organization: Closures help modularize code by enabling


developers to create self-contained functions with their own private state.

4. Extra information: Here's an example of a closure in JavaScript:

function createCounter() {
let count = 0;

return function() {
count++;
console.log(count);
};
}

const counter = createCounter();

counter(); // Output: 1
counter(); // Output: 2

Know where you stand: Masai self-rating interview preparation [Javascript] 4


In this example, the createCounter function returns an inner function that
increments and logs the count variable. The inner function retains access to the
count variable even after createCounter has completed execution. This allows
for the creation of a private variable (in this case, count ) that can't be directly
accessed or manipulated from outside the createCounter function.

Closures are an essential feature of JavaScript, providing data encapsulation,


flexibility, and improved code organization by allowing functions to retain access
to their surrounding scope even after the outer function has completed
execution.

3. Explain the differences between "==" (loose equality)


and "===" (strict equality) operators in JavaScript.

Answer

1. Definition: In JavaScript, there are two types of equality operators used for
comparing values: loose equality (==) and strict equality (===). These

Know where you stand: Masai self-rating interview preparation [Javascript] 5


operators differ in their behavior when comparing values, specifically in how
they handle type conversion during the comparison process.

2. Use case scenarios: Both equality operators are used for comparing values in
various situations, such as in conditional statements or while filtering data.
Understanding the differences between the two operators helps you make
accurate comparisons and prevent potential bugs related to type coercion.

3. Benefits: Knowing the difference between loose and strict equality operators
allows you to:

Write accurate and reliable comparisons in your code.

Avoid unexpected results or bugs related to type coercion.

Make conscious decisions about when to use each operator based on the
desired behavior.

4. Extra information: Here's a detailed explanation of the differences between the


two equality operators:

Loose equality (==): The loose equality operator compares values for
equality, but it performs type coercion if the operands are of different types.
This means that if you compare a number and a string, for example,
JavaScript will try to convert the string to a number before making the
comparison. This can lead to unexpected results in certain cases.
Example:

"5" == 5 // true, because the string "5" is coerced to

Strict equality (===): The strict equality operator compares values for
equality without performing type coercion. If the operands are of different
types, the comparison will return false. This ensures that the comparison is
accurate and reliable, as it doesn't rely on type conversion.

Example:

"5" === 5 // false, because the string "5" and the numb

Know where you stand: Masai self-rating interview preparation [Javascript] 6


Understanding the differences between the loose and strict equality operators in
JavaScript enables you to write accurate and reliable comparisons, avoid
unexpected results, and choose the appropriate operator based on the desired
behavior.

4. What are promises in JavaScript?

Answer

1. Definition: A Promise is a JavaScript object that represents the eventual


completion (or failure) of an asynchronous operation and its resulting value. It
serves as a proxy for a value that may not be available yet, allowing you to write
asynchronous code in a more structured and readable manner.

2. Use case scenarios: Promises are commonly used in situations where you
need to handle asynchronous operations, such as:

Fetching data from a server via an API.

Reading and writing files.

Know where you stand: Masai self-rating interview preparation [Javascript] 7


Performing calculations or processing that takes a significant amount of
time.

Executing multiple asynchronous tasks in parallel or sequentially.

3. Benefits: Promises offer several advantages for handling asynchronous code,


including:

Improved readability and maintainability: Promises allow you to write


asynchronous code in a more structured way, reducing callback nesting
(often referred to as "callback hell").

Error handling: Promises make it easier to handle errors in asynchronous


code by providing a standardized way to catch and propagate errors.

Flexibility: Promises can be chained, allowing you to execute multiple


asynchronous tasks in a specific order or perform additional processing on
resolved values.

4. Extra information: A Promise can be in one of three states:

Pending: The initial state; the Promise is neither fulfilled nor rejected.

Fulfilled: The Promise has successfully completed, and a resulting value is


available.

Rejected: The Promise has failed, and a reason for the failure is available.

Here's an example of creating and using a Promise:

// Creating a Promise
const asyncTask = new Promise((resolve, reject) => {
setTimeout(() => {
const result = Math.random();
if (result > 0.5) {
resolve(result);
} else {
reject("Error: The generated number is less than or equ
}
}, 1000);
});

Know where you stand: Masai self-rating interview preparation [Javascript] 8


// Using the Promise
asyncTask
.then((value) => {
console.log("Success:", value);
})
.catch((error) => {
console.error("Failure:", error);
});

In this example, the asyncTask Promise simulates an asynchronous operation using


setTimeout . If the generated random number is greater than 0.5, the Promise is

fulfilled with the number as its value. Otherwise, it's rejected with an error message.
The then() and catch() methods are used to handle the fulfilled and rejected
states, respectively.
Promises in JavaScript help you manage asynchronous operations more effectively
by providing a standardized way to handle their completion, improve code
readability, and simplify error handling.

5. What is hoisting in JavaScript and how does it affect


variable and function declarations?

Know where you stand: Masai self-rating interview preparation [Javascript] 9


Answer

1. Definition: Hoisting is a JavaScript mechanism in which variable and function


declarations appears to be moved to the top of their containing scope (either
global or function scope) during the compilation phase. This process allows
variables and functions to be used before they are declared in the code.

2. Use case scenarios: Understanding hoisting is essential for debugging issues


related to variable and function declarations, as well as writing clean and
maintainable code. Being aware of hoisting helps prevent potential bugs caused
by using variables before they are initialized or declared.

3. Benefits: Knowing about hoisting in JavaScript enables you to:

Write cleaner and more maintainable code by understanding the order in


which declarations are processed.

Avoid potential issues caused by using variables or functions before they


are declared or initialized.

Debug issues related to variable and function declarations more effectively.

4. Extra information: The hoisting behavior differs between variable declarations,


variable initializations, and function declarations:

Know where you stand: Masai self-rating interview preparation [Javascript] 10


Variable declarations using var : Declarations are hoisted to the top of their
containing scope, but initializations are not. This means that if a variable is
declared and initialized in the same line, only the declaration will be hoisted,
leaving the variable undefined until the initialization is executed.
Example:

console.log(myVar); // Output: undefined


var myVar = 10;
console.log(myVar); // Output: 10

Variable declarations using let and const : Declarations are not hoisted in
the same way as with var . Instead, they are placed in a temporal dead
zone (TDZ) until their declaration is encountered in the code. Accessing the
variable before the declaration will result in a ReferenceError.
Example:

console.log(myLetVar); // Output: ReferenceError


let myLetVar = 20;

Function declarations: Both the declaration and the function body are
hoisted, allowing functions to be called before they are defined in the code.

Example:

console.log(myFunction()); // Output: "Hello, world!"


function myFunction() {
return "Hello, world!";
}

let fun = function() {}

Understanding hoisting in JavaScript helps you write cleaner, more maintainable


code and avoid potential issues related to variable and function declarations. Being
aware of hoisting allows you to prevent bugs caused by using variables or functions
before they are declared or initialized, and debug related issues more effectively.

Know where you stand: Masai self-rating interview preparation [Javascript] 11


6. Can you explain how the "this" keyword works in
JavaScript and how it's context is determined?

Answer

1. Definition: In JavaScript, the this keyword refers to the context in which a


function is called. The value of this depends on the context in which it
appears:

a. Regular functions: Inside a function, the value of this depends on how the
function is called. In most cases, when a function is called as a method of
an object (e.g., obj.f() ), this refers to the object itself (e.g., obj ). The
value of this can also be explicitly set using the call() , apply() , or bind()

methods of the function.

b. Arrow functions: Unlike regular functions, arrow functions don't create their
own this binding. Instead, they inherit the this value from their enclosing
lexical context.

Know where you stand: Masai self-rating interview preparation [Javascript] 12


c. Constructors: When a function is used as a constructor with the new

keyword, this is bound to the new object being created.

d. Class: In classes, the this value differs in static and instance contexts. In
constructors and instance methods, this refers to the instance of the class.
In static methods, this refers to the class itself.

2. Use case scenarios: The this keyword is commonly used in object-oriented


programming, event handling, and constructor functions to refer to the current
object or context. It is essential to understand how this works to avoid bugs
and write clean, maintainable code.

3. Benefits: Understanding how the this keyword works in JavaScript enables


you to:

Access properties and methods of the current object or context.

Write clean, maintainable code with a clear understanding of the current


context.

Avoid potential bugs caused by incorrect this usage.

4. Extra information: The value of this is determined by how a function is called,


not by where it is defined. Here are some common scenarios that determine the
context of this :

Global context: When a function is called in the global context (outside any
object), this refers to the global object (i.e., window in browsers, and
global in Node.js).

Object method: When a function is called as a method of an object, this

refers to the object on which the method is called.

Event handlers: In event handlers, this refers to the element that fired the
event.

Constructor functions: When a function is called with the new keyword,


this refers to the newly created instance of the object.

call(), apply() , and bind() : These methods can be used to explicitly set
the context of this when calling a function.

Know where you stand: Masai self-rating interview preparation [Javascript] 13


Understanding how the this keyword works in JavaScript and how its context is
determined is essential for writing clean, maintainable code and avoiding potential
bugs related to incorrect usage.

7. What is the difference between "null" and


"undefined" in JavaScript?

Answer

1. Definition: In JavaScript, null and undefined are two special values that
indicate the absence of a value or a reference. While both represent a missing
value, they have different meanings and use cases.

2. Use case scenarios: null and undefined are used to represent missing or
uninitialized values in variables, function arguments, or object properties.
Understanding the difference between the two helps prevent potential bugs and
write cleaner code.

3. Benefits: Knowing the difference between null and undefined enables you to:

Write accurate and reliable code by understanding their intended use


cases.

Know where you stand: Masai self-rating interview preparation [Javascript] 14


Debug and handle missing values more effectively.

Make conscious decisions about when to use each value based on the
desired behavior.

4. Extra information: Here's a detailed explanation of the differences between


null and undefined :

null: It is an intentional absence of any object value, usually assigned to a


variable to indicate that it has no value or reference. null is considered an
assignment value and represents a known, empty value.

undefined: It is a default value assigned by JavaScript when a variable is


declared but not initialized, or when accessing a non-existent property of an
object. undefined indicates that a value is unknown or not yet assigned.

Understanding the difference between null and undefined in JavaScript helps you
write accurate and reliable code, debug missing values more effectively, and
choose the appropriate value based on the desired behavior.

8. Describe how event delegation works in JavaScript


and its benefits.

Know where you stand: Masai self-rating interview preparation [Javascript] 15


Answer

1. Definition: Event delegation is a pattern in JavaScript where a single event


listener is attached to a parent element to handle events for its child elements.
Instead of attaching event listeners to each child element individually, the parent
element listens for events and handles them based on the event's target.

2. Use case scenarios: Event delegation is particularly useful when you have
many child elements that require the same event handling or when the child
elements are dynamically added or removed from the DOM. Examples include:

Handling clicks on a large list of items.

Handling events for elements that are added or removed through AJAX or
user interaction.

3. Benefits: Using event delegation provides several advantages, such as:

Improved performance: Attaching a single event listener to the parent


element reduces memory usage and improves performance compared to
attaching individual listeners to each child element.

Dynamic elements handling: Event delegation allows you to handle events


for elements that are added or removed dynamically without the need to
update event listeners.

Simplified code: Event delegation can simplify your code by reducing the
number of event listeners you need to manage.

4. Extra information: Here's an example of how event delegation works:

<ul id="itemList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>

<script>
document.getElementById("itemList").addEventListener("click",
if (event.target.tagName === "LI") {
console.log("Clicked on:", event.target.textContent);

Know where you stand: Masai self-rating interview preparation [Javascript] 16


}
});
</script>

In this example, a single event listener is attached to the <ul> element. When an
<li> element is clicked, the event listener checks if the target is an <li> element

and logs the clicked item's text content.


Understanding event delegation in JavaScript helps improve performance, handle
dynamic elements more effectively, and simplify your code.

9. Explain the concept of prototypal inheritance in


JavaScript.

Answer

1. Definition: Prototypal inheritance is a concept in JavaScript where objects


inherit properties and methods from other objects. In JavaScript, objects can be
linked to other objects forming a prototype chain. When a property or method is

Know where you stand: Masai self-rating interview preparation [Javascript] 17


accessed on an object, JavaScript searches the object's prototype chain until it
finds the requested property or method or reaches the end of the chain.

2. Use case scenarios & real-world examples:

Creating objects with shared behavior: Prototypal inheritance allows you to


create multiple objects that share common properties and methods without
duplicating the code for each object.
Example: Creating multiple instances of a "Car" object, where all instances
share common methods like "startEngine()" or "accelerate()" through their
prototype.

Extending built-in objects: Prototypal inheritance can be used to extend the


functionality of built-in JavaScript objects by adding custom properties or
methods to their prototypes.
Example: Adding a custom method to the Array prototype, like
"Array.prototype.myCustomMethod = function() { ... }".

Implementing object-oriented programming: Prototypal inheritance is the


foundation for implementing object-oriented programming concepts like
classes, objects, and inheritance in JavaScript.
Example: Creating a class hierarchy with a base "Animal" class and derived
"Dog" and "Cat" classes, where the derived classes inherit properties and
methods from the base class.

3. Benefits: Understanding prototypal inheritance in JavaScript enables you to:

Write modular, reusable code by sharing properties and methods across


objects.

Extend built-in objects and create custom functionality.

Implement object-oriented programming concepts like classes and


inheritance.

4. Extra information: In modern JavaScript, the class keyword provides a more


familiar syntax for working with prototypal inheritance. However, it's important to
note that this syntax is syntactic sugar, and the underlying mechanism for
inheritance in JavaScript is still based on prototypes.

By understanding prototypal inheritance in JavaScript and its real-world use cases,


you can write modular, reusable code, extend built-in objects with custom

Know where you stand: Masai self-rating interview preparation [Javascript] 18


functionality, and implement object-oriented programming concepts.

10. What is a callback function and how are they used


in JavaScript?

Answer

1. Definition: A callback function is a function that is passed as an argument to


another function and is executed at a later point in time, typically after the
completion of an asynchronous operation or as a response to an event.
Callback functions are a fundamental concept in JavaScript, allowing you to
create more flexible and modular code by providing a way to handle
asynchronous events and manage control flow.

2. Use case scenarios & real-world examples:

Asynchronous operations: Callback functions are commonly used to handle


the results of asynchronous operations, such as network requests, file I/O,
or timers.
Example: Fetching data from a remote API using XMLHttpRequest or the

Know where you stand: Masai self-rating interview preparation [Javascript] 19


Fetch API, where the callback function processes the fetched data once it's
available.

Event handling: Callback functions can be used as event listeners to


respond to user interactions or other events in the browser environment.
Example: Attaching a click event listener to a button, where the callback
function is executed when the button is clicked.

Higher-order functions: Callback functions can be passed as arguments to


higher-order functions, which are functions that operate on other functions.
Example: Using the Array.prototype.map() method to transform an array,
where the callback function defines the transformation to be applied to each
element.

3. Benefits: Understanding callback functions in JavaScript enables you to:

Handle asynchronous events and manage control flow more effectively.

Create modular, reusable, and composable code.

Implement custom logic in higher-order functions.

4. Extra information: Although callback functions are widely used in JavaScript,


they can sometimes lead to issues like "callback hell" when managing complex
asynchronous control flows. To address these issues, JavaScript now provides
alternatives like Promises and async/await syntax to help you write more
readable and maintainable asynchronous code.

By understanding callback functions in JavaScript and their real-world use cases,


you can handle asynchronous events, create modular and reusable code, and
implement custom logic in higher-order functions.

Explain the output of [] === []

Difference between call , apply and bind

Know where you stand: Masai self-rating interview preparation [Javascript] 20


Difference between let , var and const

What are the states of a Promise in JavaScript?


answer
Definition:
In JavaScript, a Promise can be in one of three states:

1. Pending: The initial state of a Promise. The operation has not completed yet.

2. Fulfilled (or Resolved): The state when the operation completes successfully,
and the Promise has a resolved value.

3. Rejected: The state when the operation fails, and the Promise has a reason for
the failure.

Use case scenarios & WHY we need it:


Understanding the states of a Promise is crucial for managing asynchronous
operations in JavaScript:

Pending: While waiting for a server response or the completion of a time-


consuming task.

Fulfilled: When data has been successfully retrieved or an operation has


completed, and you need to proceed with the result.

Rejected: To handle errors or unsuccessful operations, allowing the


implementation of fallbacks or error messages.

These states allow developers to write code that can handle different outcomes of
asynchronous operations in a predictable manner.
Benefits:

Predictable Asynchronous Handling: Knowing the state of a Promise helps in


writing more robust and error-tolerant code.

Improved Error Handling: Specifically handling rejected Promises ensures


that errors are properly managed.

Know where you stand: Masai self-rating interview preparation [Javascript] 21


Better Flow Control: Understanding these states aids in structuring code for
complex asynchronous workflows.

Extra Information:
In practice, a Promise transitions from the pending state to either the fulfilled or
rejected state. Once a Promise is either fulfilled or rejected, it is considered settled
and will not transition to any other state. This behavior ensures that a Promise
represents an operation that either completes with a result or fails with a reason, but
never both.

Explain Rest Operator


answer
Definition:

Rest Operator: In JavaScript, the rest operator ( ... ) allows a function to


accept an indefinite number of arguments as an array, providing a way to
represent variadic functions in JavaScript. The rest operator collects all
remaining (rest) elements into an array, making it easier to handle variable
numbers of parameters.

Use Cases & Why:

Use Case: Creating functions that accept any number of arguments,


aggregating arguments in array operations, or destructuring arrays and objects.

Why: The rest operator is essential for writing flexible functions that don't have
a fixed number of parameters. It's particularly useful in situations where the
exact number of arguments a function will receive is unknown or varies.

Benefits:

Flexibility in Function Parameters: Enables functions to handle an unknown


number of arguments gracefully.

Cleaner Syntax: Offers a more concise and readable way to handle multiple
parameters, compared to arguments-like objects.

Improved Function Signatures: Makes it clear that a function accepts any


number of arguments, improving code readability and maintainability.

Know where you stand: Masai self-rating interview preparation [Javascript] 22


Example Code & Extra Information:

// Example of Rest Operator in a function


function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}

console.log(sum(1, 2, 3, 4)); // Outputs: 10

// Destructuring with Rest Operator


const [first, second, ...others] = [1, 2, 3, 4, 5];
console.log(first); // Outputs: 1
console.log(second); // Outputs: 2
console.log(others); // Outputs: [3, 4, 5]

Extra Information:

Unlike the arguments object in JavaScript, the rest parameters are real arrays,
which means that methods like sort , map , forEach , or pop can be applied
directly.

An analogy for the rest operator: Consider it like a flexible container bag.
Regardless of the number of items you have (arguments in a function), the bag
(the rest operator) can adjust to hold them all, allowing you to manage them as
a single unit (array).

Explain scope chaining in javascript


answer
Definition:

Scope Chaining in JavaScript: Scope chaining refers to the way in which


scopes (areas where variables are defined) are linked together in a hierarchy. In
JavaScript, when a variable is used, the JavaScript engine looks up the variable
in the current scope. If it's not found, the engine looks in the outer scope, and
this process continues up the scope chain until the variable is found or the

Know where you stand: Masai self-rating interview preparation [Javascript] 23


global scope is reached. This mechanism allows for the accessibility of
variables defined in an outer scope by inner scopes.

Use Cases & Why:

Use Case: Accessing variables from an outer scope within an inner scope, like
in nested functions or blocks.

Why: Scope chaining provides a logical structure for variable access and
encapsulation. It allows for writing more organized and maintainable code,
where functions and blocks can use and share variables defined in their outer
scopes.

Benefits:

Encapsulation and Organization: Helps in structuring code in a way that


variables are only accessible within their relevant scopes, enhancing
encapsulation.

Code Reusability: Allows inner functions to access and reuse variables from
their outer functions, promoting DRY (Don't Repeat Yourself) principles.

Memory Efficiency: Variables are kept alive only as long as their scope is
active, which can lead to more efficient memory usage.

Example Code & Extra Information:

let globalVar = "Global";

function outerFunction() {
let outerVar = "Outer";

function innerFunction() {
let innerVar = "Inner";
console.log(innerVar); // Accesses innerVar
console.log(outerVar); // Accesses outerVar from the oute
console.log(globalVar); // Accesses globalVar from the gl
}

innerFunction();

Know where you stand: Masai self-rating interview preparation [Javascript] 24


}

outerFunction();

Extra Information:

In the context of scope chaining, there's a distinction between lexical scope


(static structure of scopes) and dynamic scope (context of function calls).
JavaScript uses lexical scoping, meaning the scope chain is defined by the
physical structure of the program code.

A useful analogy for scope chaining is a multilevel building: You can see and
use things on your level and any levels above you (outer scopes), but you can't
access things on lower levels (inner scopes).

Difference between splice() and slice() array methods


Answer

Definition:

splice(): The splice() method in JavaScript is used to change the contents of


an array by removing or replacing existing elements and/or adding new
elements in place. It modifies the original array and returns an array containing
the deleted elements.

slice(): The slice() method, on the other hand, returns a shallow copy of a
portion of an array into a new array object without modifying the original array. It
selects elements based on the start and end index arguments.

Use Cases & Why:

splice():

Use case: Removing items from an array, inserting new items, or replacing
items in an array.

Why: Useful when you need to manipulate or alter the original array, such
as dynamically adjusting the contents of an array based on certain
conditions.

slice():

Know where you stand: Masai self-rating interview preparation [Javascript] 25


Use case: Creating a new array from a subset of an existing array.

Why: Ideal when you need a copy of a portion of an array without altering
the original array, preserving data integrity.

Benefits:

splice():

Flexibility: It can perform insertion, deletion, and replacement in one


method.

In-place Operation: Directly modifies the original array, which can be more
efficient in terms of memory usage in some cases.

slice():

Data Integrity: Does not modify the original array, ensuring that the original
data remains unchanged.

Simplicity: Straightforward for extracting portions of an array.

Example Code & Extra Information:

let array = [1, 2, 3, 4, 5];

// Using splice()
array.splice(2, 1, 'a', 'b'); // Removes 1 element at index 2
console.log(array); // Outputs: [1, 2, 'a', 'b', 4, 5]

// Using slice()
let newArray = array.slice(1, 3); // Copies elements from ind
console.log(newArray); // Outputs: [2, 'a']
console.log(array); // Original array remains unchanged: [1,

Extra Information:

It's important to remember that splice() modifies the original array and can be
used for various array manipulations, whereas slice() is primarily used for
extracting a portion of an array without altering the original array.

Know where you stand: Masai self-rating interview preparation [Javascript] 26


An analogy for these methods: If an array is a deck of cards, splice() is like
taking out some cards, possibly putting in new ones, and altering the deck. In
contrast, slice() is like creating a new stack from selected cards without
disturbing the original deck.

Difference between JS ES6 arrow functions vs ES5


regular functions
Answer
Definition:

ES6 Functions: With ECMAScript 6 (ES6), introduced in 2015, JavaScript


functions saw significant enhancements, including arrow functions, default
parameters, rest parameters, and more concise syntax.

ES5 Functions: ECMAScript 5 (ES5), the older standard, uses traditional


function syntax and lacks many of the features that ES6 introduced. Functions
in ES5 are more verbose and lack some of the capabilities that make ES6
functions more powerful and expressive.

Use Cases & Why:

ES6 Functions:

Use case: Writing concise and more readable code, managing this context
more easily with arrow functions, handling variable numbers of arguments
with rest parameters, and setting default parameters.

Why: ES6 functions enhance code readability and maintainability, provide


more robust ways to handle parameters and this context, and simplify
function expressions.

ES5 Functions:

Use case: Compatibility with older JavaScript environments where ES6


features are not supported.

Why: Prior to the widespread adoption of ES6, ES5 was the standard for
JavaScript and is still used in environments that have not yet adopted ES6.

Benefits:

Know where you stand: Masai self-rating interview preparation [Javascript] 27


ES6 Functions:

Improved Readability and Conciseness: Arrow functions and other ES6


features make the code more concise and easier to read.

Enhanced Functionality: Features like default parameters, rest parameters,


and arrow functions make functions more flexible and powerful.

Better Handling of this Context: Arrow functions do not have their own
this context, reducing common errors with this binding.

ES5 Functions:

Wide Compatibility: Fully supported in all JavaScript engines and browsers,


ensuring maximum compatibility.

Familiarity: Well understood by most developers, as it has been the


standard for a longer time.

Example Code & Extra Information:

// ES6 Function Examples


// Arrow function
const add = (a, b) => a + b;

// Default parameters
function greet(name = 'Guest') {
console.log('Hello ' + name);
}

// ES5 Function Example


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

// Handling 'this' context in ES5


var that = this;
someFunction(function() {
console.log(that.value);
});

Know where you stand: Masai self-rating interview preparation [Javascript] 28


// In ES6, 'this' is lexically scoped in arrow functions
someFunction(() => {
console.log(this.value);
});

Extra Information:

ES6 functions are part of the evolution of JavaScript, making the language
more powerful and expressive. They are generally preferred in modern
JavaScript development, but understanding ES5 syntax remains important for
maintaining legacy code and understanding the foundations of JavaScript.

Pass by value & pass by reference in context of


javascript
Answer
Definition:

Pass by Value: In JavaScript, when you pass a variable of a primitive data type
(like number, string, boolean) to a function, a copy of the value is passed. This
means any modification to the variable within the function does not affect the
original value.

Pass by Reference: JavaScript uses pass by reference for non-primitive data


types (like objects and arrays). When a variable referring to an object or an
array is passed to a function, a reference to the original object is passed.
Therefore, changes to the object inside the function affect the original object.

Use Cases & Why:

Pass by Value:

Use case: When working with primitive types like numbers, strings, or
booleans.

Why: This ensures that the original value of the variable cannot be altered
by the function, maintaining data integrity and avoiding side effects.

Pass by Reference:

Know where you stand: Masai self-rating interview preparation [Javascript] 29


Use case: When working with objects and arrays.

Why: This is efficient in terms of memory usage as it avoids copying the


whole object or array. It also allows functions to modify the original object or
array, which can be useful in many programming scenarios.

Benefits:

Pass by Value:

Data Integrity: Ensures the original data is not unintentionally modified.

Simplicity: Easier to understand and predict since variables are


independent of each other.

Pass by Reference:

Memory Efficiency: More memory efficient as it doesn't create a copy of the


object for each function call.

Flexibility: Allows functions to directly modify the object or array, enabling


more complex data manipulations.

Example Code & Extra Information:

// Pass by Value
function changeValue(num) {
num = 5;
}
let a = 1;
changeValue(a);
console.log(a); // Outputs: 1, the original value remains unc

// Pass by Reference
function changeObject(obj) {
obj.key = 'new value';
}
let myObj = { key: 'original value' };
changeObject(myObj);
console.log(myObj); // Outputs: { key: 'new value' }, the obj

Know where you stand: Masai self-rating interview preparation [Javascript] 30


Extra Information:

In JavaScript, even though it's said to be "pass by reference" for objects, it's
technically passing by value of the reference. The function receives a reference
to the object, but this reference itself is passed by value. This means if you
reassign the whole object inside the function, the original object is not replaced,
but modifying the object's properties will reflect in the original object.

Difference between higher order function and callback


function
Answer
Definition:

Higher-Order Function:

A higher-order function in JavaScript is a function that either takes one or


more functions as arguments (parameters), or returns a function as its
result. This concept is a core part of functional programming in JavaScript
and allows for abstraction over actions, not just values.

Callback Function:

A callback function is a function that is passed into another function as an


argument and is expected to be executed at some point within that function.
It is a way to ensure certain code doesn’t execute until other code has
already finished execution (asynchronous behavior).

Use Cases & Why:

Higher-Order Function:

Use case: Creating utility functions that can accept various functions to
perform different tasks (like map , filter , reduce in arrays), or functions that
need to create or modify other functions (like function composition or
currying).

Why: They are fundamental in JavaScript for creating reusable and


abstracted code, allowing operations to be performed on other functions.

Know where you stand: Masai self-rating interview preparation [Javascript] 31


Callback Function:

Use case: Handling asynchronous operations like HTTP requests, events,


or any scenario where you need to wait for a task to complete before
running the callback.

Why: Callbacks are essential in JavaScript’s asynchronous programming


model, allowing for non-blocking code execution.

Benefits:

Higher-Order Function:

Code Reusability: Can create highly reusable and modular code.

Abstraction: Helps in abstracting or isolating actions, which enhances code


readability and maintainability.

Callback Function:

Asynchronous Execution: Enables efficient handling of asynchronous


operations.

Control Flow Management: Allows for more control over the execution order
of functions.

Example Code & Extra Information:

// Higher-Order Function Example


function higherOrderFunction(callback) {
// 'callback' is a callback function
const result = callback();
console.log(result);
}

function simpleFunction() {
return "Hello from simpleFunction!";
}

// Using a higher-order function by passing a callback


higherOrderFunction(simpleFunction);

Know where you stand: Masai self-rating interview preparation [Javascript] 32


// Callback Function in an Asynchronous Operation
setTimeout(() => {
console.log("This is a callback function called after 2 sec
}, 2000);

Extra Information:

It's important to note that while all callbacks can be considered functions, not all
functions are callbacks. Similarly, not all functions are higher-order functions;
only those that take functions as arguments or return functions. Higher-order
functions and callbacks are central to functional programming in JavaScript,
providing a way to write more abstract, flexible, and maintainable code.

Know where you stand: Masai self-rating interview preparation [Javascript] 33

You might also like