0

Hopefully I am not crazy or this is something new about Javascript that I need to learn. I am writing an AngularJS app. I have the following script in Javascript;

$http({
    url: urls.BASE_API + '/conversations/'+conversationid,
    method: "Get"
}).then(function (response) {
    if (angular.isDefined(response.data)) {
        console.info ("The CONVERSATION!", response);
        var Data = response.data;
        Data.Messages = response.data.messages
        delete Data.data;
        options.success(Data);
    }
}, function (response) { // optional
    if (response.status = '404'){
        options.failure({
            message: "Conversation not found"
        })
    }
});

I have tested this many times. When delete Data.data; is removed the data is not available in the console.info() call. But console.info is called before delete. Why does this happen? What is the solution around this?

  • 1
    The console prints a *reference* to that object. So whenever you open it up, you see the state of the object *at the current point in time*, not it's state from when you logged it. One way you can generally view the state of an object at a point in time is to convert it to JSON. `JSON.stringify(Data)` or `JSON.stringify(Data, null, 2)` if you don't want it on one line. – Mike Cluck May 26 '16 at 22:23
  • Okay, I made a mistake I should I used Data in the console.info. Thanks. I didn't know that. –  May 26 '16 at 22:29
  • @MikeC It's not quite that simple across browsers, for example, in Chrome, if I log an object, the first open shows what you'd expect. If you change a property, open it again, the change is reflected. If you change it *again*, the change is no longer reflected when you open the object in the console. – Dave Newton May 27 '16 at 04:00

1 Answers1

0

Anyway, Javascript works with pointers and references under the hood, just primitives are allocated in memory, any other values are allocated once and refered any time they are requested.

var a = 5 // memory is allocated
var b = a // b points to &a, as it's a primitive, JS clones it
delete a  // deletes the a reference, but the memblock still there
console.log(b) // access to memblock set by first sentence via pointer

the memory block will be freed by the garbage collector once it's unaccessible, if all pointers or references are deleted the garbage collector will free the memory block.

With objects, this occurs

var a = {name: "john", surname: "doe"} // object is set in memory
var b = a // b points to &a reference, so the same mem block is used
delete a.surname; //deletes the .name obj from memory
console.log(b) // {name: "john"}

This occurs because we stored an non-primitive value and JS access it via pointers, you can clone objects to reallocate their value and make them "standalone"

PRDeving
  • 679
  • 3
  • 11