scorpio1441
scorpio1441

Reputation: 3098

Multiple shorthands for if statement?

What is the syntax for multiple if shorthands in JavaScript?

$('#field-'+i+' .name').css({
    top: '30%',
    width: '100%',
    'letter-spacing': i==1 ? '-2.5px' : '-1px',
});

I want letter-spacing to have multiple shorthands like:

'letter-spacing': i==1 ? '-2.5px' i==3 ? '-1.5px' : '-1px'

Upvotes: 1

Views: 144

Answers (6)

Matt Whipple
Matt Whipple

Reputation: 7134

@ChrisFrancis: A tabular ternary variation:

`'letter-spacing': i == 1 ? '-2.5px' 
                 : i == 3 ? '-1.5px'
                 :          '-1px'

Maybe a little confusing in this case with the first ":" meaning something else, but season to taste

Upvotes: 1

Šime Vidas
Šime Vidas

Reputation: 185933

If you have lots of choices, consider a hash:

var hash = {
    1: '-2.5px',
    3: '-1.5px'
};

and then:

'letter-spacing': hash[i] || '-1px'

If your i is an integer, you can use an array, instead of a hash-object. However, the object is more flexible.

Upvotes: 1

jAndy
jAndy

Reputation: 236032

Actually, there is nothing wrong or bad to inline multiple ternery operators if you want to have it in a single line of code, but you could use a more readable style there.

However, my suggestion here is to use a lookup-object or an Array, especially if you have a lot of different states.

var values = ['1px', '-2.5px', '5px', '-1.5px'];

$('#field-'+i+' .name').css({
    top: '30%',
    width: '100%',
    'letter-spacing': values[ i ],
});

Upvotes: 2

chrisfrancis27
chrisfrancis27

Reputation: 4536

It looks like you're talking about nested ternary expressions - I tend to indent like the following:

'letter-spacing': i==1 
    ? '-2.5px' 
    : i==3 
        ? '-1.5px' 
        : '-1px'

Upvotes: 1

cjc343
cjc343

Reputation: 3765

i === 1 ? '-2.5px' : i === 3 ? '-1.5px' : '-1px'

Upvotes: 1

Paul Armstrong
Paul Armstrong

Reputation: 7156

You are just missing a : to finish out your first conditional:

I added some parens to help a little:

'letter-spacing': (i == 1) ? '2.5px' : ((i == 3) ? '-1.5px' : '-1px')

Upvotes: 1

Related Questions