DEV Community

Aditya Raj
Aditya Raj

Posted on

Primitives, Functions, and WTH The Value won't Update

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
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode
  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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)