-2

I was sure this expression

const arr = [1,2,3]
console.log(arr)
arr.push(4)

Should return [1,2,3]. Actually, if write it in the browser console it'll return what expected. But I accidentally open codesandbox and write the same code there and I got as the answer is [1,2,3,4]. And I'm really confused in my knowledge :) I don't know why it's happening. I think it's because of bundler, I tried Parcel and WebPack bundlers both have the same result. But as I said I'm not sure. If anyone knows I would love to read it.

Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
Alex Park
  • 651
  • 8
  • 15
  • No, you are not assigning something new to the variable arr, you are just pushing the new value in. Also, when you are evaluating the output in the console. It will evaluate to the current value (ie the value it has now, not when it got sent to the console). If you just want it to have the actual data, you should either slice it or using json.stringify on the data – Icepickle Aug 28 '19 at 12:02

1 Answers1

1

it occurs when the code resides in scripts that are executed immediately (before the page is loaded), even when the console is open, whenever the page is refreshed. Calling console.log when the console is not yet active only results in a reference to the object being queued, not the output the console will contain. Therefore, the array (or any object), will not be evaluated until the console is ready. It really is a case of lazy evaluation.