MCQs Of Day 17: Working with APIs in JavaScript

Rashmi Mishra
0

  MCQs Of Day 17: Working with APIs in JavaScript

MCQs on Working with APIs in JavaScript


1.  What is the purpose of the fetch() method in JavaScript?

a) To make a GET request only
b) To send asynchronous HTTP requests
c) To handle cookies
d) To parse JSON data

Answer: b) To send asynchronous HTTP requests
Explanation: The fetch() method is used to send HTTP requests (like GET, POST, PUT) and handles the responses asynchronously.


2.  Which method is used to parse the response data as JSON?

a) .text()
b) .json()
c) .html()
d) .data()

Answer: b) .json()
Explanation: The .json() method is used to parse the response body as JSON, which can then be used in the application.


3.  What HTTP method is used to retrieve data from a server?

a) POST
b) GET
c) PUT
d) DELETE

Answer: b) GET
Explanation: The GET method is used to retrieve data from the server.


4.  Which of the following is used to send data to a server in the request body?

a) GET
b) POST
c) PUT
d) DELETE

Answer: b) POST
Explanation: The POST method is used to send data to the server in the request body.


5.  Which JavaScript method is used to handle the response after a fetch request?

a) .then()
b) .catch()
c) .finally()
d) .response()

Answer: a) .then()
Explanation: The .then() method is used to handle the successful response after making a fetch request.


6.  What is returned by the fetch() function?

a) A promise
b) A callback function
c) An array
d) An object

Answer: a) A promise
Explanation: The fetch() function returns a promise that resolves to the response object representing the completion of the request.


7.  What is the use of the catch() method in a fetch API request?

a) To log the response
b) To handle promise rejection or errors
c) To handle a successful response
d) To parse the response data

Answer: b) To handle promise rejection or errors
Explanation: The catch() method is used to catch any errors that occur during the fetch operation, such as network errors or issues with parsing the response.


8.  Which of the following is a correct way to send a JSON payload with a POST request using fetch()?

a) fetch(url, { body: 'data' })
b) fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) })
c) fetch(url, { method: 'GET', body: data })
d) fetch(url, { method: 'POST', body: 'data' })

Answer: b) fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) })
Explanation: The correct way to send a JSON payload with a POST request involves setting the Content-Type header to application/json and stringifying the data with JSON.stringify().


9.  How can you retrieve a response as plain text using fetch()?

a) .text()
b) .json()
c) .xml()
d) .html()

Answer: a) .text()
Explanation: The .text() method is used to retrieve the response body as a string.


10.        Which HTTP status code indicates that a request was successful?

a) 200
b) 400
c) 404
d) 500

Answer: a) 200
Explanation: The HTTP status code 200 indicates a successful request and response.


11.        What is the purpose of async and await in JavaScript?

a) To handle callback functions
b) To perform asynchronous operations without blocking the code
c) To handle synchronous functions
d) To parse JSON data

Answer: b) To perform asynchronous operations without blocking the code
Explanation: async and await allow you to write asynchronous code in a synchronous-like manner, making it easier to read and maintain.


12.        What will the following code output?

javascript

Copy code

fetch('https://jsonplaceholder.typicode.com/posts/1')

  .then(response => response.json())

  .then(data => console.log(data));

a) The raw JSON data
b) An object with the data
c) A promise
d) Undefined

Answer: b) An object with the data
Explanation: The .json() method parses the response into a JavaScript object, which is then logged to the console.


13.        Which HTTP method is used to update data on a server?

a) GET
b) POST
c) PUT
d) PATCH

Answer: c) PUT
Explanation: The PUT method is used to update an existing resource on the server.


14.        What does the localStorage object do in JavaScript?

a) Stores data in memory
b) Stores data on the server
c) Stores data locally in the browser with no expiration time
d) Stores cookies

Answer: c) Stores data locally in the browser with no expiration time
Explanation: localStorage allows you to store data in the browser that persists even after the page is closed or the browser is restarted.


15.        How do you check if a key exists in localStorage?

a) localStorage.has(key)
b) localStorage.exists(key)
c) localStorage.getItem(key) !== null
d) localStorage.contains(key)

Answer: c) localStorage.getItem(key) !== null
Explanation: To check if a key exists in localStorage, you use getItem(). If the key exists, it will return the value, otherwise null.


16.        Which method is used to remove an item from localStorage?

a) removeItem()
b) delete()
c) clear()
d) unset()

Answer: a) removeItem()
Explanation: removeItem() is used to remove a specific item from localStorage.


17.        What does the sessionStorage object do?

a) Stores data permanently in the browser
b) Stores data on the server
c) Stores data for the duration of the page session
d) Stores cookies for each session

Answer: c) Stores data for the duration of the page session
Explanation: sessionStorage stores data that is available for the duration of the page session. Once the browser is closed, the data is lost.


18.        How do you store a JSON object in localStorage?

a) localStorage.setItem('key', object)
b) localStorage.setItem('key', JSON.stringify(object))
c) localStorage.addItem('key', object)
d) localStorage.store('key', object)

Answer: b) localStorage.setItem('key', JSON.stringify(object))
Explanation: You need to convert a JavaScript object into a string using JSON.stringify() before storing it in localStorage.


19.        How do you parse a string from localStorage back into a JavaScript object?

a) JSON.parse(localStorage.getItem('key'))
b) parse(localStorage.getItem('key'))
c) localStorage.parse('key')
d) JSON.decode(localStorage.getItem('key'))

Answer: a) JSON.parse(localStorage.getItem('key'))
Explanation: JSON.parse() is used to convert a string from localStorage back into a JavaScript object.


20.        Which method is used to remove all items from localStorage?

a) clear()
b) removeAll()
c) clearAll()
d) deleteAll()

Answer: a) clear()
Explanation: clear() removes all items stored in localStorage for the current domain.

21.        What is the return value of the fetch() method?

a) A Promise
b) A JSON object
c) A string
d) An array

Answer: a) A Promise
Explanation: The fetch() method returns a promise, which resolves to the response of the request.


22.        Which of the following is the correct way to check for a successful fetch request in JavaScript?

a) if (response.status === 200)
b) if (response.ok)
c) if (response === 'success')
d) if (response.status === 404)

Answer: b) if (response.ok)
Explanation: The response.ok property returns true if the HTTP status code is in the range 200-299, indicating a successful request.


23.        What is the purpose of using JSON.stringify() when working with APIs?

a) To encode data into URL-safe format
b) To convert an object into a JSON string
c) To parse a JSON string into an object
d) To send binary data

Answer: b) To convert an object into a JSON string
Explanation: JSON.stringify() is used to convert a JavaScript object into a JSON string, which can be sent in the body of a POST request.


24.        How can you handle errors that occur during a fetch request?

a) Using .catch()
b) Using .then()
c) Using .finally()
d) Using if condition

Answer: a) Using .catch()
Explanation: The .catch() method is used to handle errors that occur during the fetch request, such as network errors or parsing issues.


25.        Which HTTP method is most commonly used to send data to an API server?

a) GET
b) POST
c) PUT
d) DELETE

Answer: b) POST
Explanation: The POST method is used to send data to the server, often used for creating or updating data.


26.        How do you check if a key exists in sessionStorage?

a) sessionStorage.contains('key')
b) sessionStorage.getItem('key') !== null
c) sessionStorage.exists('key')
d) sessionStorage.has('key')

Answer: b) sessionStorage.getItem('key') !== null
Explanation: You use getItem() to retrieve the value for a given key, and check if it's null to determine if the key exists.


27.        What method would you use to remove a specific item from sessionStorage?

a) sessionStorage.removeItem()
b) sessionStorage.delete()
c) sessionStorage.clear()
d) sessionStorage.remove()

Answer: a) sessionStorage.removeItem()
Explanation: The removeItem() method is used to remove a specific item from sessionStorage.


28.        Which HTTP status code indicates a bad request?

a) 200
b) 301
c) 400
d) 500

Answer: c) 400
Explanation: The HTTP status code 400 indicates that the request was malformed or invalid, known as a "Bad Request".


29.        What does response.json() do in a fetch request?

a) Converts the response body into an array
b) Converts the response body into a JavaScript object
c) Returns the raw response text
d) Converts the response into an HTML element

Answer: b) Converts the response body into a JavaScript object
Explanation: The response.json() method parses the response body as JSON and returns it as a JavaScript object.


30.        Which method is used to store data in localStorage?

a) set()
b) storeItem()
c) localStorage.setItem()
d) localStorage.addItem()

Answer: c) localStorage.setItem()
Explanation: The localStorage.setItem() method is used to store a key-value pair in localStorage.


31.        What will happen if you try to get an item from localStorage that does not exist?

a) It returns an empty object
b) It throws an error
c) It returns null
d) It returns undefined

Answer: c) It returns null
Explanation: If the key doesn't exist in localStorage, getItem() will return null.


32.        Which of the following is true about localStorage?

a) Data is automatically deleted after each session
b) Data is available across different browsers
c) Data persists even after the browser is closed
d) Data is limited to 1MB per website

Answer: c) Data persists even after the browser is closed
Explanation: Data stored in localStorage persists even after closing and reopening the browser.


33.        What is the maximum storage capacity of localStorage in most browsers?

a) 5 KB
b) 10 MB
c) 50 MB
d) 5 MB

Answer: d) 5 MB
Explanation: Most modern browsers allow up to 5MB of storage per domain in localStorage.


34.        Which HTTP status code indicates that the resource was not found?

a) 404
b) 400
c) 403
d) 200

Answer: a) 404
Explanation: A 404 status code indicates that the requested resource could not be found on the server.


35.        Which of the following is an advantage of using sessionStorage over localStorage?

a) Data persists across browser sessions
b) Data is automatically deleted when the page is closed
c) Data can be shared across different browsers
d) Data is stored in a cookie

Answer: b) Data is automatically deleted when the page is closed
Explanation: sessionStorage only stores data for the duration of the page session, and it is deleted when the page is closed.


36.        What is the correct method to store an array in localStorage?

a) localStorage.setItem('array', array)
b) localStorage.setItem('array', JSON.stringify(array))
c) localStorage.store('array', array)
d) localStorage.add('array', array)

Answer: b) localStorage.setItem('array', JSON.stringify(array))
Explanation: To store an array, it must be stringified using JSON.stringify() before storing it in localStorage.


37.        How do you parse a response from an API as text using fetch()?

a) .parseText()
b) .json()
c) .text()
d) .responseText()

Answer: c) .text()
Explanation: The .text() method is used to extract the response body as a plain text string.


38.        Which of the following methods is used to fetch data from an API and display it on the page?

a) XMLHttpRequest()
b) fetch()
c) getJSON()
d) get()

Answer: b) fetch()
Explanation: The fetch() method is used to send HTTP requests and handle the responses asynchronously.


39.        What does the response.ok property indicate in a fetch() request?

a) Whether the request was successful (status code 200-299)
b) Whether the response is in JSON format
c) Whether the response is an HTML page
d) Whether the request was cancelled

Answer: a) Whether the request was successful (status code 200-299)
Explanation: The response.ok property is true if the response status code is between 200 and 299, indicating a successful request.


40.        What does the fetch() method return when an error occurs during a request?

a) A rejected Promise
b) A string with error details
c) A 404 status code
d) A success response with an empty body

Answer: a) A rejected Promise
Explanation: When an error occurs (e.g., network issues), fetch() returns a rejected Promise, which can be handled using .catch().


Continuing with more MCQs...

The next set of MCQs will dive deeper into handling different response types (e.g., XML, text), setting headers for requests, handling CORS (Cross-Origin Resource Sharing) issues, and working with other methods like PUT and DELETE.

4o mini

You said:

more

ChatGPT said:

ChatGPT

Here are more MCQs on "Working with APIs in JavaScript" with explanations:


41.        Which of the following is the correct way to handle errors when using fetch()?

a) .then(response => { ... }).catch(error => { ... })
b) .catch(error => { ... }).then(response => { ... })
c) try { fetch() } catch (error)
d) try { fetch() } finally { error }

Answer: a) .then(response => { ... }).catch(error => { ... })
Explanation: When using fetch(), you handle the response with .then() and handle errors with .catch() for promise rejection.


42.        Which method is used to send data to a server using fetch()?

a) GET
b) POST
c) PUT
d) All of the above

Answer: d) All of the above
Explanation: You can use fetch() with different HTTP methods like GET, POST, and PUT depending on the operation you're performing.


43.        How would you send a GET request with query parameters using fetch()?

a) fetch('url?param=value')
b) fetch({url: 'url', params: {param: 'value'}})
c) fetch('url', {method: 'GET', params: 'param=value'})
d) fetch('url').setParams('param=value')

Answer: a) fetch('url?param=value')
Explanation: To send query parameters in a GET request, you append them to the URL in the format url?param=value.


44.        What does the fetch() method return if no error occurs in the request?

a) An HTTP response object
b) A string of the API response
c) A boolean value of success or failure
d) An object with status code and data

Answer: a) An HTTP response object
Explanation: fetch() returns a Promise that resolves to the response object of the HTTP request.


45.        What happens if you call response.json() before checking if the response is successful?

a) The Promise resolves, but the result might be incorrect
b) An error is thrown
c) The response is returned as a string
d) Nothing happens

Answer: a) The Promise resolves, but the result might be incorrect
Explanation: If you call response.json() before checking if the response is successful, it may still attempt to parse the response, but if the request was unsuccessful (e.g., 404), the parsing could fail.


46.        Which of the following HTTP methods is typically used for updating an existing resource on the server?

a) GET
b) POST
c) PUT
d) DELETE

Answer: c) PUT
Explanation: The PUT method is typically used to update an existing resource on the server.


47.        What is the response.text() method used for in a fetch() request?

a) To parse the response body as plain text
b) To check the response status
c) To parse the response body as JSON
d) To check the response headers

Answer: a) To parse the response body as plain text
Explanation: The response.text() method is used to read the response body as plain text.


48.        How do you set the Content-Type header in a fetch() request?

a) fetch(url, {headers: {Content-Type: 'application/json'}})
b) fetch(url, {method: 'GET', contentType: 'application/json'})
c) fetch(url).setHeader('Content-Type', 'application/json')
d) fetch(url, {header: 'Content-Type: application/json'})

Answer: a) fetch(url, {headers: {Content-Type: 'application/json'}})
Explanation: You can set headers in the fetch() request using the headers object within the options parameter.


49.        What type of data does JSON.parse() return when it parses a valid JSON string?

a) A string
b) A number
c) A JavaScript object
d) A boolean value

Answer: c) A JavaScript object
Explanation: JSON.parse() parses a valid JSON string into a corresponding JavaScript object.


50.        Which of the following is a valid way to check if localStorage is available in the browser?

a) if (localStorage)
b) if (window.localStorage)
c) if (localStorage.available)
d) if (localStorage.exists)

Answer: b) if (window.localStorage)
Explanation: Checking for window.localStorage ensures that localStorage is available in the current browser.


51.        What does the response.ok property in a fetch request signify?

a) Whether the status code is between 400 and 500
b) Whether the request was successful (status 200-299)
c) Whether the response contains valid JSON
d) Whether the API returned an empty body

Answer: b) Whether the request was successful (status 200-299)
Explanation: response.ok is true when the HTTP status code is between 200 and 299, indicating a successful response.


52.        How do you send data to the server using fetch() for a POST request?

a) fetch(url, {body: JSON.stringify(data), method: 'POST'})
b) fetch(url, {body: data, method: 'POST'})
c) fetch(url, {data: data, method: 'POST'})
d) fetch(url, {body: data, method: 'GET'})

Answer: a) fetch(url, {body: JSON.stringify(data), method: 'POST'})
Explanation: For a POST request, you use body: JSON.stringify(data) to send data in JSON format.


53.        What is the main difference between localStorage and sessionStorage?

a) localStorage stores data only for the current session
b) sessionStorage stores data even after closing the browser
c) localStorage stores data persistently across browser sessions
d) sessionStorage can store more data than localStorage

Answer: c) localStorage stores data persistently across browser sessions
Explanation: localStorage persists across sessions, while sessionStorage only stores data for the duration of the session.


54.        Which of the following methods is used to clear all items from localStorage?

a) localStorage.remove()
b) localStorage.clear()
c) localStorage.reset()
d) localStorage.deleteAll()

Answer: b) localStorage.clear()
Explanation: The clear() method is used to remove all key-value pairs from localStorage.


55.        What is the function of response.json() in a fetch() request?

a) It parses the response body as HTML
b) It parses the response body as plain text
c) It parses the response body as JSON
d) It returns the headers from the response

Answer: c) It parses the response body as JSON
Explanation: The response.json() method is used to parse the response body as JSON and return a JavaScript object.


56.        What is the result of calling localStorage.setItem('name', 'John')?

a) Stores 'name' as a string 'John' in localStorage
b) Stores 'John' as a key in localStorage
c) Creates a new object named name in localStorage
d) Adds a new user named 'John' to localStorage

Answer: a) Stores 'name' as a string 'John' in localStorage
Explanation: localStorage.setItem() stores key-value pairs, with 'name' as the key and 'John' as the value.


57.        How do you access the value of a key in localStorage?

a) localStorage.get('name')
b) localStorage.retrieve('name')
c) localStorage.getItem('name')
d) localStorage.getValue('name')

Answer: c) localStorage.getItem('name')
Explanation: You use localStorage.getItem('key') to retrieve the value associated with a specific key.


58.        How can you check if a particular key exists in localStorage?

a) if(localStorage.has('key'))
b) if(localStorage.getItem('key'))
c) if(localStorage.contains('key'))
d) if(localStorage.exists('key'))

Answer: b) if(localStorage.getItem('key'))
Explanation: You can check if a key exists by attempting to get its value with getItem(). If it returns null, the key does not exist.


59.        What does the fetch() method return when an HTTP request fails due to network issues?

a) null
b) An error message
c) A rejected Promise
d) A successful response with status 200

Answer: c) A rejected Promise
Explanation: If the request fails due to network issues, fetch() returns a rejected Promise, which can be handled using .catch().


60.        Which of the following would be used to send form data with a POST request using fetch()?

a) fetch(url, {method: 'POST', body: new FormData(form)})
b) fetch(url, {method: 'GET', body: new FormData(form)})
c) fetch(url, {method: 'POST', body: form})
d) fetch(url, {method: 'POST', body: JSON.stringify(form)})

Answer: a) fetch(url, {method: 'POST', body: new FormData(form)})
Explanation: To send form data, you can use new FormData(form) as the body of the request.


I hope these questions help you with your understanding of working with APIs in JavaScript! Let me know if you'd like more questions or explanations.

4o mini

You said:

more

ChatGPT said:

ChatGPT

Here are additional MCQs related to "Working with APIs in JavaScript" with explanations:


61.        Which of the following is used to extract data from a Response object in fetch()?

a) response.read()
b) response.content()
c) response.json()
d) response.getData()

Answer: c) response.json()
Explanation: The response.json() method is used to parse the response body as JSON data.


62.        Which HTTP method would you generally use to delete a resource from the server?

a) GET
b) POST
c) DELETE
d) PUT

Answer: c) DELETE
Explanation: The DELETE method is used to remove a resource on the server.


63.        What will response.ok return if the HTTP status is 404?

a) true
b) false
c) undefined
d) null

Answer: b) false
Explanation: response.ok returns false for HTTP status codes outside the range 200-299, including 404.


64.        How can you send a request with custom headers using fetch()?

a) fetch(url, {header: {name: 'value'}})
b) fetch(url, {headers: {name: 'value'}})
c) fetch(url, {headers: 'name: value'})
d) fetch(url, {header: 'name=value'})

Answer: b) fetch(url, {headers: {name: 'value'}})
Explanation: Custom headers can be set by passing an object to the headers field in the fetch() options.


65.        What is the default HTTP method used by fetch() if the method is not specified?

a) GET
b) POST
c) PUT
d) DELETE

Answer: a) GET
Explanation: The default HTTP method for fetch() is GET if no method is specified.


66.        Which method is used to convert the request body into a JSON string before sending in a POST request using fetch()?

a) JSON.parse()
b) JSON.stringify()
c) JSON.encode()
d) JSON.decode()

Answer: b) JSON.stringify()
Explanation: JSON.stringify() is used to convert a JavaScript object into a JSON string before sending it in the body of a fetch() request.


67.        Which of the following is a correct way to send a POST request with JSON data using fetch()?

a) fetch(url, {method: 'POST', body: JSON.stringify(data), headers: {Content-Type: 'application/json'}})
b) fetch(url, {method: 'GET', body: JSON.stringify(data), headers: {Content-Type: 'application/json'}})
c) fetch(url, {method: 'POST', data: JSON.stringify(data), headers: {Content-Type: 'application/json'}})
d) fetch(url, {method: 'POST', body: JSON.parse(data), headers: {Content-Type: 'application/json'}})

Answer: a) fetch(url, {method: 'POST', body: JSON.stringify(data), headers: {Content-Type: 'application/json'}})
Explanation: The correct way to send JSON data is by using JSON.stringify(data) to convert the data and setting the appropriate Content-Type header.


68.        What does the response.status property return?

a) The response body
b) The status message of the response
c) The HTTP status code
d) The status of the fetch request

Answer: c) The HTTP status code
Explanation: response.status returns the numeric HTTP status code (e.g., 200, 404) from the server.


69.        Which of the following methods is used to extract the response body as an array buffer?

a) response.arrayBuffer()
b) response.buffer()
c) response.text()
d) response.json()

Answer: a) response.arrayBuffer()
Explanation: response.arrayBuffer() is used to read the response body and return it as an ArrayBuffer.


70.        What happens if you try to parse an invalid JSON string with JSON.parse()?

a) It returns an empty object
b) It throws an error
c) It returns null
d) It returns a default JavaScript object

Answer: b) It throws an error
Explanation: JSON.parse() will throw an error if the string is not a valid JSON format.


71.        Which of the following is the correct way to make a GET request with parameters using fetch()?

a) fetch(url + '?param1=value1&param2=value2')
b) fetch(url, {method: 'GET', params: {param1: 'value1', param2: 'value2'}})
c) fetch(url, {params: 'param1=value1&param2=value2'})
d) fetch(url, {method: 'GET', queryParams: {param1: 'value1', param2: 'value2'}})

Answer: a) fetch(url + '?param1=value1&param2=value2')
Explanation: Query parameters are typically added directly to the URL in a GET request in the format url?param1=value1&param2=value2.


72.        Which of the following methods can be used to store API responses locally in the browser for later use?

a) localStorage.setItem()
b) sessionStorage.setItem()
c) cookie.setItem()
d) Both a and b

Answer: d) Both a and b
Explanation: Both localStorage.setItem() and sessionStorage.setItem() can be used to store API responses locally, with localStorage persisting across sessions and sessionStorage only persisting for the current session.


73.        How can you pass additional data (such as authentication tokens) in a fetch() request?

a) By adding it to the query string
b) By including it in the body of the request
c) By setting the Authorization header in the request
d) By passing it as URL parameters

Answer: c) By setting the Authorization header in the request
Explanation: You can send authentication tokens in the Authorization header of the fetch() request.


74.        What does response.text() return when you call it on a response object?

a) A JavaScript object
b) A string representing the body of the response
c) An HTML element
d) A blob containing binary data

Answer: b) A string representing the body of the response
Explanation: response.text() returns the response body as a string.


75.        Which method would you use to parse a response body as a Blob object in a fetch() request?

a) response.text()
b) response.blob()
c) response.json()
d) response.buffer()

Answer: b) response.blob()
Explanation: response.blob() is used to parse the response body as a Blob object, which is typically used for binary data.


76.        What does fetch() do if a network error occurs, such as no internet connection?

a) It returns a rejected Promise
b) It throws a custom error
c) It returns an empty response object
d) It automatically retries the request

Answer: a) It returns a rejected Promise
Explanation: If there is a network error, fetch() will return a rejected Promise, which you can catch and handle with .catch().


77.        Which of the following methods is used to send a PUT request with updated data using fetch()?

a) fetch(url, {method: 'PUT', body: JSON.stringify(data), headers: {Content-Type: 'application/json'}})
b) fetch(url, {method: 'POST', body: data, headers: {Content-Type: 'application/json'}})
c) fetch(url, {method: 'PATCH', body: data})
d) fetch(url, {method: 'PUT', data: data})

Answer: a) fetch(url, {method: 'PUT', body: JSON.stringify(data), headers: {Content-Type: 'application/json'}})
Explanation: The correct way to send updated data with a PUT request is by using JSON.stringify() to serialize the data and setting the correct Content-Type header.


78.        What does the response.headers property return in a fetch() request?

a) The status code of the response
b) The headers of the response
c) The body of the response
d) The URL of the response

Answer: b) The headers of the response
Explanation: response.headers provides access to the headers returned by the server in the response.


These questions should give a thorough understanding of how APIs work in JavaScript and fetch() usage! Let me know if you need more.

4o mini

You said:

more

ChatGPT said:

ChatGPT

Here are additional MCQs related to Working with APIs in JavaScript with explanations:


79.        What type of data does the fetch() function return?

a) An array of values
b) A Promise that resolves to a Response object
c) An object with HTTP status information
d) A string of the HTTP response

Answer: b) A Promise that resolves to a Response object
Explanation: fetch() returns a Promise that resolves to a Response object, which contains the response data from the API.


80.        Which of the following is a valid way to check if the fetch() request was successful?

a) if (response.ok)
b) if (response.success)
c) if (response.code == 200)
d) if (response.status === 'OK')

Answer: a) if (response.ok)
Explanation: response.ok is a boolean value that indicates whether the HTTP response status code is in the range 200-299, meaning the request was successful.


81.        Which method is used to check if the fetch() request is still in progress?

a) response.inProgress()
b) response.status
c) response.ok
d) fetch() doesn't provide a method to check progress directly.

Answer: d) fetch() doesn't provide a method to check progress directly.
Explanation: The fetch() function does not include built-in methods for checking progress. To track progress, you would typically use the XMLHttpRequest API or ReadableStream in combination with fetch().


82.        How can you catch errors in a fetch() request?

a) Using try...catch block
b) Using .catch() method on the Promise
c) Using response.status
d) Both a and b

Answer: d) Both a and b
Explanation: Errors in fetch() can be caught either using the .catch() method on the returned Promise or by wrapping the code in a try...catch block if using async/await.


83.        What is the default Content-Type header when sending data with fetch()?

a) application/json
b) application/x-www-form-urlencoded
c) text/plain
d) No default header is set

Answer: d) No default header is set
Explanation: By default, fetch() does not set the Content-Type header. You must specify it manually if sending data such as JSON.


84.        Which HTTP method should you use to create a new resource on the server using fetch()?

a) PUT
b) DELETE
c) PATCH
d) POST

Answer: d) POST
Explanation: The POST method is used to send data to the server to create a new resource.


85.        What does the response.text() method return?

a) The HTTP status code
b) The JSON data
c) The response body as a string
d) The headers of the response

Answer: c) The response body as a string
Explanation: response.text() returns the body of the response as a plain text string.


86.        Which of the following options is used to handle multiple API requests simultaneously in JavaScript?

a) Promise.all()
b) Promise.each()
c) fetch.all()
d) async.all()

Answer: a) Promise.all()
Explanation: Promise.all() is used to handle multiple API requests simultaneously, waiting for all promises to resolve.


87.        What is the correct way to send data in the body of a GET request in fetch()?

a) fetch(url, {method: 'GET', body: data})
b) GET requests cannot have a body
c) fetch(url, {body: data})
d) fetch(url, {method: 'GET', payload: data})

Answer: b) GET requests cannot have a body
Explanation: GET requests do not have a body according to HTTP standards. Any data should be passed as URL parameters.


88.        What happens when you call response.json() on a non-JSON response?

a) It returns the response as a string
b) It throws an error
c) It automatically converts the response into JSON
d) It returns null

Answer: b) It throws an error
Explanation: If the response is not valid JSON, response.json() will throw an error. You should check if the response is valid before calling response.json().


89.        Which method is used to modify or update an existing resource on the server in fetch()?

a) POST
b) DELETE
c) PUT
d) PATCH

Answer: c) PUT
Explanation: PUT is used to modify or update an existing resource on the server with new data.


90.        What is the primary purpose of the response.headers object in the fetch() API?

a) To access the response status code
b) To access the response body
c) To retrieve the metadata about the response, like content type and length
d) To store cookies

Answer: c) To retrieve the metadata about the response, like content type and length
Explanation: response.headers contains metadata about the response, such as the content type and content length, which can help you understand the format of the returned data.


91.        Which of the following HTTP status codes indicates a successful GET request?

a) 200
b) 201
c) 400
d) 404

Answer: a) 200
Explanation: HTTP status code 200 indicates that the GET request was successful and the response body contains the requested data.


92.        What does the response.json() method do?

a) Converts the response to text
b) Parses the response body as JSON
c) Converts the response to an array
d) Converts the response to XML

Answer: b) Parses the response body as JSON
Explanation: response.json() parses the response body as JSON, converting it from a JSON-formatted string into a JavaScript object.


93.        Which method can be used to parse an API response as a stream?

a) response.arrayBuffer()
b) response.stream()
c) response.json()
d) response.text()

Answer: a) response.arrayBuffer()
Explanation: response.arrayBuffer() is used to parse the response body as an array buffer, which can be useful for working with binary data or streams.


94.        How can you prevent a fetch() request from timing out?

a) By setting a timeout using setTimeout()
b) By adding the timeout option to fetch()
c) fetch() does not allow timeout configuration
d) By setting the AbortController's timeout property

Answer: d) By setting the AbortController's timeout property
Explanation: To handle request timeouts, you can use the AbortController API in conjunction with fetch() to abort requests that take too long.


95.        Which of the following is used to create a delay between API requests in JavaScript?

a) setTimeout()
b) delay()
c) fetch().timeout()
d) sleep()

Answer: a) setTimeout()
Explanation: You can use setTimeout() to create delays between API requests. However, for more control, you can also use async/await with Promises.


96.        Which of the following HTTP status codes indicates a client error, such as a bad request?

a) 404
b) 200
c) 500
d) 301

Answer: a) 404
Explanation: A 404 status code indicates that the requested resource was not found, which is a client error.


97.        Which of the following HTTP methods is typically used to send data to an API for updating an existing resource?

a) PATCH
b) GET
c) DELETE
d) PUT

Answer: d) PUT
Explanation: PUT is used to update an existing resource with the provided data.


98.        Which fetch() method is used to retrieve the response as a JSON object?

a) response.text()
b) response.json()
c) response.body()
d) response.jsonObject()

Answer: b) response.json()
Explanation: response.json() is used to parse the response body as a JSON object.


99.        What does the AbortController allow you to do with fetch() requests?

a) Cancel the request after a certain time
b) Wait for the request to complete
c) Handle timeouts
d) Retry the request

Answer: a) Cancel the request after a certain time
Explanation: AbortController can be used to abort a fetch() request, providing better control over request timeouts and cancellations.


100. What does the response.ok property indicate?

a) Whether the response contains the expected data
b) Whether the status code indicates success (i.e., in the range 200-299)
c) Whether the request was sent correctly
d) Whether the content type matches the request

Answer: b) Whether the status code indicates success (i.e., in the range 200-299)
Explanation: response.ok is a boolean value that indicates if the HTTP response status code is in the range 200-299, signaling a successful request.




Post a Comment

0Comments

Post a Comment (0)