I was reviewing a bit of code the other day and came across a set of syntax I hadn't seen before. It looked like this:
!!{...obj, ...obj2}.item
There are pieces of this code I recognize. But all together? Not so much.
Object Spread
If we go by order of operations the first thing we need to look at is the spread piece of this expression.
{...obj, ...obj2}
Luckily I've written that post before. It's taking two objects and creating a single object with all the unique key value pairs between them.
What comes next?
This was the first thing I needed to figure out. I was pretty confident the next piece of syntax to execute was the .item selector, but I wasn't positive.
Turns out that is correct. Since the result of our spread expression is an object, we're accessing the value of the item key in that object.
To break it down we can write it this way.
const newObj = {...obj, ...obj2}
const item = newObj.item
Bang Bang
This may be the most unfamiliar bit of syntax. ! means NOT in JavaScript, but was does !! mean? It actually means NOT NOT. It's guaranteeing that the result of the expression is always true or false.
I found this article to be the best explanation but I'll try to summarize here.
In JavaScript we have falsy values and truthy values. null, for example, is falsy. That means this statement is true.
!null === true
If we add another ! we discover the expression is equivalent to false.
!!null === false
So !! is telling us whether our expression is truthy or falsy.
All together
Let's look at our original example.
!!{...obj, ...obj2}.item
If we break it down it's doing this.
const newObj = {...obj, ...obj2}
const item = newObj.item
if (item) {
    return true
} else {
    return false
}
The result depends entirely on our objects. Let's look at two options.
Example 1:
const obj = {
    item: null
}
const obj2 = {
    key: "thing"
}
In this case, the expression is false, because null is falsy.
Example 2:
const obj = {
    key: false
}
const obj2 = {
    item: "some value"
}
In this example, the expression is true!  "some value" is truthy.
Pretty cool
What do you think? Not sure how often I'd use it, but it's a neat bit of code. Allows us to look through a number of objects and determine if we have a legitimate value for a particular key.















Now that you have explained it I might use it for personal code but I definitely wouldn't have easily recognized what was going on without this explanation. Soo depending on the team I am working with I might not use it if I think it would confuse others on my team.