Y.Solanki Y.Solanki - 1 year ago 63
Javascript Question

Distinguishing between 0 and null in OR statement in Javascript (not a duplication to == vs === as I am looking at not increasing lines of code here)

I have below code in my function, I want to assign a value to the variable newValue.

var newValue = fieldValue || originalValue || masterValue;

Here if I have the originalValue = 0, the java script treats it as false/null and assigns masterValue to the newValue.
Instead I want to assign originalValue (0) to the newValue.

Is there a way to achieve this without an extra line of code?

Answer Source

Yes but it gets a bit complicated (using the ternary operator).

var newValue = fieldValue || (originalValue || originalValue===0) ? originalValue : masterValue;

(this assumes you want to 0 to be assigned even when in fieldValue)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download