Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a "global function" or a "main function" in Javascript?

For me variables are easy to understand in Javascript: if a variable is not in local scope then it is a field in the global object.

But what about Javascript commands? If i just write Javascript commands in a file (outside any function) then how will the Javascript engine interpret it?

----- file.js -----
console.log('hai:DDD');
--- end of file ---

Will it create some kind of "global" or "main" function type object with the commands and then execute it? What if there are multiple files with code?

I guess this question only applies to node.js because in browsers all Javascript code is event handlers

like image 672
Kaarel Purde Avatar asked Dec 19 '22 19:12

Kaarel Purde


2 Answers

Javascript does not have a main function. It starts at the top and works it's way down to the bottom.

In Node.js, variables are stored in the module scope which basically means they're not quite global. In a way, you could imagine any code you run in Node.js as being wrapped up like this:

(function(exports, require, module, __filename, __dirname) {
   ...
})();

But you seem to have a misconception about the browser. Not all JS code is an event handler in the browser. If you just run a basic script in the browser it will also populate the global scope.

var myGlobal = "I'm available to everyone";
like image 71
Mike Cluck Avatar answered Feb 16 '23 03:02

Mike Cluck


Javascript is, as the name implies, a scripting language to be interpreted by some Javascript interpreter. Thus, the "main function" can be thought of as the whole file, the entry point is at the first character of the first line in the script. Typically, the entirety of the functions the script is to perform are wrapped in a function that loads with the page, but this isn't necessary, just convenient.

like image 28
ocket8888 Avatar answered Feb 16 '23 03:02

ocket8888