admin管理员组

文章数量:1134241

I have some code with a lot of if/else statements similar to this:

var name = "true";

if (name == "true") {
    var hasName = 'Y';
} else if (name == "false") {
    var hasName = 'N';
};

But is there a way to make these statements shorter? Something like ? "true" : "false" ...

I have some code with a lot of if/else statements similar to this:

var name = "true";

if (name == "true") {
    var hasName = 'Y';
} else if (name == "false") {
    var hasName = 'N';
};

But is there a way to make these statements shorter? Something like ? "true" : "false" ...

Share Improve this question edited Aug 20, 2014 at 15:42 cookie monster 11k4 gold badges33 silver badges45 bronze badges asked Aug 16, 2013 at 8:45 MeekMeek 3,3549 gold badges42 silver badges71 bronze badges 4
  • 7 This has nothing to do with jQuery which is a DOM manipulation library for JavaScript. – Benjamin Gruenbaum Commented Aug 16, 2013 at 8:46
  • 6 Why are you using the word "true", rather than the boolean value true? – Rich Bradshaw Commented Aug 16, 2013 at 8:48
  • 1 possible duplicate of Shorthand if/else statement Javascript – Felix Kling Commented Aug 16, 2013 at 8:49
  • Not my question, sorry. – Meek Commented Aug 16, 2013 at 8:51
Add a comment  | 

8 Answers 8

Reset to default 166

Using the ternary :? operator [spec].

var hasName = (name === 'true') ? 'Y' :'N';

The ternary operator lets us write shorthand if..else statements exactly like you want.

It looks like:

(name === 'true') - our condition

? - the ternary operator itself

'Y' - the result if the condition evaluates to true

'N' - the result if the condition evaluates to false

So in short (question)?(result if true):(result is false) , as you can see - it returns the value of the expression so we can simply assign it to a variable just like in the example above.

You can use an object as a map:

  var hasName = ({
        "true"  : "Y",
        "false" : "N"
  })[name];

This also scales nicely for many options

  var hasName = ({
        "true"          : "Y",
        "false"         : "N",
        "fileNotFound"  : "O"
  })[name];

(Bonus point for people getting the reference)

Note: you should use actual booleans instead of the string value "true" for your variables indicating truth values.

?: Operator

If you want to shorten if/else you can use ?: operator as:

condition ? action-on-true : action-on-false(else)

For instance:

let gender = isMale ? 'Male' : 'Female';

In this case else part is mandatory.

I see this kinda short hand format use for null/undefined checking like:

const avatarName = user.firstname ? user.firstname : user.lastname;

However in this case you can simply use:

const avatarName = user.firstname ?? user.lastname;

or

const avatarName = user.firstname || user.lastname;

To see the difference check this out

&& Operator

In another case, if you have only if condition you can use && operator as:

condition && action;

For instance:

!this.settings && (this.settings = new TableSettings());

FYI: You have to try to avoid using if-else or at least decrease using it and try to replace it with Polymorphism or Inheritance. Go for being Anti-If guy.

Try this

hasName = name ? 'Y' : 'N';

Try like

var hasName = 'N';
if (name == "true") {
    hasName = 'Y';
}

Or even try with ternary operator like

var hasName = (name == "true") ? "Y" : "N" ;

Even simply you can try like

var hasName = (name) ? "Y" : "N" ;

Since name has either Yes or No but iam not sure with it.

Most answers here will work fine if you have just two conditions in your if-else. For more which is I guess what you want, you'll be using arrays. Every names corresponding element in names array you'll have an element in the hasNames array with the exact same index. Then it's a matter of these four lines.

names = "true";
var names = ["true","false","1","2"];
var hasNames = ["Y","N","true","false"];
var intIndex = names.indexOf(name);
hasName = hasNames[intIndex ];

This method could also be implemented using Objects and properties as illustrated by Benjamin.

Try this method;

Shorthand method:

let variable1 = '';

let variable2 = variable1 || 'new'
console.log(variable2); // new

Longhand method:

 let variable1 = 'ya';
 let varibale2;

 if (variable1 !== null || variable1 !== undefined || variable1 !== '')
       variable2 = variable1;

console.log(variable2); // ya

Try This

var name = "true";
var hashname;
     name
      ? hashname = "Y"
      : !name
       ? hashname = "N"
       : ""

     console.log(hashname)

本文标签: javascriptShorthand for ifelse statementStack Overflow