Is there a "global function" or a "main function" in Javascript? - 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

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";

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.

There is no global function in JavaScript, but there are some similar concepts:
The Global Environment (10.2.3)
The global environment is a unique Lexical Environment which is
created before any ECMAScript code is executed. The global
environment’s Environment Record is an object environment
record whose binding object is the global object (15.1). The
global environment’s outer environment reference is null.
The Global Object (15.1)
An unique object used as the binding of the environment record of the global environment.
Global Code (10.4.1, 10.1)
Global code is source text that is treated as an ECMAScript Program. The global code of a particular Program does not include any source text that is parsed as part of a FunctionBody.
Global Execution Context (10.4.1.1)
An execution context of global code.

Here is a link to video.. watch this he explains how javascript works.
link to the video
And tool to visualize how JavaScript works.
link to the tool
In case if you want to run after the window is loaded there is window.onload , $(document).ready(); if you are using Jquery.

No, javascript is a scripting language, there is no point of insertion.
Lines of code are executed in the order they are encountered by the javascript interpreter.
If multiple files are included on the page, the functions and variables declared in them will be added to the global scope (unless they are declared in an anonymous function)

Related

How does Javascript runtime identify setTimeout() as a WEB API?

When javascript runtime finds setTimeout() method, it sends it to Event table. How does runtime know that setTimeout() is a WEB API? Does it first look for setTimeout() method in the current context and then if not found assumes it as a WEB API?
When javascript runtime finds setTimeout() method, it sends it to Event table.
JavaScript doesn't "know" or care what setTimeout does. :-) It's just that setTimeout is one of the functions defined in the host environment provided to the JavaScript engine by the host (the browser, in your example). When you use JavaScript to call the function, the function's implementation (provided by the host environment) is executed with the information you provide. It's the host, not the JavaScript engine, that knows what to do with the arguments you provide to setTimeout.
When the host (the browser or Node.js or whatever) needs to create a new runtime environment (for instance, for a window), one of the things it does is create an object to be the host-provided global object for that environment (more properly called a realm), including putting any properties on that object (like setTimeout) that provide host-defined features. It provides that object to the JavaScript engine via what the JavaScript specification calls the InitializeHostDefinedRealm abstract operation. When the JavaScript engine runs your code that uses setTimeout, it sees the identifier setTimeout and looks in the current execution context to see if setTimeout is defined there; if it isn't, the engine looks at the parent execution context, and so on, until it reaches the global execution context, which gets its globals from the host-provided global environment (in part; it also has other globals). So, having found the function matching setTimeout, the JavaScript engine calls that function — which runs the host-defined code for the function, which sets the timer.
So the JavaScript engine doesn't know what setTimeout does, just that there is a setTimeout function on the global object it got from the host.
In terms of identifying which function to run, it doesn't make any difference whether a function is built into the engine, or added at run-time (this fact is really useful, allowing functions to be "polyfilled" if the engine doesn't provide them).
When you write foo(), JS actually looks for a variable with that name (this unification of variables, properties, functions and methods is an unusual feature of JS). It looks for it first in the local scope, then in the parent of that scope, and so on up the "scope chain".
The last place it looks is the "global object", which in a browser is the window object. So if you define window.foo as a function, you can call foo() from anywhere that doesn't have its own function called foo in scope.
Built-in functions work just the same way: when the JS engine starts up, it (conceptually) defines a whole bunch of functions on the window object, with special implementations referring to internal operations in the engine rather than composed of JS code.
So when you call setTimeout, JS walks up the scope chain, and if it doesn't find anything else, will find the setTimeout function registered by the engine, and runs it. The engine then does whatever it wants to do with that - hopefully, something that complies with the behaviours described in the current ECMAScript standard.

How does the 'window' object become the global object of a front end JS script?

Hello Stackoverflow community!
I kind of know what the window and global object is, but I would like to know how this works under the hood / behind the scene.
How does the browser add this window object as the global object to our script and why?
Thanks
Creation phaase a.k.a Global Execution Context.
When running code at the base level, JS engine will automatically do the following:
Create a global object, which means all your code will sit inside of this global object. If you are using in browser environment, this global object is window. It all depends on where do you execute your JS code.
Create a special variable called "this". At the global level, "this" would equal the Global (window) Object.
A reference to the outer environment if there is one. This means where something sits physically in the code you write and what's around it, a.k.a Lexical Environment

If code is placed within an anonymous function, why can I access it from the console?

I've noticed that Meteor's production ready code is concatenated, minified, and then wrapped in an anonymous function.
In theory, this should make the Meteor object and its methods inaccessible through the DOM / window object / console.
Why can I still access objects placed within an anonymous function through the console?
Javascript is function scoped, which means the outer function variables are accessible (and editable!) by inner functions. This goes all the way up to global (window) variables. For example:
(function() {
window.t ='foo';
})();
If you run that code in the console, then see what t is, you'll see you created/changed it from within the function. Meteor globally scopes a few variables (Meteor, check, etc.) so you can access them, in addition to any variables you scope yourself when you create a package. This is because each .js file is also an anonymous function & if you didn't export some variables, you'd have to write everything in 1 big file. By only exporting the variables you need, your project stays modular. Hope this helps!

Break the encapsulation of immediately executed anonymous functions?

A common Javascript pattern is:
(function() {
var localScopedValue = "foobar";
// code... functions...
}());
The self-executing or immediately executed anonymous function creates a scope for everything inside it to prevent pollution of the global scope, and it also theoretically prevents anyone from getting references to either the function object or anything defined inside it from an outside script, browser console, etc. That's the idea, anyway.
However, Javascript being a dynamic language with reflection, etc., I am wondering if there is any way -- no matter how hackish (but not editing any existing code) -- of getting references to locals that are not deliberately exposed from Javascript code.
Reason: pure curiosity / breaking things.
Adding: Things I'm looking at include Function.caller and event listeners, basically anything where items inside the IIFE are known to call/hook out, but I can't put together the complete package.
JS doesn't have "real" reflection - all it has is the ability to access the properties of an object using a variable as a key with myObject[myVar] syntax instead of myObject.myProperty.
This therefore provides no access to lexically scoped private variables.

How many JavaScript programs are executed for a single web-page in the browser?

JavaScript programs consist of statements and function declarations. When a JavaScript program is executed, these two steps occur:
the code is scanned for function declarations, and every func. declaration is "executed" (by creating a function object) and a named reference to that function is created (so that this function can be called from within a statement)
the statements are executed (evaluated) sequentially (as they appear in the code)
Because of that, this works just fine:
<script>
foo();
function foo() {
return;
}
</script>
Although the "foo" function is called before it is declared, it works because the function declaration is evaluated before the statement.
However, this does not work:
<script>
foo();
</script>
<script>
function foo() {
return;
}
</script>
A ReferenceError will be thrown ("foo is not defined").
This leads to the conclusion that every SCRIPT element inside the HTML code of the web-page represents a separate JavaScript program and every time the HTML parser encounters a SCRIPT element, it executes the program inside that element (and then once the program is executed, the parser moves on to the HTML code that follows the SCRIPT element).
Then again, this does work:
<script>
function foo() {
return;
}
</script>
<script>
foo();
</script>
My understanding here is that the Global object (which serves as the Variable object in the global execution context) exists (and remains) at all times, so the first JavaScript program will create the function object and make a reference for it, and then the second JavaScript program will use that reference to call the function. Therefore, all JavaScript programs (within a single web-page) "use" the same Global object, and all changes done to the Global object by one JavaScript program can be observed by all JavaScript programs that run subsequently.
Now, note this...
<script>
// assuming that foo is not defined
foo();
alert(1);
</script>
In the above case, the alert call will not execute, because the "foo()" statement throws a ReferenceError (which breaks the whole JavaScript program) and therefore, all subsequent statements do not execute.
However, in this case...
<script>
// assuming that foo is not defined
foo();
</script>
<script>
alert(1);
</script>
Now, the alert call does get executed. The first JavaScript program throws a ReferenceError (and as a consequence breaks), but the second JavaScript program runs normally. Of course, the browser will report the error (although it did execute subsequent JavaScript programs, after the error occurred).
Now, my conclusions are:
every SCRIPT element within the HTML code of the web-page represents a separate JavaScript program. These programs execute immediately as the HTML parser encounters them.
all JavaScript programs within the same web-page "use" the same Global object. That Global object exists at all times (from the moment the web-page is fetched up until the web-page is destroyed). JavaScript programs may manipulate the Global object, and all changes done to the Global object by one JavaScript program can be observed in all subsequent JavaScript programs.
if one JavaScript program breaks (by having an error thrown), that does not prevent subsequent JavaScript programs to execute.
Please fact-check this post and tell me if I got something wrong.
Also, I have not found resources that explain the behaviors mentioned in this post, and I assume that the browser makers must have published such resources somewhere, so if you know about them, please provide the links to them.
Function hoisting — the process that evaluates function statements before the rest of the function — is part of the ECMAScript standard IIRC (I can't find a reference right now, but I recall seeing discussions of EMCAScript that mention it). The evaluation of script tags is part of the HTML standard. It does not specify that they are "separate programs" in so many words, but it does say that the script elements are evaluated in the order they appear in the document. That is why functions in later script tags aren't hoisted: The script hasn't been evaluated yet. That also explains why one script stopping doesn't cut off subsequent scripts: When the current script stops evaluating, the next one starts.
Dmitry Soshnikov has answered your question. Every <script> element is executed as a Program, as defined by the ECMAScript specification. There is one global object that each Program within a single page uses. And that's really it.
They are separate programs, but they modify a shared global object.
Another way to think about this is pseudo local vs global scope. Every SCRIPT declaration has a local scope to it's current methods/functions, as well as access to the current (previously declared) global scope. Whenever a method/function is defined in a SCRIPT block, it is then added to the global scope and becomes accessible by the SCRIPT blocks after it.
Also, here's a further reference from W3C on script declaration/handling/modification:
The dynamic modification of a document
may be modeled as follows:
All SCRIPT elements are evaluated in order as the document is loaded.
All script constructs within a given SCRIPT element that generate
SGML CDATA are evaluated. Their
combined generated text is inserted in
the document in place of the SCRIPT
element.
The generated CDATA is re-evaluated.
This is another good resource on script/function evaluation/declaration.

Categories

Resources