What does javascript function return in the absence of a return statement?

Javascript

Javascript Problem Overview


I was just wondering, does a function without a return statement (or without hitting any return statements) return a value that is completely equivalent to false?

For example:

function foo(){};
!!foo();

This should return false if executed in firebug (but does not return anything if i just called foo();).

Thanks a lot!

Jason

Javascript Solutions


Solution 1 - Javascript

A function without a return statement (or one that ends its execution without hitting one) will return undefined.

And if you use the unary negation operator twice on an undefined value, you will get false.

You are not seeing anything on the console because Firebug doesn't prints the result of an expression when it's undefined (just try typing undefined; at the console, and you will see nothing).

However if you call the console.log function directly, and you will be able to see it:

function foo(){}

console.log(foo()); // will show 'undefined'

Solution 2 - Javascript

<html>
<body>
<script>
function a() {}
alert(a());
</script>
</body>
</html>

Solution 3 - Javascript

to find out, try this in firebug console:

alert((function(){})());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFurtiveFelonView Question on Stackoverflow
Solution 1 - JavascriptChristian C. SalvadóView Answer on Stackoverflow
Solution 2 - Javascriptuser181548View Answer on Stackoverflow
Solution 3 - JavascriptScott EverndenView Answer on Stackoverflow