I am watching a course where the professor mentions a local execution context being created every time we execute a function created by ourselves (he does not says exactly that, however he does not mentions this when he explains external functions like setTimeOut or fetch). However what happens when we call an external function (like setTimeOut or fetch) does javascript creates a local execution context for this functions too? What I mean by external functions is functions not created by ourself but part of an API.
Most external functions for javascript are actually written in C, so they don't have a javascript execution context per se. However, they still have a stack frame, which is similar to what a javascript execution context is.
Related
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.
I just realize that I can use the function console.log to read a codebase of any javascript function. Anyone how it happens? and what behind the sense of this action (read codebase)
Example:
Open chrome console and paste this code
function superMan(){
var i=i+1;
var j=i+1;
}
then you use the function console.log like console.log(superMan) and you can see the codebase of SuperMan
In javascript, When a program is run a execution context is created. There are 2 phases in which its created namely below.
Creation phase
Execution phase
What you are referring to in the question is mostly related to the creation phase. In this phase all the variables are declared and initialized to undefined ( incase of var) and for variables with let and const they are declared in the Temporal Dead Zone and are unreachable and only reachable when the code is executed in execution context.
For functions(specifically Function statements and not function expressions) these are taken in as it is in memory and stored. So, when you try to log in the function in console.log it shows the variable in memory. This will be also true for function expression once the execution runs over it(since before its treated like a normal variable and not function). They will be showed as it will now be pointing to the function directly assigned to that variable. Also, You need to understand function in Javascript are first-class functions meaning it can be passed and treated like a normal variable (containing a number) and so.
It's part of the spec but a good reason to use it is in edge-cases where the code of the function could be important to its execution (usually for an API, interface or some form of abstraction) where you need to know a bit more about the function before acting upon it. There are many use-cases, but it can be particularly useful to try to detect and handle edge-cases for a transpiler (the code you write isn't verbatim to the code that the browser sees)
I was learning JS and execution contexts. Also, I found out that there is a special execution context which is executed by default which is fglobal execution context. The question is "Is global execution context a function which is executed behind the scenes"?
It's not a function, it's an abstraction that holds certain information about the context within which javascript is running. It is set up by the javascript engine before it starts to execute any code so it is created by a "function behind the scenes", but it is not itself a function. In the browser, the globsal execution context will include various functions and objects (like the document object). In node on the server, it will be something different. It is closely related to the global scope, but execution context and scope are not identical. It's quite a complex subject, so you may want to read this for more information: https://codeburst.io/js-demystified-04-execution-context-97dea52c8ac6
Consider the following function being executed,
function loadPage()
{
takeInput();
processInput();
outputInput();
}
In what order would they be executed(I have read that it follows stack so option 2 will be the answer)?
Option #1
takeInput();
processInput();
outputInput();
Option #2
outputInput();
processInput();
takeInput();
JavaScript functions are not asynchronous. Some very limited set of functions have an asynchronous API:
addEventListener, setTimeout, setInterval. These are the only 3 (which I thought was very surprising).
They allow you to pass in a callback that may get called eventually. Such as when a timer expires, or when a user clicks on something, or when an AJAX request completes.
JavaScript has an event loop. The event loop processes each event as it comes in. If you click a button 3 times and then a timer expires that will also be the order the events are handled. It is all very well defined and determined.
Furthermore, JavaScript doesn't have threads, it runs one event completely till there is nothing left to do (you return) before starting the next event. So events will never interfere in any way. This allows you to make very strong assumptions about the state of your data.
Are JavaScript functions asynchronous?
Some are, most are not.
In what order would they be executed
They will be executed in the order in which they are called. Since they are are all called from the same function, that will be in a simple linear order.
If any of them are written in an asynchronous way, then they might not finish all their activity in the same order. For example:
function a() {
console.log('a');
}
function b() {
console.log('b');
}
function c() {
console.log('c');
}
function aAsync() {
setTimeout(a, 500);
}
function load() {
aAsync();
b();
c();
}
load();
Javascript is not Asynchronous. It works Synchronously ,that is it runs one line of code at a time.
When javascript code is run , first a Global execution context is created and if you call a function from global execution context, another execution context is created by the javascript engine and that is placed at the top of the execution stack (global execution context is already in the stack)and if there is another function being called from inside that function ,another execution context is created and stack size keeps on increasing.
So,javascript engine keeps running this code one line at a time and in that process if there is any event/ http request fires, the browser puts them in the EVENT QUEUE. So, the point is javascript engine wont process the events in queue until the execution stack is empty.
And when the engine is done with the execution stack, it periodically looks if there is any event handler for current event in queue and similarly creates execution context for that handler and runs the code within.
So, the whole process is just synchronous and asynchronousity is just handled by the other parts of browser like(rendering engine or http engine) while the javascript engine continues to run the code synchronously.
So, in your case,
from whichever context function loadpage was invoked , its execution context was created and and placed at the top of the stack. Then, it invokes the takeinput function, its exec. context is created and and other functions context will not be created and placed in the stack until the takeinput context is popped out from the execution stack.
So, the correct order will be takeinput, processinput and outputinput.
I hope it answers your question.
JavaScript is not, generally asynchronous, but it does have asynchronous and event driven methods.
Ajax calls are the big asynchronous methods.
For events, I'm not sure that you can be guaranteed about an order of execution, but I might be wrong about that.
No, not by default/as standard, though there are asynchronous methods. And jQuery makes use of asynchronous behaviour much more so. But in each case, it's subjective, and can't be said that "All of the JavaScript is this or that".
Methods are always executed in the order they are called; the asynchronousness of them means that any may complete before another, even if called afterwards.
Javascript is a single-threaded beast, so strictly speaking tasks are not asynchronous as one might think of in terms of spawning child threads to execute code. The mechanisms that provide this create the illusion of asynchronicity, but its still single-threaded.
In case you don't know what I'm talking about, please read John Resig - How JavaScript Timers Work and Is JavaScript guaranteed to be single-threaded?
There are several triggers that enqueue tasks in the JS engines' execution FiFo. This is not part of any standard, so I'm trying to find an exhausive list of those triggers. (I guess it all boils down to internal event handlers, like script load events or timer events, but I'd rather ignore the engine's internals and look at things from the user's point of view.)
So far I have identified
<script> elements in the initial document (including the ones added by document.write)*
<script> elements inserted by JS at runtime*
Event handlers
-- these include a wide variety of cases, such as user interaction, Error events, Web Worker messages or Ajax callbacks ...
window.setTimeout
window.setInterval
*) only in Browser/DOM environments
Any more? Any differences between JS engines?
"JavaScript" as a language name should not really be used it is too broad.
ECMAScript is what you are referring to. You can find information on ECMAScript at http://www.ecmascript.org/
The language standard is called ECMA-262 with the 5.1 Edition supported by most browsers.
setTimeout, setInterval, DOM events, and more are not part of the language. These are provided by the host environment as host objects. Writing ECMAScript for a wide range of host environment should take special care when using host objects.
ECMAScript code is executed within an execution context. This takes the form of a stack and will hold the state of the current execution context at the top.
There are 3 ways to push an execution context. Global code, eval, and function. This is the only way to start code. Host environments will use these methods to execute code.
The host environment can supply a call stack. This is used to stack function calls generated by host objects which may run in independent threads. Typically an event such as setTimeout will add a function to the call stack. The host environment will then wait until the execution context stack is empty then pop the function from the call stack, create a new execution context, execute the code until completed. It will repeat this until the call stack is empty.
Attempting to build a comprehensive list of host object execution context managers is futile.
To answer the questions.
Any more?
Yes there are many more. This is beyond the scope of this answer. Refer to the particular host environment you wish to use.
Any differences between JS engines? (ECMAScript Host environments).
Yes. Again this beyond the scope of this answer and dependent on the host
There are dozens of host environments, with new ones created all the time. What triggers the creation of a new execution context is highly dependent on the host environment.