Home  >  Article  >  Web Front-end  >  Primitives, Functions, and WTH The Value won&#t Update

Primitives, Functions, and WTH The Value won&#t Update

王林
王林Original
2024-08-14 12:33:39869browse

Primitives, Functions, and WTH The Value won

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:

  1. 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.

  2. Function scope:
    Variables defined inside a function have function scope, meaning they're only accessible within that function.

  3. 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:

  1. When I call add3(myPoints), a copy of the value of myPoints (3) is passed to the function.
  2. Inside the function, points is a local variable that gets increased to 6.
  3. However, this change only affects the local points variable, not the original myPoints.
  4. The function doesn't return the new value, so the result is not stored anywhere.
  5. The original myPoints remains unchanged.

To fix this, I have two main options:

  1. Return the new value and reassign it:
function add3(points) { 
    return points + 3;
}

myPoints = add3(myPoints);
  1. 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

The above is the detailed content of Primitives, Functions, and WTH The Value won&#t Update. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn