Initiative: Red Dawn

June 5, 2016

Tip: Avoid unwanted assignments

Let’s say you want to check if the current level number equals 2. Normally you would do:
if (levelNumber == 2) { // some code here }
But, if you accidentally do:
if (levelNumer = 2) { // some code here }
Then your program will always step into that “if” sentence (unless levelNumer is a readonly property). Because doing “levelNumer = 2” is an assignment and it will return true. You will be assigning the value 2 to the variable levelNumber, and most likely you don’t want to do that. For such cases, simple invert the order and put the constant before like so:
if (2 == levelNumer) { // some code }
The result is exactly the same, but if you miss one equal sign the compiler will complain. unwanted-assignments And always, absolutely always is better to have compile errors than run time ones. Follow us to get more programming tips! [twitter-follow screen_name=’indelvestudios’]

Leave a Reply