简体   繁体   中英

Javascript shorthand syntax explanation

I gone through this syntax in my project. Can I get the explanation for this code please?

 // Handles focus on error title.
 var error = $('#consentError')[0];
 error && error.focus();

Is this the shorthand syntax for if() condition.

Yes, the code is equivalent to

var error = $('#consentError')[0];
if (error) {
  error.focus();
}

The if version is definitely easier to read and comprehend at a glance. Using the && method creates an unused expression, which is weird and is often forbidden by linters.

But jQuery has an even better way to achieve this - just call focus on the jQuery collection, and it'll call .focus() on the native element, if there is such an element (and if there isn't one, it just won't do anything - it won't throw).

$('#consentError').focus();

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