+ 1

JavaScript: variable without value outputs 1

Anyone explaining this simple code? var x; if (x = 1) { alert("1"); } else { alert("2"); } // output: 1

31st Jan 2020, 5:31 PM
Prof. Dr. Zoltán Vass
4 Réponses
+ 7
Prof. Dr. Zoltán Vass Thank you for your opinion! I'm glad to hear that! 😃 Also, thanks for you noticed me about the Line 9. Well, yes, it's actually redundant.. 😁
6th Feb 2020, 8:45 PM
Donthack
Donthack - avatar
+ 6
Welcome. Take a look on this code, i tried to write the things. Maybe the answer can be explained better than mine, but at least this code is working :) https://code.sololearn.com/WSxyh2kBdQ9h/?ref=app
6th Feb 2020, 9:42 AM
Donthack
Donthack - avatar
+ 4
In your first if statement you are DEFINING x as 1. Use the == to compare x to 1.
31st Jan 2020, 5:32 PM
Gevork Bagratyan
+ 1
Donthack Thanks for the code, it is a nice explanation! (BTW line 9 in your code seems to be redundant)
6th Feb 2020, 2:40 PM
Prof. Dr. Zoltán Vass