Reputation: 14141
I am trying to put an if statement inside an object but I am not sure if it is possible.
Here is what I am aiming for.
function typed(){
$(".code-animate").typed({
strings: options.typed.strings,
typeSpeed: options.typed.typeSpeed,
backSpeed: options.typed.backSpeed,
contentType: 'text',
loop: true,
if(options.typed.callback)callback: options.typed.callback // this is what I am trying to do
});
}
Upvotes: 3
Views: 61
Reputation: 9399
There are a few ways to achieve what you want:
Ternary operator:
var foo = {
callback: someValue ? someValue : null
}
OR operator (tends to be more elegant than ternary in most simple cases):
var foo = {
callback: someValue || null
}
Post object creation insertion:
var foo = {};
if (someValue) foo.callback = someValue;
Notice that in the two first cases, your object will always have a member called "callback". It will have a null
value if the condition is not met. In the last case, if the condition is not met, your object will not have a member called "callback". You may force your object to have a "callback" with a null value by using an else
statement, if that's convenient for you.
Upvotes: 4
Reputation: 15648
If the goal is to use ternary operator instead of if
, this is the way:
Object.assign(
{
key1: value1,
key2: value2,
},
cond ? {key3: value3} : {}
)
Upvotes: 3
Reputation: 734
You could build the object first, then use this in the typed function:
var params = {
strings: options.typed.strings,
typeSpeed: options.typed.typeSpeed,
backSpeed: options.typed.backSpeed,
contentType: 'text',
loop: true,
}
if( something == true ) { params.test = 'qwerty'; }
$(".code-animate").typed(params);
Upvotes: 2
Reputation: 44444
You can always pull it outside:
var opts = {
strings: options.typed.strings,
typeSpeed: options.typed.typeSpeed,
backSpeed: options.typed.backSpeed,
contentType: 'text',
loop: true,
}
if(options.typed.callback)
opts.callback = options.typed.callback
$(".code-animate").typed(opts);
Upvotes: 4