+ 1

JavaScript question

Hi var a = { atr: 12 } var b = 37; function change(obj, x) { x++; a.atr++; } change(a, b); console.log(a.atr + "" + b); // 1337 Why is the output 1337? Should itnot br 1338, since parameter x is being incremented, and in the function call that argument is variable b?

5th Mar 2022, 9:14 AM
David
David - avatar
3 Answers
+ 2
// Because x is a local variable of the function the code should looks like: var a = { atr: 12 } var b = 37; function change(x) { x++; a.atr++; return x } b=change(b); console.log(a.atr + "" + b);
5th Mar 2022, 9:39 AM
JaScript
JaScript - avatar
+ 1
when you called the function you are not actually passing the variables but you are just passing the values of those variables, and hence the variables 'b' will remain unchanged because you incremented the 1 into value of b and not the actual variable b.
5th Mar 2022, 9:24 AM
Ratnapal Shende
Ratnapal Shende - avatar
+ 1
Just a little edit var a = { atr: 12 } var b = 37; function change(obj, x) { x++; obj++; return obj + "" + x } console.log(change(a.atr, b)); // 1338
5th Mar 2022, 10:51 AM
Chigozie Anyaeji 🇳🇬
Chigozie Anyaeji 🇳🇬 - avatar