user900276
user900276

Reputation: 1

Javascript test and assignation in one line

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

Answers (5)

Hemant Metalia
Hemant Metalia

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

techfoobar
techfoobar

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

ustun
ustun

Reputation: 7021

if (data == null) {
    list = [] 
} else {
    if (data.wine instanceof Array) {
        list = data.wine 
     else {
        list = [data.wine];
     }
}

Upvotes: 1

Matt
Matt

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

Linus Kleen
Linus Kleen

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

Related Questions