57

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

FurtiveFelon
  • 12,838
  • 27
  • 72
  • 96
  • 2
    JavaScript also has a second value that indicates absence of value. The undefined value represents a deeper kind of absence. It is the value of variables that have not been initialized and the value you get when you query the value of an object property or array element that does not exist. The undefined value is also returned by functions that have no return value, and the value of function parameters for which no argument is supplied. undefined is a predefined global variable – Xsi May 03 '14 at 12:22

3 Answers3

71

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'
Christian C. Salvadó
  • 723,813
  • 173
  • 899
  • 828
3
<html>
<body>
<script>
function a() {}
alert(a());
</script>
</body>
</html>
1

to find out, try this in firebug console:

alert((function(){})());
Scott Evernden
  • 35,319
  • 14
  • 75
  • 83