I was working on my basics a bit and came across this problem, that I know intuitively, but never went into detail to explore. And there's no excuse for me to not have a deeper understanding of how JavaScript treats primitives.
This is by far the simplest example. Here, the myPoints
variable won't update even when I call the add3
and the remove1
functions.
let myPoints = 3;
function add3(points) {
points += 3;
}
function remove1(points) {
points--;
}
add3(myPoints);
remove1(myPoints);
console.log(myPoints) // 3
Here's the core concepts that make this work the way it does:
Pass by value:
In JavaScript, when you pass primitive values (like numbers) to functions, they are passed by value. This means a copy of the value is created and passed to the function, not the original variable itself.Function scope:
Variables defined inside a function have function scope, meaning they're only accessible within that function.Return values:
Functions in JavaScript need to explicitly return a value if you want to use the result outside the function.
Here's why myPoints
isn't changing:
- When I call
add3(myPoints)
, a copy of the value ofmyPoints
(3) is passed to the function. - Inside the function,
points
is a local variable that gets increased to 6. - However, this change only affects the local
points
variable, not the originalmyPoints
. - The function doesn't return the new value, so the result is not stored anywhere.
- The original
myPoints
remains unchanged.
To fix this, I have two main options:
- Return the new value and reassign it:
function add3(points) {
return points + 3;
}
myPoints = add3(myPoints);
- Pass the variable by reference (using an object):
let myPoints = { value: 3 };
function add3(pointsObj) {
pointsObj.value += 3;
}
add3(myPoints);
console.log(myPoints.value); // Now it's 6
Top comments (0)