Javascript variable scope in anonymous function [duplicate] - javascript

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 3 years ago.
I'm confused as to why the below will output "1".
If I use var to declare a in myFunc that should limit the scope of a to that function.
Calling "a" in the anonymous function (in the setInterval call) is a different function so why is that considered with the scope of myFunc?
Is it only because the function is anonymous? I would expect a to be available to another function unless bind() was used.
myFunc = function(){
var a = 1;
var int = setInterval(function () {
console.log(a);
}, 5);
}

The function bound to setInterval is a closure, when something is unknown in its own scope, it looks in the outer scope, in your case myFunc scope

Related

Calling one function with another function variables javascript [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Learning JavaScript: Lexical Versus Dynamic Scoping
(3 answers)
What is lexical scope?
(21 answers)
Closed 8 months ago.
I am trying to learn JS internals.I am currently trying to print message "yo" both times using the two console.logs. I tried using call,bind or apply to see if it will help but it still doesn't. On the execution stack it places func2 execution context above the func1 execution context. So, I was hoping it would take the func2.
var a = 'hello';
function func1() {
console.log(a);
}
function func2() {
var a = 'yo';
func1();
console.log(a);
}
func2();
I know that if we put it as a nested function it will work.
var a = 'hello';
function func2() {
var a = 'yo';
function func1() {
console.log(a);
}
func1();
console.log(a);
}
func2();
Is there a way to print the internal message without declaring a function inside like the 2nd example without passing a variable to func1?
I think the reason why the first is not working is because this refers to the window but slightly confused due to Execution Context placed over the Execution Stack.

Is closure created when a function is called (not declared) within another function and, if so, why? [duplicate]

This question already has answers here:
How do JavaScript closures work?
(86 answers)
How is a closure different from a callback?
(9 answers)
Closed 5 years ago.
From every definition I have looked up, closure is when a function is created or declared from within another function. Examples are plentiful across blogs and websites of this happening. But what about when the function is declared outside of another function, but called then called from within a function? For example:
const add = (x,y) => {
return x + y;
};
const double = num => {
return add(num,num)
};
let a = double(6);/*?*/
Does add(num, num) create closure? If so, please help me understand why.
Closures are a product of lexical scope.
A closure is the combination of a function and the lexical environment
within which that function was declared.
You must define a function within another one to create a closure.
What you do in your example is simply call a function that calls another and uses its return value. At no point can the double function access the scope of the add function: their scopes are distinct.
Here is a classical example of JavaScript closure
var makeAdder = function(x) {
return function(y) {
return x + y;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2)); // 7
console.log(add10(2)); // 12
In both cases, the functions returned by makeAdder, "remember" the outer scope in which the were created (the scope created by the makeAdder function).
Anything that was in scope of the outer function was also in scope for the inner function, and it remains so when the inner function is returned.

Call a scoped function dynamically [duplicate]

This question already has answers here:
dynamically call local function in javascript
(5 answers)
How can I access local scope dynamically in javascript?
(4 answers)
Closed 5 years ago.
Within Javascript, you can create and call a function as such:
function test_1(){ console.log(1); }
window['test_1']() // --> 1
However, my current code is scoped:
(function(){
function test_1(){ console.log(1); }
window['test_1']() // --> not a function
})();
...making any created functions not be bound to the window-level, but to the specific scope level.
How can I create a function within a scope, and then dynamically* call that function?
*By dynamically I mean that I can dynamically alter the string with a variable, such as window['test_'+index]().
Global variables become properties of the window object.
Non-global variables do not automatically become properties of any object.
You can't do this.
Consider making the function a property of an object explicitly instead.
(function(){
var functions = {};
functions.test_1 = function test_1(){ console.log(1); };
functions['test_1']();
})();
To call the scoped function from within the scope you just call it by name (do not use window):
(function(){
function test_1(){ console.log(1); }
test_1();
})();
To call the scoped function from outside the scope you need to export it into the calling scope:
var scope = (function(){
function test_1(){ console.log(1); }
return {
test_1: test_1
};
})();
scope.test_1();

Javascript functions and declaring [duplicate]

This question already has answers here:
What is the different between a parameter and a local variable?
(4 answers)
Closed 6 years ago.
When working with functions in JavaScript, are variables declared as parameters in a function different from variables declared within the function itself?
For example, is
function functionName (var1, var2)
different to
Function (var1, var2) {
Var VarName;
}
In the second example, could var1 be declared where varName is declared? If not, why?
var1 and var2 are parameter variables, they automatically get their values from the arguments provided when the function is called.
Variables declared with var inside the function body are local variables of the function.
Parameter variables are automatically made local to the function. You can have
var var1;
in the function, but it's redundant and has no effect. It doesn't create a new variable or override the value of the parameter (unless you include an initializer).
function myFunc(var1, var2) {
var var1;
var var2 = 3;
var newVar;
console.log(var1, var2, newVar);
}
myFunc(1, 2);

javascript function declarations and differences in scope [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
What is the difference between a function expression vs declaration in JavaScript? [duplicate]
(5 answers)
Closed 8 years ago.
I couldnT find an answer easily, so even if this question is a dupe, the answers donT come up using these keywords.
I want to know the difference between the different way of declaring functions in a sample app.js
var foo = function()
{
//..
}
function bar()
{
//..
}
var baz= function()
{
//..
}
function qux()
{
//..
}
// other??
I m also not clear about the scope where I can use each function. Thanks!
There are four ways to create a function in JavaScript.
Function declaration
This will create a variable foo in the current scope and assign a named function to it.
function foo () {
}
Function declarations are hoisted so it doesn't matter where, in the applicable scope, you put them. It is considered good coding practise to define them before you use them though.
Anonymous function expression
This will create a function without a name and use it in an expression. In this example it is assigned to the variable something.
something = function () {
};
Named function expression
This is the same as an anonymous function expression except that it has a name, creates a variable of that name in the scope of itself and is horribly broken in older versions of Internet Explorer.
something = function foo () {
};
Function constructor
Do not use function constructors. They are eval by another name. You can read about them on MDN if you're interested.

Categories

Resources