Is 'global' a function in Javascript? - javascript

I am studying hard what the closure is in Javascript.
According to MDN, closures are created every time a function is created, at function creation time.
However, many articles and answers in Stack Overflow says that the concept of closure needs the relationship between inner function and outer function and their variables.
So, I wonder whether 'global' is the kind of a function which executes at runtime of global scope(or global execution context) or not.
If 'global' is a function, all of the functions in script are maybe inner functions, I guess.
Please answer me if you are fully understanding closures, and execution contexts. Thank you!

your question is a very genuine one :). What I get from your question is that your confusion is in 'global' in JavaScript. It is not clear from your question if you need help in closures and execution context, so to keep the answer short I'll focus on "global" only.
So global in JavaScript is the global execution context. It is more like complier running the code.
If you have experience in any programming language say Java. You may relate to this. The place where you write functions is not a function itself. So we can safely say global is not a function rather an execution context.
Same way, the functions defined inside a global execution context are not inner functions. They are simply functions.
Maybe you are confused in this, because you feel the variables declared globally can be accessed inside the function declared in global concept, this is simply because of scope of a variable and has nothing to do with closures.

When we execute our code, one of the very first things that the JavaScript engine does is to create a global execution context. This has the same purpose as function execution context, but at the global level with some more particularities. Now, once GEC got created - JS engine moves line by line and starts to execute other functions with their own function execution context!
So as per your question, global is just an execution context that gets created only once at the beginning with some extra features.
Hope this could clear your doubt.

Related

Does automatically hoisting slow down the performance of JavaScript?

Lately, I was studying Scope in Javascript. I want to know whether automatically hoisting is done at compile time or at the time of executing the code(run time). If it does at run time then I have another question does auto-hoisting will slow down the performance of the Javascript program.
something = a();
function a(){
console.log("hoisting");
return 10;
}
var something;
Should we use manual hoisting or it would be better to use automatically hoisting?
To put my comments as an answer:
People have a different understanding of what hoisting supposed to mean. Fact is that, according to the spec, every time a function is called a new execution context is created, which holds a new environment. Then the function body is processed to find all variable declarations (var, let, const (and function declarations)) and bindings for those names are created in the new environment. var declarations are initialized with undefined. Then the body is actually evaluated.
Considering this, from the perspective of the engine it doesn't really matter where you place the var declaration, the whole body has to be processed anyway.
Having said that, I would be surprised if actual implementations didn't cache that information. After all, the variable declarations in a function don't change between function calls.
As I know, There are no performance issues. The initializations are getting done in compile time. So doesn't matter you initialize on top or bottom, The JS engine will create the references in compile time.
BUT
If you forgot to initialize at the bottom, It will be initialized as undefined by default. Because of hoisting it’s considered a practice to declare functions or variables at the top of their respective scopes.
JavaScript: What is Hoisting? (Recommended)
It is not done at run time.
It's in the compile process.
So it doesn't slow down the performance.
Just before the code is executed the compiler scans for all variable and function declarations and allocates them in the memory.

Is there any benefit from hoisting?

I would like to see which are the benefits of hoisting, if there's some... I looked for an answer but they only explain what is it, I would like to know is there's an actual benefit that I can use to write better code.
It seems that with the use of const and let, javascript is actually enforcing to avoid hoisting, not to mention that some linters actually enforce to declare functions and variables at the top from where they're called.
The main benefit of hoisting is that functions don't have to be declared in a specific order in order to work properly. The interpreter makes a pass over a function of code and finds all the function declarations within that function and makes them available to code anywhere in the scope (hoisting them) whether the code referring to the functions is before or after where the function declarations are located. It also allows A to call B and B to call A without running into declaration ordering issues.
Variable hoisting is rarely used anymore now that we have const and let which are block scoped and cannot be used before declaration. So hoisting is mainly useful for function declarations now.
In JavaScript, Hoisting is the default behavior of moving all the declarations at the top of the scope before code execution. Basically, it gives us an advantage that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.
It allows us to call functions before even writing them in our code.
Note: JavaScript only hoists declarations, not the initializations.

Different scoping in Javascript - Lexical vs Dynamic

I was going through the scoping concept and I found out that it is possible to implement both lexical and dynamic scope. Can any one help me to understand what is the major difference between Lexical and Dynamic scope in accordance of JavaScript?
Also how can we implement it in JavaScript?
In lexical scoping, the variable can be called only from within the block of the code which it is defined. The scope of that variable is defined when the program is compiled. The variable can be accessed by its children's execution contexts. But it doesn't work backward to its parents, meaning that the variable likes cannot be accessed by its parents.
In dynamic scope, the variable declared can be called from outside the code block. In this, the compiler will search for the variable reference in the local function first, then it searches in the function that called the local function, then it searches in the function that called that function, and so on, up the call stack. "Dynamic" refers to change, in that the call stack can be different every time a given function is called, and so the function might hit different variables depending on where it is called from.
http://wiki.c2.com/?DynamicScoping

Why was block scope not originally implemented in JavaScript?

I have read, and discovered through my own experience, that JavaScript doesn't have a block scope. Assuming that the language was designed this way for a reason, can you explain to me what is that reason?
I've looked around on Google and here, but the posts I have found just reiterate that JS has a function scope and not block scope, without explaining why. I'm curious to know why this is actually the case.
Converting my comment to answer
Choice of the creator: I tweeted Brendan and got the following answer:
#mplungjan 10 days did not leave time for block scope. Also many "scripting languages" of that mid-90s era had few scopes & grew more later.
That said, here are some relevant points:
Block statement
Important: JavaScript prior to ECMAScript2015 (6th edition) does not have block scope. Variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. Although "standalone" blocks are valid syntax, you do not want to use standalone blocks in JavaScript, because they don't do what you think they do, if you think they do anything like such blocks in C or Java.
a workaround
we can artificially introduce scopes by creating new functions and immediately invoking them
ECMAScript 2015 (ES6)
let and const declared variables are hoisted but they are not initialized to undefined in the same way var is. Hence, referencing a let or const declared variable before its value is assigned raises a ReferenceError.
Redeclaration of the same variable in the same block scope raises a SyntaxError.
New answer as of 2015. ES6 does have block scope for variable definitions with the let and const keywords.
Block scope was not implemented for the following reasons:
It's makes the language easier to implement. JavaScript was initially designed as a language for writing interactive web applications. Hence it needed to be small and easy to implement.
Block scopes introduce a performance hit to dynamic languages like JavaScript. This is because when you try to access some variable which is not in the current scope JavaScript first checks the current scope, then the parent scope and so on until it either finds the variable or reaches the end. Hence the introduction of block scopes would make variable access in loops and nested loops very slow.
The lack of block scopes makes it easier to write programs. For example say you want to create a variable only if a certain condition is true. All you need to do in JavaScript is declare and define the variable within an if statement. In languages like C you would have to declare the variable outside the if statement and define it within the if statement.
The lack of block scopes allow declarations to be hoisted. This is especially useful in the case of function declarations. For example see this fiddle: http://jsfiddle.net/L6SgM/ (note however that this example doesn't work in Firefox).
Since JavaScript supports first-class function expressions we don't need block scopes. They can be simulated using immediately invoked function expressions.
There are many reasons, but some that come to mind are to aid in parsing/debugging code that uses object literals (which can sometimes look like a block), and to simplify the garbage collection of local variables.
I hope that the promised support (discussed here, for example, http://esdiscuss.org/notes/2012-07-25) turns out to be real because it would be very convenient to use variables like i that were local to only a single loop.

What is the difference between a closure and an anonymous function in JS

What is the difference between a closure and an anonymous function in JavaScript
The closure mechanism applies to all JavaScript functions, whether anonymous or not.
I think confusion between the two concepts comes from use of the term "closure" where an author has said something like "the following code creates a closure" and then given an example that happens to use an anonymous function. In such instances typically the closure mechanism is what is important to make the particular piece of code work as intended, while use of an anonymous function rather than a named function just happens to be a convenient way to code it. People reading such examples and seeing "closure" for the first time then misinterpret the term and go on to use it incorrectly in their own Stack Overflow or blog posts and so the confusion spreads.
A closure is an expression relying on a namespace reference in which variables are resolved (a context). An anonymous function is one way to form a closure in Javascript - a named function is another.
There is some discussion about the ability to form closures with non-function blocks, but the current standards specify no such.
http://jibbering.com/faq/notes/closures/ is a pretty good description.
A closure is a function that has captured its environment (the variables that it has access to)
It can be created both from an anonymous and as from named function.
And an anonymous function differs from a named function mainly that it's declaration does not get hoisted to top of the scope.

Categories