Reputation: 1
Can someone explain this JS LINE ? data is an object.
var list = data == null ? [] : (data.wine instanceof Array ? data.wine : [data.wine]);
Upvotes: 0
Views: 3008
Reputation: 30648
its conditional operator in javascript
Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. Syntax
variablename=(condition)?value1:value2
var variablename;
if(condition true){
variablename=value1;
}
else{
variablename=value1;
}
evaluation of your code is as follow:
var list;
if (data == null) {
list = [];
} else {
if (data.wine instanceof Array) {
list = data.wine;
} else {
list = [data.wine];
}
}
Upvotes: 0
Reputation: 66663
It means:
If data is null
assign an empty array to list
else
if data.wine is of type Array
assign data.wine to list
else
create an array with data.wine as the only item and assign that array to list
end
end
Upvotes: 1
Reputation: 7021
if (data == null) {
list = []
} else {
if (data.wine instanceof Array) {
list = data.wine
else {
list = [data.wine];
}
}
Upvotes: 1
Reputation: 75317
It is basically this;
var list;
if (data == null) {
list = [];
} else {
if (data.wine instanceof Array) {
list = data.wine;
} else {
list = [data.wine];
}
}
It consists of nested ternary operators. A ternary operator is of the form;
x ? y : z
Which evaluates x
, and returns y
if it is truthy, otherwise it returns z
.
Upvotes: 3
Reputation: 34632
As an if-else statement:
if (data == null)
list = []; // list is an empty array now
else if (data.wine instanceof Array)
list = data.wine; // data.wine is an array; assign it to list
else
list = [data.wine]; // make a new array with data.wine as element
Upvotes: 0