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

Basically, if a variable is not set, set it to a different value.

There must be a better way, it looks so dirty.

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; } 
+4
source share
4 answers

In JavaScript, you can use the or || operator to compact things that are undefined. So it really is:

 $image_src = $image_src || $apple_icon || $apple_icon1; 
+10
source
+4
source

An extension of my comment - just in case, if you have a script in which one of the variables cannot be declared, you can do something like the following - it is 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); 
+1
source

Honestly, I think the way you wrote it clearly shows what you want to do.

You can make it more compact using the methods shown in other answers, but I find how you wrote it is easier to understand at first glance than other IMOs.

It all depends on what you want. Method || probably more effective, but your reader is quite readable.

Wrapping this in a function will be fine.

0
source

Source: https://habr.com/ru/post/1444673/


All Articles