简体   繁体   中英

One-Liner with Return Statement

Is there a way to write the JavaScript code below as a one-liner?

this.isContactPage = (window.location.pathname === '/contact');
if (!this.isContactPage) return false;

The method continues on if this.isContactPage is true.

The property this.isContactPage is needed in other places in the script.

return !(this.isContactPage = (window.location.pathname === '/contact'));

Another example:

console.log(window.prop); // undefined
console.log(!(window.prop = true) || undefined); // undefined
console.log(!(window.prop = true)); // false
console.log(window.prop); // true

It'll be fairly dense and "obscured" code, but you can inline assignments in conditionals:

if ( !this.isContactPage = ( window.location.pathname == '/contact' ) ) return false;

This will only return the function if this.isContactPage is assigned the value false otherwise the function is not returned and continues on execution, as opposed to:

return ( this.isContactPage = ( window.location.pathname == '/contact' ) );

Which will return true or false immediately.

return !this.isContactPage = (window.location.pathname === '/contact')

with this you will not have errors!

this.isContactPage = /contact/gi.test(window.location.pathname);
if (!this.isContactPage) return false;

or

return !(/contact/gi.test(window.location.pathname))

I have something makes your code as short as possible!

return !(this.isContactPage=location.pathname=='/contact')
  1. You don't need "Window"
  2. You don't need returning false or true directly through your code
  3. You don't need ===, then change it to == The shortest way guys suggested has 88 letters and this suggestion has just 68 letter and is more readable and understandable!

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