JavaScript - Intermediate Flashcards
function declaration
In JavaScript, a function declaration is a statement that defines a named function.
It consists of the function keyword, followed by the function name, a list of parameters, and the function body enclosed in curly braces.
Function declarations are hoisted, meaning they can be called before they are defined in the code.
for example:
function add(a, b) {
return a + b;
}
function expression
involves assigning a function to a variable or a constant.
It can be either anonymous or named.
Function expressions are not hoisted and must be defined before they are called.
For example:
// Function Expression (anonymous)
const multiply = function(a, b) {
return a * b;
};
// Function Expression (named)
const divide = function divide(a, b) {
return a / b;
};
Explain the concept of scope and how it works in JavaScript?
Scope in JavaScript defines the visibility and accessibility of variables, functions, and objects in some particular part of the code during runtime.
What are the different types of scope in JavaScript?
Function Scope
Global Scope
Local Scope
Block Scope
Lexical Scope
Function Scope
Each function creates its own scope.
Global Scope
Variables declared outside of any function are considered global and can be accessed from anywhere in the code.
Local Scope
Variables declared within a function are considered local and can only be accessed within that function.
What is the scope chain?
JavaScript follows a hierarchical structure called the scope chain.
When a variable is accessed, the JavaScript engine searches for the variable in the current scope.
If it doesn’t find the variable, it moves up the scope chain until it either finds the variable or reaches the global scope.
Block Scope
ES6 introduced block scope with the let and const keywords, allowing variables to be scoped to a specific block of code, such as within loops or conditional statements.
How does the “this” keyword behave in arrow functions compared to regular functions?
In arrow functions, the value of this is lexically scoped.
In other words, the this value in an arrow function is based on the surrounding scope where the arrow function is defined, rather than how it is called.
Arrow functions do not have their own this value.
Lexical Scope
retains the value of the enclosing context
When is it good to use arrow functions?
Arrow functions are especially useful when dealing with callbacks or when you need to preserve the value of this from the enclosing scope.
What are the different methods available for iterating over an object’s properties?
For … in
Object.keys()
Object.values()
Object.entries()
For … in
It iterates over all enumerable properties of an object, including inherited ones.
for (let key in object) {
if (object.hasOwnProperty(key)) {
console.log(key, object[key]);
}
}
Object.keys()
t returns an array containing the enumerable properties of an object.
const keys = Object.keys(object);
keys.forEach(key => {
console.log(key, object[key]);
});
Object.values()
It returns an array containing the values of enumerable properties of an object.
const values = Object.values(object);
values.forEach(value => {
console.log(value);
});
Object.entries()
It returns an array containing the enumerable properties of an object as [key, value] pairs.
const entries = Object.entries(object);
entries.forEach(([key, value]) => {
console.log(key, value);
});
Explain the concept of the event loop in JavaScript and how it enables asynchronous behavior.
The event loop is a mechanism in JavaScript that allows the runtime environment to handle multiple events and tasks asynchronously.
It enables non-blocking behavior, preventing long-running operations from blocking the execution of other code.
What are the implications of the single threaded nature of JavaScript when it comes to handling asynchronous operations such as AJAX calls?
When an asynchronous operation is initiated, it is offloaded to the browser’s APIs or other external mechanisms.
How does the event loop work?
The event loop continuously checks the call stack (the place where function calls are tracked) and the task queue (a queue of asynchronous tasks) for any pending tasks.
When the call stack is empty, the event loop picks the next task from the queue and pushes it onto the call stack, allowing it to be executed.
This process of checking the call stack, handling tasks, and pushing them onto the call stack is repeated indefinitely, allowing JavaScript to process multiple tasks and maintain responsive behavior.
What’s the difference in error handling between Promises and async/await?
Promises use .catch()
asyncFunction()
.then(result => {
// Handle success
})
.catch(error => {
// Handle error
});
async/await wraps the awaiting function in a try and handles errors in the catch
try {
const result = await asyncFunction();
// Handle success
} catch (error) {
// Handle error
}
What are async/await and how do they simplify working with asynchronous code in JavaScript?
Async/await is a syntax introduced in ES2017 (ES8) that simplifies asynchronous programming in JavaScript.
It is built on top of promises and provides a more synchronous-like way to write and handle asynchronous code
Async/await allows you to write asynchronous code in a more sequential and readable manner, similar to synchronous code.
It avoids the need for explicit promise chaining using .then() and provides a natural error-handling mechanism using try…catch.
for example:
async function fetchData() {
try {
const response = await fetch(‘https://api.example.com/data’);
const data = await response.json();
return data;
} catch (error) {
console.log(‘Error:’, error);
}
}
fetchData();
What does the await keyword do?
The await keyword waits for the promises to resolve before moving to the next line, resulting in cleaner and more understandable code for handling asynchronous operations.
What are the different ways to copy an array or object in JavaScript?
Shallow copy with spread operator (…)
Shallow copy with Object.assign()
Deep copy with JSON.parse() and JSON.stringify()
Shallow copy with spread operator (…)
This method creates a new array or object and copies the enumerable properties or elements from the source to the new one.
It performs a shallow copy, meaning nested objects or arrays are still referenced.
const newArray = […oldArray];
const newObject = { …oldObject };
Shallow copy with Object.assign()
Similar to the spread operator, Object.assign() creates a new object or array and copies the enumerable properties or elements from the source.
It also performs a shallow copy.
const newArray = Object.assign([], oldArray);
const newObject = Object.assign({}, oldObject);
Deep copy with JSON.parse() and JSON.stringify()
This method converts the array or object to a JSON string and then parses it back into a new array or object.
It creates a deep copy, meaning all nested objects or arrays are also copied.
const newArray = JSON.parse(JSON.stringify(oldArray));
const newObject = JSON.parse(JSON.stringify(oldObject));