-3

Is it possible to shorten this code?

var access_followup = user_access && user_access.followup && user_access.followup.access ? true : false;
clarkk
  • 27,151
  • 72
  • 200
  • 340
  • 2
    `var access_followup = user_access && user_access.followup && user_access.followup.access;`: probably not what you wanted, but it is _technically_ shorter. – tklg Jan 21 '17 at 22:03

4 Answers4

1

Maybe I am answering the wrong thing, but why would you want to make it shorter? I'd vote to make it a bit longer, but easier to read for people who work with your code ( including you :) ).

You could make it more readable by splitting it up into multiple lines:

var access_followup = (
 user_access &&
 user_access.followup &&
 user_access.followup.access === true // if access is a boolean value
);

Or, in case you really really want to have short code and you do not use a minifier already, you can try https://jscompress.com/ (which actually compresses any code you paste into it! but makes it WAY less readable).

Angelo Michel
  • 265
  • 1
  • 5
1

Unfortunately JS does not have a null conditional operator. You could write helper function for it or use a slightly less effective method of creating dummy objects:

var access_followup = !!((user_access || {}).followup || {}).access;

which is shorter and prevents using the property names more than once, but doesn't improve readability. The !! is used to enforce a boolean value even when the values don't exist

Me.Name
  • 12,259
  • 3
  • 31
  • 48
0

If the first 2 checks are because you are protecting against exception thrown when user_access.followup is undefined, you can try this:

var accessFollowup;
try {
  accessFollowup = !!user_access.followup.access;
} catch (e) {
  accessFollowup = false; 
}

You could also shorten by removing just the ternary by using !! to force last element into Boolean value:

var access_followup = !!user_access && !!user_access.followup && !!user_access.followup.access
hackerrdave
  • 6,486
  • 1
  • 25
  • 29
0

very ugly code that works

var access_followup = (followup = (user_access || {}).followup) && followup.access;
Sagi
  • 8,972
  • 3
  • 33
  • 41