+ 3
Js question
function f(x) { x += 1; return x; } var b = 1; f(b) console.log(b); // 1 Why this code doesn't output 2?
7 Respostas
+ 8
i would agree to Rupali , except the fact that we should not use the same variable name for storing the returned value from function as this is already used for the "input" value that is passed to the function.
(sample from Rupali)
function f(x){
x += 1;
return x;
}
var b = 1;
res = f(b);
console.log(res);
+ 5
// As Rupali said you did not store the value. For this reason you can code instead:
console.log(f(b));
+ 4
David your function is returning that value and you are not storing this value in any variable, first you have to store this value in amy variable then print that variable.
Or you can do something like that:
function f(x){
x+=1;
return x;
}
var b=1;
b=f(b);
console.log(b); //2
+ 4
Thanks everyone for your help!
+ 4
Because the value of the variable b is passed to the function parameter x and operations are performed with x in the function, and b, as it was 1, remains 1. ☺️
+ 3
Hi ! Go through this thread please ,
https://www.google.com/url?sa=t&source=web&rct=j&url=https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language%23:~:text%3DJavaScript%2520is%2520always%2520pass%252Dby,%252Dclass%2520objects%2520in%2520JavaScript).&ved=2ahUKEwjC3Ma0mczzAhUmxzgGHeq9AJwQFnoECAQQBQ&usg=AOvVaw1h_wtXxgbPv7g8HWdO7N6R
+ 3
console.log(f(b))