Reputation: 5986
I am reading source codes written in a game. Some lines are written as follows:
0 ? player.y > global.screenHeight/2 : global.screenHeight/2 - player.y
Assume that player
is a sprite with position and global
is just an import from other files which contains some properties. What does the above code do? I thought the ternary operator will be something like this:
c ? a : b
where a
and b
are of the same type and c
is the condition.
But the game demo runs smoothly so the above code should be fine. I just don’t get the meaning of the code.
The code is extracted from here:
https://github.com/huytd/agar.io-clone/blob/master/src/client/js/app.js
Upvotes: 1
Views: 115
Reputation: 3032
In the above ternary statement 0
is the condition.
Because Javascript treats 0
as falsy
, the statement is evaluated as if written as:
false ? player.y > global.screenHeight/2 : global.screenHeight/2 - player.y
Therefore, global.screenHeight/2 - player.y
will be returned.
It is possible the author put the ternary there to act as an on/off switch. By replacing the 0
with a 1
, the ternary statement would return player.y > global.screenHeight/2
instead.
Upvotes: 1
Reputation: 2579
0 ? player.y > global.screenHeight/2 : global.screenHeight/2 - player.y
Here 0 is false , So the global.screenHeight/2 - player.y
will be always executed
Upvotes: 0
Reputation: 1013
c ? a : b
a
and b
can evaluate to values of any type, and c
will evaluate to true
or false
.
0
will evaluate to false
, "b" will run: global.screenHeight/2 - player.y
This will happen regardless of anything else - the first expression will never run.
If I had to guess why that's in there, I'd say it may be a placeholder for a planned feature or improvement (however I obviously can't know for sure).
Upvotes: 0