简体   繁体   中英

use of ternary operator in javascript

I know basic use of '?' ternary operator. window.URL should be expression, which should return true or false. But in this case, it is returning a string.

how this expression is evaluated.

var createSrc = window.URL ? window.URL.createObjectURL : function(stream) {return stream;};

A string is evaluated to true as long it is not empty, in which case it is false .

Though it doesn't look like window.URL is a string in this case. It appears to be an object, which if undefined will evaluate to false as well.

What your statement does, is it checks if window.URL exists. If it does, then it will assign to createSrc , the value of window.URL.createObjectURL , which I assume is probably a function. Otherwise, it will assign the third part of the ternary operator, function(stream) {return stream;} .

This means, createSrc should always be a function and calling it will not generate an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM