I have a function that goes something like
//denominator is a passed argument. Integer
/*priceData will either be an empty array, or an array
that looks something like this
priceData = {
'splitBy2' : [0.5, 0.5],
'splitBy3' : [0.34, 0.33,0.33],
'splitBy4': [0.25, 0.25, 0.25, 0.25]
}
*/
//Returns list of values. Currency distribution. Eg if denominator = 3
//Then distribution will equal [0.34, 0.33,0.33]
distribution = distributionToArray(currency(totalPrice).distribute(denominator))
//This check doesn't work.
if(typeof (priceData['splitBy'+denominator]) !== 'undefined' && (priceData['splitBy'+denominator]).length == 0){
priceData['splitBy'+denominator] = distribution;
}
What I want to do is check if priceData['splitBy'+denominator]
is empty. And if it isn't, create it.
So let
denominator=5
priceData = {
'splitBy2' : [0.5, 0.5],
'splitBy3' : [0.34, 0.33,0.33],
'splitBy4': [0.25, 0.25, 0.25, 0.25]
}
I want to check if priceData['splitBy5'] is set, and if it's not, run the rest of the function priceData['splitBy5
] = distribution;` to create it. Even if priceData is empty.
1 Answer 1
You've shown this code:
if(typeof (priceData['splitBy'+denominator]) !== 'undefined' && (priceData['splitBy'+denominator]).length == 0){
priceData['splitBy'+denominator] = distribution;
}
and that should certainly work if the property A) Either doesn't exist or has the value undefined
, or B) Has an array.
What I want to do is check if
priceData['splitBy'+denominator]
is empty. And if it isn't, create it.
Your code should do that. But since an array (even an empty one) is a truthy value, you can do:
const key = "splitBy" + denominator;
if (!priceData[key] || priceData[key].length === 0) {
priceData[key] = distribution;
}
!priceData[key]
looks to see if the property doesn't exist (or has a falsy value; no array is falsy). priceData[key].length === 0
checks to see if the array is empty. Since they're joined with ||
("or"), if the first check is true the second isn't performed and so won't cause an error.
The two key (no pun!) changes there are:
Building the key once. This is purely so that we avoid typos like
splitby
instead ofsplitBy
in one of the three places it would be used.Using a falsy rather than
undefined
check.
But if you know the property won't be there, will have the value undefined
, or will be an array, your code should work. All of the 'splitBy'+denominator
concatenations look like they're spelled the same, and the typeof
check is correct (and doesn't misspell undefined
, which is my particular bugaboo). You don't need any of those inner ()
, but they don't do any harm.
4 Comments
key
with "splitBy" + denominator
in all three places in the if
and it would be just the same. Something else must have been going on. Is there some possibility that the property's value is some falsy value that isn't undefined
(like null
, ""
, 0
, NaN
, or false
)?