JavaScript Flashcards

1
Q

What is a callback function?

A
  1. Define the Concept Clearly

“A callback is a function that is passed as an argument to another function and is executed after that function has finished its execution or when a specific event occurs. Callbacks are commonly used in asynchronous programming to handle tasks that take time, such as API calls, file operations, or timers.”

  1. Provide Context or Use Case

“Callbacks are essential when dealing with asynchronous tasks, as they allow us to specify what should happen after an operation completes without blocking the rest of the program. For example, when making an API call, a callback function is used to process the response, whether it’s a success or an error.”

  1. Give a Clear Example

JavaScript Example:

```jsx
javascript
CopyEdit
function fetchData(callback) {
setTimeout(() => {
const data = { id: 1, name: “John Doe” }; // Simulating API response
callback(null, data); // Calling the callback with data
}, 1000);
}

function handleResponse(error, data) {
if (error) {
console.error(“Error fetching data:”, error);
} else {
console.log(“Data received:”, data);
}
}

// Call fetchData with handleResponse as the callback
fetchData(handleResponse);

~~~

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

What is a promise?

A

A Promise is an object representing the eventual completion or failure of an asynchronous operation. It has three states: pending, fulfilled, or rejected, and allows chaining with .then() and error handling with .catch().

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

What an observable?

A

An Observable is a data stream that emits values over time, allowing subscribers to react to new data, errors, or completion events. It is commonly used in reactive programming and is a core concept in libraries like RxJS.

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