Here is the code snippet:
var prjId = navObj.itemId || navObj
Does this mean that prjId is either equal to navObj.itemId or navObj? What does it then mean that a variable is equal to navigation object?
Thank you in advance for answers!
Here is the code snippet:
var prjId = navObj.itemId || navObj
Does this mean that prjId is either equal to navObj.itemId or navObj? What does it then mean that a variable is equal to navigation object?
Thank you in advance for answers!
If navObj.itemId is set to false or has not been defined at all,
prjId = navObj;
otherwise:
prjId = navObj.itemId;.
No. The || operator first tries to convert navObj.itemId to a Boolean value.
It will be converted to true if it is already the Boolean value, true, a number other than 0 or NaN, a non-empty string, or an object that is not null or undefined. These are known as "truthy" values.
It will be converted to false if it is already the Boolean value false, 0, NaN, an empty string, null or undefined. These are known as "falsey" values.
If navObj.itemId is "truthy", navObj.itemId is assigned to prjId, otherwise navObj is assigned to prjId.
Further Reading
|| operator. If the /quality/ of the left side is truthy, then the variable is set to the /value/ of the left side. If not, the right side is used.|| operator in JS is a kind of simplified version of the ?: operator. x || y is equivalent to x ? x : y. The result is x or y, not the truth values associated with them.It simply means that if the left operand of the logical or operator (||) is a truthy value then return it otherwise return the right operand.
The following values are always falsy:
So if navObj.itemId doesn't evaluate to anything of the above, then it will be assigned to the prjId variable.
This is widely used when we have optional parameters in a function, for example. It is a way of specifying the default value for an optional parameter. But of course that's not the only use of it.