Reputation: 1198
return
keyword in Javascript scripts, outside of functions, in browsers and Node?I have tried using it in a Node script as follows:
#!/usr/bin/env node
return 10;
My expectation was that this would make the return status of the process be equal to 10
. However, upon asking the return status of the last utility ran under bash
, by echo $?
, I would receive 0
, so that is not the case.
This woke my curiosity upon what else does return
ing in the middle of a Node module, apart from terminating execution, does. Also, I wonder what happens in the context of browser <script>
s.
Thanks beforehand.
Upvotes: 3
Views: 1607
Reputation: 707736
This woke my curiosity upon what else does returning in the middle of a Node module, apart from terminating execution, does.
When you run a Javascript script file with node.js, it is wrapped in a module wrapper function as you can see here in the node.js docs for Modules.
(function (exports, require, module, __filename, __dirname) {
// Your module code actually lives in here
});
So, your return
is a return from that module wrapper function and it does nothing except stop the execution of any further code in that module. Modules in node.js don't have any documented behavior for returning a value from the module. So, return;
or return 10;
or no return
value at all, all have the same behavior. The return value is not used.
As always in a Javascript function, you could use a plain return
to skip the execution of the rest of the code in the module, though it is probably better to just use an if/else to more clearly execute only the code you want to execute.
My expectation was that this would make the return status of the process be equal to 10. However, upon asking the return status of the last utility ran under bash, by echo $?, I would receive 0, so that is not the case.
If you want to set a return value for the process, you should use:
process.exit(10);
In node modules, if you want to share data with other modules, you can use module.exports = some object or value
, but that has no effect on the main module since the node loader is not paying any attention to either the return value of the module.exports
from the main module. That is only useful with other modules that you explicitly require()
in.
Also, I wonder what happens in the context of browser
<script>s
.
Using a return
statement at the global level (which is what the top level of a browser <script>
tag would be is not permitted by the language. return
is only appropriate inside a function. Doing so generates this error:
Uncaught SyntaxError: Illegal return statement
Upvotes: 4