简体   繁体   中英

What is the difference between (var1 !== var2) vs (var1 && var1 !== var2) in JavaScript?

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

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.

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM