Instagram | Twitter | LinkedIn
What is the output of the following code ?
A. true
B. undefined
C. false
Click here to see the correct answer and explanation 👀
Correct Answer | Explanation |
---|---|
A | Checking if two JavaScript objects are equal to see if you need to update the UI is a common task in React (for example). One of the ways to compare two objects in JavaScript is to convert them to JSON and check if the resulting strings are equal. JSON.stringify() takes a JavaScript object and transforms it into a JSON string. In this case, JSON.stringify(Smoothie1) and JSON.stringify(Smoothie2) are the same JSON string ("{"strawberries":"🍓","bananas":"🍌","orangeJuice":"🍊"}" ) and for this reason, the result is true . |
Explanation based on 👉🏼 JSON.stringify() and JSON.parse() and JSON.stringify() If you want to know more about Object Comparison 👉🏼 JavaScript deep object comparison - JSON.stringify vs deepEqual
¿ Qué imprime el siguiente código ?
A. true
B. undefined
C. false
Haz click aquí para ver la respuesta correcta y su explicación 👀
Respuesta correcta | Explicación |
---|---|
A | Mirar si dos objetos en JavaScript son iguales para saber si se necesita actualizar la UI (User Interface) es una tarea muy común en React (por ejemplo). Uno de los caminos para comparar dos objetos en JavaScript es convertirlos a JSON strings y revisar si son iguales. JSON.stringify() toma un objeto de JavaScript y lo transforma en JSON string. En este caso, JSON.stringify(Smoothie1) y JSON.stringify(Smoothie2) son el mismo JSON string ("{"strawberries":"🍓","bananas":"🍌","orangeJuice":"🍊"}" ) y por esta razón, el resultado es true . |
Explicación basada en 👉🏼 JSON.stringify() y JSON.parse() and JSON.stringify() Lecturita adicional 👉🏼 JavaScript deep object comparison - JSON.stringify vs deepEqual