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 myPointsvariable 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:
To fix this, I have two main options:
function add3(points) { return points + 3; } myPoints = add3(myPoints);
let myPoints = { value: 3 }; function add3(pointsObj) { pointsObj.value += 3; } add3(myPoints); console.log(myPoints.value); // Now it's 6
The above is the detailed content of Primitives, Functions, and WTH The Value wont Update. For more information, please follow other related articles on the PHP Chinese website!