1

The supposed duplicate question only answers the first part(badly) of this question, and not the second. It answers the first part "badly" because JSON.stringify only works for super simple examples. Once the example becomes slighly more complex it opens another problems. Such as "TypeError: Converting circular structure to JSON".

console.log doesn't work as expected. Pay attention to the behaviour in React, CodeSandbox. Link. I stumbled upon the bug while working on my project, which isn't on CodeSandbox, and doesn't use create-react-app(if that matters).

This is not only in React CodeSandbox, but also in Vanila sandbox and probably others.

Below I wrote 2 examples that work as expected.

<!DOCTYPE html>
<html>

<body>
  <h1>My First Heading</h1>

  <p>My first paragraph.</p>
</body>
<script>
  const items = [1, 2];

  console.log(items); //okay. Expected=Actual=[1,2]
  console.log(items[0]); //okay. Expected=Actual=1
  items.reverse();
  console.log(items); //okay, Expected=Actual = [2,1]
  console.log(items[0]); // okay, Expected=Actual=2
</script>

</html>

Reactjs snippet:

const Why = () => {
const items = [1, 2];

  console.log(items); //okay. Expected=Actual [1,2]
  console.log(items[0]); //okay. Expected=Actual=1
  items.reverse();
  console.log(items); //okay, Expected=Actual = [2,1]
  console.log(items[0]); // okay, Expected=actual=2
  
return <div>{items}</div>;
};

ReactDOM.render(
  <Why />,
  document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
  1. How can I fix that console.log() issue?
  2. Why does the behaviour differ in different environments?
ZenVentzi
  • 3,945
  • 3
  • 33
  • 48
  • What exactly is the bug? Everything says `okay. Expected=Actual`? – CertainPerformance Mar 12 '19 at 09:42
  • @CertainPerformance No it doesn't. Re-read the top sentence, with the link, and the first console.log in the link – ZenVentzi Mar 12 '19 at 09:44
  • 5
    when `console.log()` objects, the displayed value will be altered by object mutations. `Array.prototype.reverse` is a mutation, you can shallow copy the array before logging. – remix23 Mar 12 '19 at 09:45
  • The top sentence `console.log doesn't work as expected` does not explain what the bug you're experiencing is, you just posted a bunch of code and said that there's a bug, but not what the bug actually is... (all information should be in the question itself, not somewhere offsite) – CertainPerformance Mar 12 '19 at 09:48
  • @CertainPerformance it explains very clearly that value X is expected and instead we receive value Y. Also I gave different examples because it's unclear why it works differently in different environments. I don't see how the "duplicate" question answers that. – ZenVentzi Mar 12 '19 at 09:55

0 Answers0