0

In my nodeJS server I've got the following:

console.log(socket.geoData.hostname + socket.geoData.uri + ": " + 
                                socket.geoData.country + 
                                (socket.geoData.city != "false" ? ", " + socket.geoData.city : false)
                            );

But if condition fails it is actually appending the word false and not simply doing nothing. In PHP, I could return false and nothing would be appended. How can I achieve that here?

Chud37
  • 4,907
  • 13
  • 64
  • 116
  • 1
    is city "false" actually `string` or `boolean` ? – shyammakwana.me Mar 12 '19 at 13:28
  • I don't know the order of operations for the ternery operator relative to the != "False" statement so you may wish to add a parenthesis to make it explicit. Also, why not just say "" instead of false? – BobtheMagicMoose Mar 12 '19 at 13:34
  • I just found one answer as per your question asked answered by @fra9001[https://stackoverflow.com/questions/31960619/javascript-ternary-operator-with-empty-else/31960809] – Suresh Shetiar Mar 12 '19 at 13:44

3 Answers3

2

Just return empty string ("") instead of false

luthfianto
  • 1,746
  • 3
  • 22
  • 37
0

You could take an empty string as value.

console.log(socket.geoData.hostname + socket.geoData.uri + ": " +
  socket.geoData.country +
  (socket.geoData.city != "false" ? ", " + socket.geoData.city : "")
);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can wrap the code in a if, who checks if the socket.getData.city is != false, before do anything

if(socket.geoData.city !== "false") {
    console.log(`${socket.geoData.hostname}@${socket.geoData.uri}:`);
    console.log(`${socket.geoData.country} - ${socket.geoData.city}`);
}