My question is, if the GET request returns the responseText as a string by default, then wouldn’t it be redundant to use JSON.parse() in line * only to JSON.stringify() it back to a string in the next line?
Couldn’t we just add the responseText to the HTML element by doing something like: document.querySelector('.message').innerHTML = req.responseText
I am guessing that we use JSON.parse() because we might need it in object format for other things, and it’s not a best practice to just keep it as a string?
You are correct in pointing out that using JSON.parse() followed by JSON.stringify() in the following code sample would be superfluous if the answer is already a string. If the GET response is a valid JSON string, you can assign it directly to the HTML element without any additional parsing or stringifying.
In this situation, you can use req.responseText to assign the JSON string to the HTML element’s innerHTML attribute directly. Here’s a modified version of the code that removes the superfluous JSON.parse() and JSON.stringify() calls.