0

Is it possible to change the variable value with function like example below? Whenever I change the passed parameter value the original value doesn't change. Why is this happening?

let b = 3; function t(n) { n = 5; } t(b) console.log(b) // still 3 

I know this can be done like this, but I am wondering why the example above wont work.

let b = 3; function t() { return 5; } b = t(); console.log(b) 
1
  • JavaScript, like many other languages uses pass by value, not pass by reference. So what you want is not possible in that exact way. There are workarounds though. However, in such a simple case, returning the value and letting the caller decide how what to do with it seems the best solution. Commented Jul 1, 2022 at 7:26

1 Answer 1

2

Passing scalar values to function will pass them by value, not by reference.

One solution would be to pass it as object:

let b = {value: 3}; function t(n) { n.value = 5; } t(b); console.log(b.value);

Sign up to request clarification or add additional context in comments.

3 Comments

Objects are also passed by value but the value is a (different kind of) reference. You wouldn't be able to do n = {value: 5} either.
@FelixKling Yes, you are right, it's passed as shallow copy - only inner properties can be changed
It's not a copy, otherwise making changes to it wouldn't have any effect on the "original" object.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.