I try to modify a boolean
parameter inside a function, like this:
const getCheckedValue = (action) => {
let value = true;
getPermissionIsCheckedRecursively(permission, action, value);
return value;
};
const getPermissionIsCheckedRecursively = (
permission,
action,
checkedValue
) => {
if (!permission?.permission_child?.length) {
checkedValue =
checkedValue &&
!!dataForUpdate?.find(
(i) =>
i.permission_key === permission?.key &&
i?.action?.find((e) => e === action)
);
} else {
permission.permission_child.forEach((i) => {
getPermissionIsCheckedRecursively(i, action, checkedValue);
});
}
};
The result I got is always true
, I think this implement is wrong, so I changed to a plain object, like this:
const getCheckedValue = (action) => {
const dummy = {
value: true,
};
getPermissionIsCheckedRecursively(permission, action, dummy);
return dummy.value;
};
const getPermissionIsCheckedRecursively = (
permission,
action,
checkedValue
) => {
if (!permission?.permission_child?.length) {
checkedValue.value =
checkedValue.value &&
!!dataForUpdate?.find(
(i) =>
i.permission_key === permission?.key &&
i?.action?.find((e) => e === action)
);
} else {
permission.permission_child.forEach((i) => {
getPermissionIsCheckedRecursively(i, action, checkedValue);
});
}
};
By adding a dummy object wrapper, this code worked correctly, but I don’t understand why?
>Solution :
In JavaScript, primitive data types such as booleans are passed by value, which means that when you pass a boolean as a function parameter, a copy of the original value is created and passed to the function. Any changes made to the value inside the function are made to the copy, not the original value. Therefore, when you modify the checkedValue parameter inside getPermissionIsCheckedRecursively
, it does not modify the value variable defined in getCheckedValue
.
When you use an object wrapper, you are passing an object reference to the function, not a copy of the value. The object reference points to the same object in memory, so any changes made to the object inside the function are reflected outside of the function.
In your modified code, you create a dummy object with a value property set to true. You pass this object to getPermissionIsCheckedRecursively
as the checkedValue parameter. Inside the function, you modify the value property of the checkedValue object, which modifies the dummy object outside the function. When you return dummy.value
from getCheckedValue
, you are accessing the modified value
property of the dummy
object.
Therefore, by using an object wrapper, you can modify the boolean value inside the function and have those changes be reflected outside the function.