Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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

like image 274
FurtiveFelon Avatar asked Oct 13 '09 01:10

FurtiveFelon


People also ask

What does a function return if it has no return statement in it JavaScript?

If no return value is specified, JavaScript will return undefined . In many languages the result of the last statement is returned (more useful, IMO). These are called implicit returns.

What does a JavaScript function return?

Usually, the JavaScript functions returns a single value, but we can return multiple values by using the array or object. To return multiple values, we can pack the values as the object's properties or array elements.

What is empty return statement in JavaScript?

"Blank return" statements can be used to transfer the control back to the calling function (or stop executing a function for some reason - ex: validations etc). In most cases I use blank return statement is when I'm doing some kind of a validation.

What happens when JavaScript function reaches a return statement?

Function Return When JavaScript reaches a return statement, the function will stop executing. If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.


1 Answers

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' 
like image 164
Christian C. Salvadó Avatar answered Sep 23 '22 18:09

Christian C. Salvadó