Passing by Value

When you pass data into a function in JavaScript, how that data is handled depends on its type. Primitive variables (like Numbers, Strings, and Booleans) are passed by value.

What is “Pass by Value”?

“Pass by value” means that when a variable is passed into a function, the function receives a completely independent copy of that variable’s value. The function cannot reach out and mutate the caller’s original data.

let x = 5;

function increment(val) {
  // 'val' is a copy of 'x'
  val++;
  console.log("Inside function:", val); // 6
}

increment(x);

// The original 'x' is completely unaffected
console.log("Outside function:", x); // 5

(Note: Objects and Arrays are passed by reference, which we will cover in a later chapter. Passing by reference allows the function to mutate the original data).

Practical Example

A common mistake for beginners is attempting to modify primitive arguments inside a function and expecting those changes to persist outside. You must explicitly return the new value to capture the change.

// BAD PRACTICE
function updateBill(billAmount) {
  // This only updates the local copy!
  billAmount = billAmount + 10; 
}

let myBill = 50;
updateBill(myBill);
console.log(myBill); // Still 50!

// GOOD PRACTICE
function calculateNewBill(billAmount) {
  return billAmount + 10;
}

let myNewBill = 50;
// Capture the returned copy
myNewBill = calculateNewBill(myNewBill); 
console.log(myNewBill); // 60