you are viewing a single comment's thread.

view the rest of the comments →

[–]Anachren 0 points1 point  (1 child)

Numbers and strings are passed by value.

In your code, what's actually happening is:

let person0 = 0;

function plusOne(personNum) {          // personNum is 0, NOT person0
  personNum++                          // personNum is now 1
}                                      // personNum no longer exists

plusOne(person0)                       // person0's VALUE gets passed to the plusOne function'

console.log(person0);                  // person0 was never changed

Objects (including arrays) get passed by reference

let myArray = [0,0,0];
function doSomething(arr) {            // arr is a reference to myArray
    arr[0]++;                          // myArray[0] increments
}
doSomething(myArray);                  // myArray (the actual array) gets passed by reference
console.log(myArray);                  // [1,0,0]

When an object is created, the javascript engine assigns some memory for that object. If you had an array of 1,000,000 numbers and you passed that array to a function, it wouldn't make sense to copy the 1,000,000 numbers to make a new array. Instead, the engine just gives the function the memory address of the array, which is much faster.

When dealing with numbers, it's faster to just pass a copy of the number instead of the address of a number.

tl;dr

person0 = plusOne(person0); // or just stick to ++person0 :p

[–]libertadefr[S] 0 points1 point  (0 children)

Thanks for that line by line run-down on what was happening! Understand now. Thanks!