4 ms·
var aCoolFunction = undefined; aCoolFunction && aCoolFunction(); What is the purpose of this?
by Kiro 12y ago
var aCoolFunction = undefined;
aCoolFunction && aCoolFunction();
What is the purpose of this?
- berzniz 12y agovar getJSON = function(callback) { // did async work to get the JSON data and now I want to call the callback function, but is it there? callback && callback(data); }; getJSON(); // See how I don't care about the result
- lnanek2 12y agoIf the function doesn't exist, don't do anything. aCoolFunction is false so the other half of the statement won't execute. If it does exist, call it. Useless as written, but there may be cases where you don't know if it is defined or not when you want to call it.
- nmjohn 12y agoVery few practical purposes. It was already described what it does - but the thing is, why would you ever want that? If a function is coming up undefined that I expect to be defined, that's an issue - not one I want to fail silently - because that is no fun to debug. If something I expect to be defined isn't, that should throw an error and stop execution. There are some edge cases where it may not matter and there is a legit reason why a function may sometimes be undefined, but I've never written code like that and can't think of anything that doesn't have a much better alternative.