3 Short JavaScript Quizzes 💡

365kim
2 min readJul 21, 2024

--

Photo by Ahmet Kurt on Unsplash

ã…¤

Quiz 1 — JSON.stringify

What is the result of the following statement?

JSON.parse(JSON.stringify({ a: undefined }))

Answer choices:

  • {}
  • { a: undefined }
  • { a: ‘undefined’ }

The answer is {}

When an object contains a property with the value undefined, that property is omitted from the resulting JSON string. Therefore, JSON.stringify({ a: undefined }) results in '{}'

When this JSON string is parsed back into an object using JSON.parse, the resulting object is {}.

Quiz 2 — fetch API

In the following code, will an error log be printed if an error occurs in fetch?

try {
fetch('https://example.com') // 404 or 500 Server Response
} catch (err) {
console.error(err, 'error')
}

what about the following code?

fetch('https://example.com')
.then((res)=>console.log(res))
.catch((err)=>console.error('error', err))

The answer is No, and No.

The fetch() promise resolves on server response errors like 404 or 500, unlike network errors or CORS issues which cause it to reject.

To determine the success status of a fetch() request more concisely, you need to check res.ok directly. (In this aspect, using ky is recommended.

Quiz 3— RegExp.prototype.test()

Why is the first result true and the second result false?

> new RegExp({}).test('mom') // true
> new RegExp({}).test('dad') // false

Passing an object to the RegExp constructor creates a regular expression /[object Object]/. Therefore, new RegExp({}).test(str) is evaluated as /[object Object]/.test(str).

This regular expression is interpreted as a character set containing the characters o, b, j, e, c, t, O, b, j, e, c, t. Essentially, it will match any string that contains at least one of these characters.

Thus, test('mom') returns true, while test('dad') returns false.

ã…¤

Understanding these quirks and details can help you write more robust and error-free JavaScript code. Keep experimenting and learning, and happy coding!

--

--

365kim
365kim

Written by 365kim

Web Front-End Developer who believes Every Day Counts!

No responses yet