+ 6

Can anyone explain this to me?

var y = 7 ; function func(x) { x = 4 } ; func(y) ; document.write(y) Why is the output 7, not 4? Please explain!

8th Jan 2017, 11:11 AM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
9 Answers
+ 7
Nothing changes the value of "y" so it stays the same.
8th Jan 2017, 11:18 AM
Valen.H. ~
Valen.H. ~ - avatar
+ 7
It should be written "y = func(y)", got it?
8th Jan 2017, 11:21 AM
Valen.H. ~
Valen.H. ~ - avatar
+ 5
But x is a parameter, it's not a variable...
8th Jan 2017, 11:16 AM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 5
Why does func(y) not change the value of y?
8th Jan 2017, 11:19 AM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 5
y = func(y) is only if func(x) has a return value of 4.
8th Jan 2017, 11:22 AM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 5
Even if func() had return, "y" value wouldn't change.
8th Jan 2017, 11:27 AM
Valen.H. ~
Valen.H. ~ - avatar
+ 3
'y' variable is passed to function 'func' by value: the value of 'y' is duplicated, and set to the argument variable 'x' value. Inside 'func', the value of variable 'x' is modified, then the function end, and its scope too: var 'x' and its value are deleted ( precisly: garbage collected ^^ ). During all this time, the value of 'y' stay unchanged, just have been reading when the call of the function occured, to COPY the value in function parameters... The trap is, when passing objects ( all non basic type, including arrays ), variables are passing by reference, which means without duplicate it, so will be modified if the function change their values!
8th Jan 2017, 11:37 AM
visph
visph - avatar
+ 1
Because there is no return. The variable x which has a scope only within the function is 4 If you would document.write(x) in the function the output would be 4
8th Jan 2017, 11:14 AM
Manuel Wiltz
Manuel Wiltz - avatar
0
when you call fanc(y) here is the logic of what happens... x becomes equal to y then x becomes equal to 4. y doesn't change.
10th Jan 2017, 5:02 AM
Periklis Panagiotis Arnaoutis
Periklis Panagiotis Arnaoutis - avatar