0

As you can see below, even though the array is logged before the mutating method is applied, the debugger still shows it as already being applied. However, its elements and properties when called specifically still return correctly:

If I add a breakpoint before the methods, then it is correct. If I continue then the result doesn't change.

I've read about Copying methods and mutating methods but still don't get why this is the case.

Is this a bug of VS Code or something?

const array = ["cat","dog","mouse"]
console.log('array', array);
console.log('array[0] :>> ', array[0]);
console.log('array.length :>> ', array.length);

array.splice(0, 1)
// array.push('bat')
debugger
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Ooker
  • 1,969
  • 4
  • 28
  • 58
  • Now try it logging `JSON.stringify(array)` – Dave Newton Jul 19 '23 at 15:47
  • `["cat","dog","mouse"]` – Ooker Jul 19 '23 at 15:48
  • What does that suggest about logging objects? – Dave Newton Jul 19 '23 at 15:49
  • 1
    a bug of VS Code? – Ooker Jul 19 '23 at 15:50
  • Or console.log is dynamic and reflects the object as-it-is, rather than as-it-was. That's what `JSON.stringify` does. – Dave Newton Jul 19 '23 at 15:54
  • if so, then why does applying non-mutating methods to the object itself, e.g. `array = array.slice(0,1)` doesn't change the object? – Ooker Jul 19 '23 at 15:57
  • 1
    Same thing happens in browsers: https://stackoverflow.com/q/11284663/3001761, https://stackoverflow.com/q/23429203/3001761. _"why does applying non-mutating methods... doesn't change the object"_ - because they're non-mutating. – jonrsharpe Jul 19 '23 at 15:59
  • 1
    Non-mutating methods don't change the object by definition. – Dave Newton Jul 19 '23 at 16:00
  • @DaveNewton I know that they don't change the object, but isn't that assigning the result to the original object changing it as well? – Ooker Jul 19 '23 at 16:41
  • 1
    That changes what `array` references, not the object. The `console.log(array)` line isn't re-evaluated--the console displays the original reference. – Dave Newton Jul 19 '23 at 16:46
  • 1
    The outcome of `console.log()` is colored in blue. The other information that you can see in the console is probably an enhancement of the browser (VSCode is backed by Chromium) that displays dynamic data in the console, based on what objects were passed to `console.log()`. It mixes the behaviour of the console (which shows the data as it looked like when it has been printed) with the behaviour of the "Variables" window, which evaluates each expression every time the application is stopped in the debugger. – axiac Jul 19 '23 at 16:58

0 Answers0