chris
chris

Reputation: 605

Is this javascript syntactically correct or is there a better way?

Basically if a variable isn't set then set it to another value.

There must be a better way, this looks so messy.

        if ($image_src === undefined) {
                $image_src = $apple_icon;
            }

            if ($image_src === undefined) {
                $image_src = $apple_icon2;
            }

            if ($image_src === undefined) {
                $image_src = $item_prop_image;
            }

            if ($image_src === undefined) {
                $image_src = $image_first;
            }

Upvotes: 4

Views: 198

Answers (4)

Joe Enos
Joe Enos

Reputation: 40393

Expanding on my comment - just in case you do have the scenario where one of the variables may not have been declared, you can do something like the following - harder to read, but safer:

$image_src = getWhateverTheInitialValueIsSupposedToBe();

$image_src = $image_src || (
    (typeof($apple_icon) !== "undefined" && $apple_icon) ? $apple_icon :
    (typeof($apple_icon2) !== "undefined" && $apple_icon2) ? $apple_icon2 :
    (typeof($item_prop_image) !== "undefined" && $item_prop_image) ? $item_prop_image :
    (typeof($image_first) !== "undefined" && $image_first) ? $image_first :
    $image_src);

Upvotes: 1

John
John

Reputation: 16007

Honestly, I think the way you've written it shows clearly what you want to do.

You can make it more compact through the ways shown in the other answers, but I find the way you wrote it is more readily understandable at first glance than the others IMO.

It all depends on what you want. The || method is probably more efficient, but yours is quite readable.

Wrapping this in a function would be fine.

Upvotes: 0

g.d.d.c
g.d.d.c

Reputation: 47978

In JavaScript you can use the or || operator to condense things that are undefined. So this is valid:

$image_src = $image_src || $apple_icon || $apple_icon1;

Upvotes: 10

Brad
Brad

Reputation: 163334

$image_src = $image_src || $apple_icon;

http://billhiggins.us/blog/2007/02/13/the-javascript-logical-or-assignment-idiom/

Upvotes: 4

Related Questions