Are primitive values passed by value or by reference when passed as arguments to a function in JavaScript?

In JavaScript, primitive values are passed by value when used as arguments in a function.

When a primitive value (such as a number, string, boolean, etc.) is passed as an argument to a function, a copy of the actual value is passed to the function. Any changes made to the parameter inside the function do not affect the original value outside the function. This is because primitive values are immutable, and operations on them create new values.

Here's a simple example:

function modifyPrimitive(x) {
  x = x + 1;
  console.log("Inside function:", x);
}

let num = 5;
modifyPrimitive(num);

console.log("Outside function:", num);

In this example, the `modifyPrimitive` function takes a primitive value (`num`) as an argument. The function increments the value inside the function, but this change does not affect the original `num` variable outside the function. The output will be:


Inside function: 6
Outside function: 5


This behavior contrasts with objects, which are passed by reference. When you pass an object to a function, you're passing a reference to the original object. Changes made to the object inside the function will affect the original object outside the function.