+ 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?

15th Oct 2021, 10:00 AM
David
David - avatar
7 odpowiedzi
+ 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);
15th Oct 2021, 10:45 AM
Lothar
Lothar - avatar
+ 5
// As Rupali said you did not store the value. For this reason you can code instead: console.log(f(b));
15th Oct 2021, 10:45 AM
JaScript
JaScript - avatar
+ 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
15th Oct 2021, 10:26 AM
Rupali Haldiya
Rupali Haldiya - avatar
+ 4
Thanks everyone for your help!
15th Oct 2021, 10:50 AM
David
David - avatar
+ 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. ☺️
15th Oct 2021, 11:00 AM
Solo
Solo - avatar
+ 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
15th Oct 2021, 10:24 AM
Abhay
Abhay - avatar
+ 3
console.log(f(b))
16th Oct 2021, 4:42 PM
Chigozie Anyaeji 🇳🇬
Chigozie Anyaeji 🇳🇬 - avatar