Concept of functions in JavaScript
JavaScript Functions:
.. many more
Function prevents script to be loaded on very first page, as function block get executed only upon call.
If we don't use function, JavaScript code will get executed during HTML page load.
formatted string usages
Concept of hoisting
Declarations of variables, functions, constants are hosted on top of the same scope.
in case of variable
Here we will get error as can not access x. In actual x is defined in the scope ahead of call due to concept of hoisting but value is unavailable.
ReferenceError: Cannot access 'x' before initialization
Let's say we replace let with var, then x is allocated at the top of call, and we get undefined.
output : undefined
for function
For function also, similar to variable, if we use function prior declaration; then due to concept of hoisting, function is defined ahead in scope.
So, below code works as intended.
Output: Hello World
In actual hello is a reference name which is created on top and entire code is converted into function object which is pointed by hello
Thus variable hello is a reference variable which contains the address of function object(containing block of code) in heap. hello.
When JavaScript code is run following happens
i) Memory is allocated, function and variables are hoisted.
Inside memory two sections are allocated call stack and heap.
ii) Execution context
- Global execution context
- Function execution context
- GEC context gets loaded during program execution and remains till program is running.
- Function execution gets called when a function object which is allocated by GEC is invoked. Function execution context is created so that function can be ran. Whenever function is invoked function execution context gets created and it comes to call stack similar to GEC.
- When function execution is completed, function execution context is released from call stack, however GEC remains till programs' life.
Comments
Post a Comment