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

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

王林
Release: 2024-08-14 12:33:39
Original
918 people have browsed it

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
Copy after login

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);
Copy after login
  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
Copy after login

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!

source:dev.to
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template