Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
11 views7 pages

Lecture 4 - JS Additional Features

The document covers various JavaScript features including ES6 syntax, asynchronous programming with Promises, and the use of async/await. It includes multiple choice questions, state questions, code output questions, error finding, and code completion tasks related to these topics. Key concepts such as rest parameters, arrow functions, destructuring, and the spread operator are also explained with examples.

Uploaded by

moarcarc
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)
11 views7 pages

Lecture 4 - JS Additional Features

The document covers various JavaScript features including ES6 syntax, asynchronous programming with Promises, and the use of async/await. It includes multiple choice questions, state questions, code output questions, error finding, and code completion tasks related to these topics. Key concepts such as rest parameters, arrow functions, destructuring, and the spread operator are also explained with examples.

Uploaded by

moarcarc
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/ 7

Lecture 4 - JS Additional Features

Multiple Choice Questions


1. Which ES6 feature allows for variable function parameters? a) Arrow functions b)
Rest parameters c) Spread operator d) Destructuring

Answer: b) Rest parameters - Rest parameters allow a function to accept an indefinite


number of arguments as an array, using the syntax function foo(...args) .

1. Which of the following correctly defines an arrow function in JavaScript? a)


function(a, b) => { return a + b; } b) (a, b) -> { return a + b; } c) (a, b) => { return a + b; }
d) function => (a, b) { return a + b; }

Answer: c) (a, b) => { return a + b; } - This is the correct syntax for an arrow function in
JavaScript.

1. What is the primary purpose of JavaScript Promises? a) To make code execution


faster b) To handle asynchronous operations c) To reduce memory usage d) To
encrypt data transmission

Answer: b) To handle asynchronous operations - Promises provide a cleaner way to


handle asynchronous operations and avoid callback hell.

1. Which method is called when a Promise is successfully fulfilled? a) .then()


b) .catch() c) .finally() d) .resolve()

Answer: a) .then() - The .then() method is called when a Promise is fulfilled successfully.

1. What is the output of console.log(typeof (() => {})) in JavaScript? a) "arrow" b)


"function" c) "object" d) "undefined"

Answer: b) "function" - Arrow functions are still functions, so typeof returns "function".

State Questions
1. State the difference between synchronous and asynchronous code execution in
JavaScript.

Answer: In synchronous execution, code is executed line by line, and each operation
must complete before the next one begins. The program "blocks" or waits for operations
to complete. In asynchronous execution, operations can be initiated and the program
continues to run without waiting for them to complete. When the asynchronous
operation finishes, a callback function, promise, or async/await is used to handle the
result. This allows JavaScript to perform time-consuming operations without blocking
the main thread.

1. State what a JavaScript Promise represents and its possible states.

Answer: A Promise in JavaScript represents the eventual completion (or failure) of an


asynchronous operation and its resulting value. A Promise can be in one of three states: -
Pending: Initial state, neither fulfilled nor rejected - Fulfilled: The operation completed
successfully, and the promise has a resulting value - Rejected: The operation failed, and
the promise has a reason for the failure Once a promise is either fulfilled or rejected, it is
considered settled and cannot change to another state.

1. State the purpose of the async/await syntax in JavaScript.

Answer: The async/await syntax provides a more readable and cleaner way to work with
asynchronous code in JavaScript. It allows asynchronous code to be written in a way
that looks and behaves more like synchronous code, making it easier to understand and
maintain. The async keyword declares that a function returns a Promise, and the await
keyword pauses the execution of the function until the Promise is resolved, allowing the
result to be assigned to a variable without explicit Promise handling.

1. State what destructuring assignment is and provide a simple example.

Answer: Destructuring assignment is a JavaScript syntax that allows you to extract


values from arrays or properties from objects and assign them to variables in a more
concise way.

Example with an array: javascript const [first, second] = [1, 2]; // first = 1, second = 2

Example with an object: javascript const { name, age } = { name: 'John', age: 30 }; // name =
'John', age = 30

1. State the difference between a regular function and an arrow function regarding
the 'this' keyword.

Answer: In regular functions, the this keyword is dynamically scoped and depends on
how the function is called. It can refer to different objects depending on the context of
invocation (e.g., method call, constructor, event handler).

In arrow functions, the this keyword is lexically scoped, meaning it inherits the this
value from the enclosing scope where the arrow function is defined. Arrow functions do
not have their own this context, which makes them unsuitable for methods in objects or
constructors, but ideal for callbacks where you want to preserve the surrounding this
context.

Code Output Questions


1. What is the output of the following code?

const promise = new Promise((resolve, reject) => {


resolve("Success!");
});
promise.then(value => console.log(value));

Answer: "Success!" - The Promise is immediately resolved with the value "Success!", and
the .then() handler logs this value.

1. What is the output of the following code?

const [a, b, ...rest] = [1, 2, 3, 4, 5];


console.log(rest);

Answer: [3, 4, 5] - The rest parameter collects all remaining elements after the first two
into a new array.

1. What is the output of the following code?

const person = { name: 'John', age: 30 };


const { name, job = 'Unknown' } = person;
console.log(job);

Answer: "Unknown" - When destructuring, you can provide default values for properties
that don't exist in the source object. Since job doesn't exist in the person object, it takes
the default value "Unknown".

1. What is the output of the following code?

async function test() {


return "Hello";
}
console.log(test());
Answer: Promise {<fulfilled>: "Hello"} - An async function always returns a Promise. The
console.log shows the Promise object itself, not its resolved value. To get the actual
value, you would need to use .then() or await.

1. What is the output of the following code?

const numbers = [1, 2, 3];


const newNumbers = [...numbers, 4, 5];
console.log(newNumbers);

Answer: [1, 2, 3, 4, 5] - The spread operator (...) expands the numbers array into
individual elements, which are then combined with 4 and 5 to form a new array.

Find Errors Questions


1. Find and fix the error in the following code:

const getData = async () => {


const response = await fetch('https://api.example.com/data');
const data = response.json();
console.log(data);
}

Answer: The response.json() method returns a Promise, so it needs to be awaited.


Corrected code: javascript const getData = async () => { const response = await fetch('https://
api.example.com/data'); const data = await response.json(); console.log(data); }

1. Find and fix the error in the following code:

let promise = new Promise((resolve, reject) => {


throw new Error("Something went wrong");
});
promise.then(result => console.log(result));

Answer: The code throws an error in the Promise constructor but doesn't handle it. You
need to add a .catch() handler. Corrected code: javascript let promise = new
Promise((resolve, reject) => { throw new Error("Something went wrong"); }); promise .then(result
=> console.log(result)) .catch(error => console.error(error));

1. Find and fix the error in the following code:


const multiply = (a, b) => a * b;
const result = multiply.call(null, 2, 3, 4);
console.log(result); // Expected output: 6

Answer: Arrow functions don't have their own this binding, so using .call() doesn't
affect how they handle parameters. The function only uses the first two arguments. The
third argument (4) is ignored. This isn't technically an error, but if you want to multiply
all three numbers, you need to modify the function. Corrected code: javascript const
multiply = (...args) => args.reduce((acc, val) => acc * val, 1); const result = multiply(2, 3, 4);
console.log(result); // Output: 24

1. Find and fix the error in the following code:

const person = { name: 'John' };


const { name, age } = person;
console.log(age.toString());

Answer: The age property doesn't exist in the person object, so it's undefined. Calling
toString() on undefined causes an error. Corrected code: javascript const person = { name:
'John' }; const { name, age } = person; console.log(age ? age.toString() : 'Age not specified');

1. Find and fix the error in the following code:

async function fetchData() {


try {
const response = await fetch('https://api.example.com/data');
return response.json();
} catch (error) {
console.log(error);
}
}
fetchData().then(console.log('Data fetched successfully'));

Answer: The .then() method expects a function as an argument, but here it's receiving
the result of console.log(), which is undefined. Also, response.json() returns a Promise
that should be awaited. Corrected code: javascript async function fetchData() { try { const
response = await fetch('https://api.example.com/data'); return await response.json(); } catch
(error) { console.log(error); } } fetchData().then(data => console.log('Data fetched successfully:',
data));
Write/Complete Code Questions
1. Write an async function that fetches data from a URL and returns the parsed JSON
response.

Answer: ```javascript async function fetchData(url) { try { const response = await


fetch(url);

if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}

const data = await response.json();


return data;
} catch (error) {
console.error('Error fetching data:', error);
throw error; // Re-throw to allow calling code to handle it
}

// Example usage: // fetchData('https://api.example.com/data') // .then(data =>


console.log(data)) // .catch(error => console.error('Failed to fetch data:', error)); ```

1. Complete the following function to create a Promise that resolves after a specified
delay:

function delay(ms) {
// Your code here
}

Answer: ```javascript function delay(ms) { return new Promise(resolve =>


{ setTimeout(resolve, ms); }); }

// Example usage: // async function example() { // console.log('Starting'); // await


delay(2000); // Wait for 2 seconds // console.log('After 2 seconds'); // } ```

1. Write JavaScript code that uses destructuring to swap the values of two variables.

Answer: ```javascript let a = 5; let b = 10;

// Swap values using destructuring [a, b] = [b, a];


console.log(a); // 10 console.log(b); // 5 ```

1. Complete the following code to handle both successful and failed Promise
outcomes:

fetch('https://api.example.com/data')
// Your code here to handle the response and any errors

Answer: javascript fetch('https://api.example.com/data') .then(response => { if (!response.ok)


{ throw new Error(`HTTP error! Status: ${response.status}`); } return response.json(); }) .then(data
=> { console.log('Data received:', data); // Process the data here }) .catch(error =>
{ console.error('Error fetching data:', error); // Handle the error appropriately }) .finally(() =>
{ console.log('Fetch operation completed'); // Clean up code that should run regardless of success
or failure });

1. Write JavaScript code that uses the spread operator to merge two objects into a
new object.

Answer: ```javascript const object1 = { a: 1, b: 2 }; const object2 = { b: 3, c: 4 };

// Merge objects using spread operator const mergedObject = { ...object1, ...object2 };

console.log(mergedObject); // { a: 1, b: 3, c: 4 }

// Note: Properties from object2 override those from object1 if they have the same key
```

You might also like