+ 1

I need explains about the output of this JS code...

var a ={attr:12}; var b =37; function change(obj,x){ x++; obj.attr++; } change(a,b); console.log(a.attr+""+b); Output is "1337". Can someone please explain for me why the value of b is still 37 although I called function change() with 2 arguments a and b? Thank you so much and sorry for my bad English! :)

22nd Jan 2018, 11:41 AM
Nguyễn Hứa Gia Thuyên
Nguyễn Hứa Gia Thuyên - avatar
2 Antworten
+ 7
An object is always passed by reference.. that's why the value of attr changes.But when you pass b as argument in the function, it means you are passing the value of b(37), not the variable b..so the function changes 37 to anything else and doesn't affect the value of b
22nd Jan 2018, 12:39 PM
Md. Nafis Ul Haque Shifat
Md. Nafis Ul Haque Shifat - avatar
+ 1
@Md. Nafis Ul Haque Shifat: Thank you so much for your answer. I understood like this: When I called functions with argument "b", it will be treated as local scope. That why the value of the global scope "b" didn't change. I tried removing the second parameter of the function, using b instead of x and the output was "1338". Is my thought right?
22nd Jan 2018, 1:37 PM
Nguyễn Hứa Gia Thuyên
Nguyễn Hứa Gia Thuyên - avatar