Non
Non

Reputation: 8589

From a JSON object: '0' is false?

I am getting a JSON object with this properties

id: "23132772"
isAvailable: "1",
isSelected: "0",
maxPoints: "0",
minPoints: "0",
name: "Parlay",
placeBetIsAvailable: "0"

this JSON comes from an object named betType

so lets say I want to work with placeBetIsAvailable when it is false.

As you see, there I have placeBetIsAvailable: "0"

so, in my code, am I able to do:

if(!betType.placeBetIsAvailable) ?

or should I specify

if(betType.placeBetIsAvailable === '0') ?

Upvotes: 2

Views: 1389

Answers (4)

abs
abs

Reputation: 801

Try converting it to number and use ! to convert it to boolean

if(!!Number(betType.placeBetIsAvailable))

Upvotes: 1

damix911
damix911

Reputation: 4443

The construct if(!betType.placeBetIsAvailable) is inappropriate if you are using the strings "0" and "1" to encode true and false. Type this in your address bar to see why.

javascript:alert(["0", !"0", "1", !"1"])

Basically, !"0" and !"1" both evaluate to false.

If you really cannot do anything about the JSON returned by the server, you should use the form if(betType.placeBetIsAvailable === '0').

Upvotes: 1

ijsnow
ijsnow

Reputation: 162

If it were a number and not a string you could do that, but since it is a string with character in the string(not empty string ''), it is no longer falsey. To fix this you could do this

if(!parseInt(betType.placeBetIsAvailable)) 

or

if(!+betType.placeBetIsAvailable)

which is probably more work than just doing

if(betType.placeBetIsAvailable === '0')

Upvotes: 1

Pointy
Pointy

Reputation: 413720

The string "0" is truthy in JavaScript, while the number 0 is not. If your JSON is being encoded with zeros in quotes, then they're non-empty strings.

Upvotes: 5

Related Questions