0

I have the following code:

function control_function() {
    let data = { inputs: [ 'one', 'two'] };
    level_one(data);
    console.log(data);
} control_function();

function level_one(data) {
    data.inputs.shift();
}

And you can see I'm outputting data, it should give me ['one', 'two'] back, instead it gives me ['two'], meaning that the function level_one has, for some reason, affected data that it shouldn't have access to (to write, it has access to it to read, since I'm passing it to the function). I'm signaling to JS that this let data is only to be used within the control_function scope and is not to be affected by other functions.

In PHP, this doesn't happen and it makes sense for it not to happen, yet it happens here, which means there's some underlying basic concept I don't understand. What am I doing wrong?

coolpasta
  • 725
  • 5
  • 19
  • 1
    "In any other programming language, this doesn't happen" Wrong. What makes you think that? Objects and arrays etc. are passed by references in other programming languages just as well and you would observe the exact same behavior (Java, C#, ..) – marsze Nov 12 '18 at 09:39
  • @marsze Sorry, I meant PHP. Is there any reason for why this was chosen and how can I make it work so that any function that uses the data I pass has it as a copy, not as a reference, so that my original data doesn't get changed? Also, this smells bad, it feels that if I have to pass an object by value, something is wrong. – coolpasta Nov 12 '18 at 09:44
  • If you want to modify the contents of the array without affecting the original, you should simply make a copy/clone first. – marsze Nov 12 '18 at 09:48
  • @marsze Naturally and here's the code: `let copied_data = $.extend({}, data);` but doesn't this feel like a cheat? – coolpasta Nov 12 '18 at 09:48
  • Arrays are objects. If you want to **modify** a passed object inside a function, but **keep** original, then yes you have to make a clone. You can also clone arrays with `clone = array.slice(0)`. – marsze Nov 12 '18 at 09:58

0 Answers0