Reputation: 1
What is the difference between (var1 !== var2)
vs (var1 && var1 !== var2)
in JavaScript?
The above question is in reference to when working with HTMLElementObjects as variables.
Google Chrome's extension development example shows this in the below function:
let current = event.target.parentElement.querySelector(
`.${selectedClassName}`
);
if (current && current !== event.target) {
current.classList.remove(selectedClassName);
}
let color = event.target.dataset.color;
event.target.classList.add(selectedClassName);
chrome.storage.sync.set({ color });
}
Why does it have to be "current && current"? It doesn't work with just "current !== event.target"
Link to full article for reference: https://developer.chrome.com/docs/extensions/mv3/getstarted/#logic
Upvotes: 0
Views: 344
Reputation: 110
The first Var checking in var && var...
is checking if var is not null or undefined and then compare It with var2
In fact, you could write It like that :
If (var !== null || var !== undefined || var !== false) {
return var !== var2
}
Upvotes: -1
Reputation: 593
This is because of JavaScript's operator precedence:
11: Strict Inequality (
!==
)
...
7: Logical AND (&&
)
Since strict inequality has a higher precedence than logical AND, it's functionally equivalent to the following:
(current) && (current !== event.target)
The people who wrote the tutorial likely did not want this expression to evaluate as true if current
was any kind of falsey value. By doing this, they ensure that event.target
can't just be any old value and still pass.
Upvotes: 2
Reputation: 3805
What it does is checks if current is truthy AND is not equal to event.target. If event.target and current are both null it will still return false
Upvotes: 1