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
Related
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.
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.
In his (great) series of books “You don't know JS", Kyle Simpson states that dynamic scope and this mecanism are "near cousin", he also says that :
"the this mechanism is kind of like dynamic scope."
(YDKJS, Scope and Closure, Appendix A)
What is preventing him from saying that this is plain and simple dynamic scoping ?
Also, in the book "this & Object Prototypes", also part of the series YDKJS, as far as I can say, Kyle is not mentioning once dynamic scope while discussing how thisis working, so I am a bit surprised why he decided to not go further in the analogy... Does anyone have an idea why ?
Thanks
The reason I claim this is just "kind of like" a dynamic scope and not actually a dynamic scope is based on these two observations:
The aesthetic of accessing the "scope context" explicitly with an object reference (this.foo = 1) is distinct from implicitly accessing it via lexical variable reference (foo = 1). At best, this makes the two systems of "scope" parallel, not the same. But there's more different than what it seems on the surface!
But more importantly, dynamic scopes are traditionally defined as scope chains that are based on the call-stack. That is, a dynamic scope is one where the decision of what "scope contexts" to consult, in order, is exactly the current stack of function calls. But this isn't based on the call-stack, per se, but rather just the manner in which the most recent call in the stack was made, only.
Consider this scenario: foo() calls bar(), bar() calls baz(), and in baz() a reference is made to an x variable that is not defined in baz().
In lexical scope, the lookup would be baz(), then whatever the outer scope of baz() is, and so on. bar() and foo() wouldn't be consulted at all, unless they happened to be the lexically surrounding scopes of baz().
In dynamic scope, the call stack foo() -> bar() -> baz() is the scope chain, so baz() is consulted, then bar(), then foo(), regardless of where those 3 functions exist lexically in the code base.
Now, consider the same scenario, but this.x is the reference made inside baz(). The call stack foo() -> bar() -> baz() is not particularly relevant in resolving this.x. Rather, the only thing that matters is how baz() was invoked. If the call site is baz(), the "default binding" rule applies. If it's this.baz(), the "implicit binding" rule applies. If it's baz.call(..), the "explicit binding" rule applies. And if it's new baz(), the "new binding" rule applies. That's it.
Actually, it's not the only thing, it's just the first decision that's made. Once it's determined what object (aka scope context object) this points to, now the only thing that matters is the prototype chain of that object, as that's the "scopes" that will be consulted, in order of the prototype chain linkage.
Summary:
In lexical scope, where a function is defined is the only thing that determines what contexts are used, and in what order, to resolve a variable reference.
in dynamic scope, where a function is called from is the only thing that determines what contexts are used, and in what order, to resolve a variable reference.
in this-based context, neither where a function is defined nor where it's called from are relevant. Therefore, this is neither lexical scoping nor dynamic scoping.
The only thing that matters here is how the current function in the call stack (top of the stack) was called. Well, that's the only thing that matters to determine which scope chain to start the lookup on. But once that object is decided, it's now that object's prototype chain that entirely defines the scope resolution.
Because the this "variable" is the only variable that has dynamic scope, all other ("real") variables have lexical scope in JavaScript. In contrast, in "plain and simple dynamic scoping", all variables have dynamic scope and you can't get away from it (which is really ugly). So when we want to have multiple values in our dynamic scope, we store them in an object, and access them as properties of the this object, which is quite different from dynamic scope and also involves object inheritance.
Can this be done either via writing some code to intercept the global scope default declaration or via a setting within the javascript engine itself which each program or function has access to?
What I mean is if I could, at the top of the program (or function), tell the javascript engine to use local scope for undeclared variables instead of global scope... then, when the javascript engine compiles each function, it would declare them in local scope.
I understand if you want to declare a variable outside of the current scope, that should be done explicitly since no one knows where you want it declared, but I think defaulting to global scope leaves too much room for error and forces too much typing of var statements in each function, so I'd like to change the default in my programs if that's possible.
My primary purpose is to avoid having to type the list of local variables in a var statement at the top of every function, and to avoid the maintenance of keeping this list in sync with the local variables as I'm using them within a function. Not allowing a global scope default also reduces the risk of errors.
I would never want undeclared variables to end up in any higher scope than the scope in which they are first used. There is no value in having them default to global scope that I can see.
I know I can explicity declare variables in the current scope (or the global scope), but would like to avoid doing so and use a more useful default than the global scope default built into javascript.
I also know I can use "use strict" to force all variables to be declared explicitly. Not wanting to debate the right or wrong of it, but just asking if there is any way to change the default to local scope instead of global scope for a given function.
No, Javascript behaves the way it does, there's no switch to flip to turn its variable declaration rules on its head.
'use strict' is an option you can employ to help you catch problems more easily, but it doesn't change the rules.
What you want is a different language; for example CoffeeScript, a Javascript preprocessor which, among other things, happens to solve this variable declaration issue explicitly.
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.