Changing variable names leading to change in output | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 10

Changing variable names leading to change in output

When i write var first = {name}; first.name = "myName"; console.log(first.name); //Output: myName But when i write var name = {first}; name.first = "myName"; console.log(name.first); //Output: error Why ? All i've done is change their names

22nd Sep 2019, 5:14 AM
LightHimself
LightHimself - avatar
3 Answers
+ 6
because var name is window.name, the name property of window object. try using let name to declare instead. https://code.sololearn.com/W6QCoeIi2IaM/?ref=app
22nd Sep 2019, 9:23 AM
Gordon
Gordon - avatar
+ 5
Your problem would be solved if you changed "name" for other word and if you removed "first" from the brackets, as there is no variable called "first". The result could be this one: var nombre = {}; nombre.first = 'Rushikesh'; console.log(nombre.first); If you wanted to keep "first" in the brackets, the result could be this one: var nombre = {first:""}; nombre.first = 'Rushikesh'; console.log(nombre.first); The reason that "first" is working here it's that it's not seen as a variable but as a property with no value.
22nd Sep 2019, 9:30 AM
Sercalod
Sercalod - avatar
0
yes
23rd Sep 2019, 7:39 AM
mohd kashan
mohd kashan - avatar