1

Say for example you have a function like below

var value = 1;
function test(myVar) {
  myVar = 2
}
test(value)
console.log(value)
//prints out 1

Now, I have read that there are two things that happen in JS functions.

1) Javascript passes primitives by value. When "value" is passed as an argument to test(), a copy is created that is separate from the global variable "value". Therefore the "myVar" is a separate variable from "value"

2) Parameters in JS functions are really just local variables to the function. So, the "myVar" parameter has scope only inside of the test() function.

I know both statements are true, but which one of these statements causes console.log(value) to print out 1

user3092075
  • 281
  • 1
  • 2
  • 9

2 Answers2

0

Both of those statements are true. The reason why it prints out 1 is that, as you mentioned, parameters are passed by value. As such, the value of your variable value is never altered.

Although point #2 is also true, it doesn't really have much to do with this behaviour. it is more related to doing something like using myVar outside of that function's scope.

Pabs123
  • 3,385
  • 13
  • 29
0

Both of the statements are correct

Please check this URL from Mozilla Variable Scope in Javascript

Arpit Agarwal
  • 553
  • 1
  • 4
  • 15