function hello() {
var result = [];
var str = 'I am here';
function inner() {
var result = [];
for (var i=0;i<10;i++) {
result.push(i);
}
return result;
}
}
in the code above when I called the function hello(), the return value was an empty [], also it did not console.log the str from the inner function. However, in the below code set I have used a call back function:
function forEach(cb) {
for(var i =0;i<10;i++) {
cb(i);
}
}
function hello() {
var result = [];
var str = 'I am here';
forEach(function(num) {
console.log(str);
result.push(num);
});
return result;
}
the question is why both functions reacted, and gave a different output? Note; in both codes there was an inner function which supposed to create a new scope that can access the outer scope ? Does anyone have a good explanation for this issue ?
Thanks
In the first code block, inner is a new function that is declared inside of hello. It does not execute because you do not call it. It does create a new child scope inside of hello when it is called. But, since hello() doesn't actually return anything and doesn't call inner(), you get undefined when you call hello(). You could fix that by changing to this (you can run this snippet to see the return value):
function hello() {
var str = 'I am here';
// declare inner
function inner() {
var result = [];
for (var i = 0; i < 10; i++) {
result.push(i);
}
return result;
}
// now call inner() and return its result
return inner();
}
console.log(hello());
Functions declared inside other functions do create a new scope. Every function declaration and corresponding call in Javascript creates a new scope. If the function is inside another function, then the code inside that inner function has access to both its local scope and to the parent scope and this can nest as deep as your nested function declarations go.
the question is why both functions reacted, and gave a different
output? Note; in both codes there was an inner function which supposed
to create a new scope that can access the outer scope ? Does anyone
have a good explanation for this issue ? Thanks
In the first example, you never called the inner function so it never executed.
In the second example, you pass an inline, anonymous function reference as a function argument to your forEach() function. When that forEach() function executes, it calls your callback function with the line of code cb(i) so that's how your callback function is getting called in the second example. forEach() calls it for you.
Also, in the second example, the locally declared callback function is accessing the parent scope and modifying the result array (which is perfectly allowable). In your first code example, you are declared a new result variable in the inner function scope and then returning that. You are not accessing the parent result variable. When you declare a local variable with the same name as a variable in the parent scope, the local variable overrides the parent variable (essentially hiding the parent variable) and any references to that variable in the local scope only access the local variable.
You could have written the first code example to use a parent scoped result variable like this:
function hello() {
var result = [];
var str = 'I am here';
// declare inner
function inner() {
for (var i = 0; i < 10; i++) {
result.push(i);
}
return result;
}
// now call inner() and return result
inner();
return result;
}
console.log(hello());
You have confused function declaration and calling.
Declaring a function can be done in multiple ways:
function myNewFunction() {}
Now this function exists in the current scope, but will not execute unless called.
You can call the function like this. Now your function will get executed.
myNewFunction();
Functions and their scopes can be compared to variables. Functions defined inside another function can only be accessed from inside the parent function. Let me give you an example.
function myMegaFunction() {
console.log("in mega");
function mySmallFunction() {
console.log("in small");
}
}
myMegaFunction();
This will only print - 'in mega'. If you call mySmallFunction() inside of myMegaFunction then both lines will get printed.
Now let's take a more complex scenario like this:
function myMegaFunction() {
console.log("in mega");
var str = "car";
var result = function mySmallFunction() {
console.log("in a small", str);
}
return result;
}
var resultingFunction = myMegaFunction();
resultingFunction();
This will first print the following:
in mega
in a small car
So essentially, this is functions being passed around like variables. They can be executed later on too.
Related
Any function within function forms a closure. Do closures always needs to be in an immediately invoked function?
The first example is where a closure is formed within an iife and works as expected, gives "8" and "7" as output.
var cat = (function (){
var lives = 9;
return function() {
return --lives;
}
}());
console.log("iife");
console.log(cat());
console.log(cat());
In the below example the closure does not work as expected, prints the same value every time.
var cat = function (){
var lives = 9;
return function() {
return --lives;
}
};
console.log("no iife");
console.log(cat()());
console.log(cat()());
A closure is just the link between a function and the scope in which it was created, link which exists when the function uses a variable from this scope.
You have this problem because you don't keep the closure: you're recreating it at every console.log when you call cat().
Change
console.log(cat()());
console.log(cat()());
into
let c = cat();
console.log(c());
console.log(c());
function emergency() {
var ambulance = 100;
var callAmbulance = function() { alert(ambulance); }
ambulance++;
return callAmbulance;
}
var accident = emergency();
accident(); // alerts 101
I am referring to the variable 'ambulance'.
When I call accident(); it should call emergency() which should use the declared variable 'ambulance' [considering the global scope thing in javascript, still it could set the value to global] but its using old value 101 instead of setting again back to 100 - behaving more like static var.
What's the Explanation?
What you have there is called a closure. It means a function can access variables declared in outer functions (or in the global scope). It retains access even after the 'parent' function has returned. What you need to understand is that you don't get a copy. The changes performed on that variable are visible to your inner function, which in theory means you could have multiple functions sharing access to the same variable.
function f () {
var x = 0;
function a() { x += 1; }
function b() { x += 2; }
function show() { console.log(x); }
return {a:a, b:b, show:show};
}
var funcs = f();
funcs.a();
funcs.b();
funcs.show(); // 3
One thing to be aware of is that a subsequent call to f will create a new scope. This means a new x variable will be created (new a, b, show functions will be created as well).
var newFuncs = f();
newFuncs.a();
newFuncs.show(); // 1
funcs.a();
funcs.show(); // 4
So, how do you get a copy? Create a new scope.
function g () {
var x = 0;
var a;
(function (myLocal) {
a = function () { myLocal += 1; }
}(x));
x += 200;
return a;
}
JS only has pass-by-value so when you call the anonymous function, the xvariable's value will be copied into the myLocal parameter. Since a will always use the myLocal variable, not x, you can be certain that changes performed on the x variable will not affect your a function.
If, by any chance, you're coming from a PHP background you are probably used to do something like
use (&$message)
to allow modifications to be reflected in your function. In JS, this is happening by default.
You are creating a function definition which is not compiled at this time:
var callAmbulance = function() { alert(ambulance); }
And before you are sending it to the called function, you are incrementing the num:
ambulance++;
And then you are sending it to the called function:
return callAmbulance;
But whether you are sending it there or not, it doesn't matter. The below statement executes or compiles the function:
var accident = emergency();
And this takes in the current ambulance value which is 101 after the increment. This is an expected behaviour in creating function but not executing it. Please let me know, if you didn't understand this behaviour. I will explain it more clearly.
Is there a way to print the value of temp (a closure variable) from a function defined outside the closure but referenced within the closure without passing temp as a variable to funcA?
var funcA, funcB;
funcA = function () {
console.log(temp);
}
funcB = function () {var temp, funcC;
temp = 1;
funcC = funcA;
funcC();
}
funcB(); // temp is undefined.
This works, but only because funcA is defined within funcB:
funcB = function () {var temp, funcA, funcC;
temp = 1;
funcA = function () {
console.log(temp);
}
funcC = funcA;
funcC();
}
funcB(); // 1
I'm trying to find a way to pull some function definitions out of outer functions to streamline code that's getting a little complex. Can I define funcA outside of funcB but still reference the temp variable without having to pass parameters?
I read that javascript does not have dynamic run time scoping, that it's only lexical scoping, but with referencing a function (funcA via funcC) within funcB, is there a way to meet the lexical scope requirement and provide access to the scoped variables for funcB?
Using Akinkunle Allen's comment, I came up with this which seems to solve my problem.
function funcB () {
var funcA, funcB, temp;
funcA = function () {
console.log(temp);
}
funcB = function () {var funcC;
temp = 1;
funcC = funcA;
funcC();
}
return funcB();
}
funcB(); // 1
Yes, and No.
The keyword var for declaring variables behaves different depending upon what the current scope is. When var is executed on the global scope it is optional. The variable becomes a property of the global object. When executing in the browser this global object is window.
So the following in global space has the same result.
var temp = 1;
window.temp = 1;
this.temp = 1;
All the above is just window.temp because of the global context.
When you use var inside a function then the variable is attached to the function. All functions in Javascript are objects so local var variables will live as long as the parent function is still being used somewhere.
Javascript will walk the hierarchy of executing scopes to find a variable identifier. So any inner functions can access their outer function variables (as in your example).
What you can do is play around with the this reference in functions.
The identifier this in Javascript is dynamic (meaning that you can change it). I can pass a variable to an unknown function that was declared outside the calling function. Since the this.temp is used to reference the variable the function funcA is able to display the value.
funcB = function(otherFunc)
{
this.temp = 1;
otherFunc();
}
funcA = function()
{
alert(this.temp);
}
funcB(funcA);
http://jsfiddle.net/thinkingmedia/dfLvj/
See the above jsfiddle example.
What you can do with this is change the meaning of this on the fly. Here is a better example.
funcB = function(otherFunc)
{
var temp = {
message: "Hello World!"
};
var foo = otherFunc.bind(temp);
foo();
}
funcA = function()
{
alert(this.message);
}
funcB(funcA);
http://jsfiddle.net/thinkingmedia/K5Pw6/
Dynamically changing this can have a lot of benefits by allowing a function to accept closure references that will be executed with a custom this reference.
An example might be a click event handler where this is the DOM element that triggered the event.
I have done a fair amount of research but have not been able to find any answers, to what seems like a simple question:
I want to associate a property with a function (to use as a static variable in this function), like so:
function foo() {
if (!foo.counter) {
foo.counter = 1;
}
else {
foo.counter++
}
// rest of the function code goes here...
}
If I change the name of the function later, I don't want to have to change references to it inside function definition.
So, is there a way to refer to the currently executing function? (other than arguments.callee which is now deprecated). A keyword like thisFunction?
If not, what is the reason for not having something like this?
I do not know of an identifier or keyword like thisFunction (besides arguments.callee) that JavaScript exposes, but one way to achieve the same effect is to name the function foo in a closure, and return foo from that closure. That way you can always use the name foo within foo to refer to itself, regardless of what variable it's assigned to by your program:
var fn = (function() {
function foo() {
if (!foo.counter) {
foo.counter = 1;
}
else {
foo.counter++
}
// rest of the function code goes here...
}
return foo;
})();
function foo() {
if (typeof foo.counter=="undefined") {
foo.counter = 1;
}
else {
foo.counter++
}
return foo;
}
var x = new foo();
alert(x.counter); //1
var y = new foo();
alert(x.counter); //2
If you don't need to refer to the counter outside of the function, this will work. Instead of setting a variable of the function itself, you define a variable outside of the function and let the function modify that instead. Every time you call makeFoo, it makes a new variable x and returns a function using x. Every time you call the returned function, it still refers to the same x created by makeFoo. Additionally, this entirely encapsulates the variable, ensuring that almost nothing outside of the returned function can change it (it definitely won't be changed by most things outside of the returned function, but there is enough funky javascript reflection that I can't guarantee that nothing will change it). Certainly, moving the function between variables won't affect the counter (ie x=makeFoo();y=x;x=null;).
function makeFoo() {
var x=0;
return function () {
x++;
return x;
}
}
//different counters
x=makeFoo();
y=makeFoo();
x();//returns 1
y();//returns 1
x();//returns 2
y();//returns 2
//same counter
x=makeFoo();
y=x;
x();//returns 1
y();//returns 2
x();//returns 3
y();//returns 4
function getCtr(){
var i = 0;
return function(){
console.log(++i);
}
}
var ctr = getCtr();
ctr();
ctr();
I've been using Javascript from last five years, but this question made me dumb in last interview. I tried everything to my knowledge but can't figure it out.
Can you please help me with the output and reason for it so that I can be better equipped for future interviews if I have one.
var ctr = getCtr();
This calls getCtr(), which initializes i to 0, and stores a reference to the function
function() {
console.log(++i)
}
in ctr. Because that function was created in the scope of getCtr(), the variable i is still accessible in the scope of the function stored in ctr.
The first call to
ctr()
executes console.log(++i) which has a preincrement on i, so it prints out 1. The second call executes the same code, with the same preincrement, and prints out 2.
DISCLAIMER: Not a javascript developer. Forgive me if I've made an error or used some unpreferred wording.
So the code you posted outputs 1 2. Yet the code:
function getCtr(){
var i = 0;
return function(){
console.log(++i);
}
}
getCtr()();
getCtr()();
outputs only 1 1!
The difference is that if you save a reference to getCtr() by using the var ctr = getCtr();, you create what is called a closure.
So the difference between calling getCtr()() and ctr() is that ctr has i defined in its scope, and that scope is saved thanks to var ctr = getCtr();. Because the reference is saved, the function inside of ctr is able to always act on the same variable.
run this:
var m=0;
var d=0;
alert(m++ +":"+ ++d);
and you get "0:1"
IF it were me asking in an interview, the difference in where the ++ is is what I would be after :)
http://jsfiddle.net/MarkSchultheiss/S5nJk/
Closures
The return statement in that function saves i. So when var i = 0; is only called var ctr = getCtr();. Then ctr becomes the returned function:
function () {
console.log(++i)
}
and the variable ctr has i in the scope of the outer function, getCtr() and the return function is in the scope of getCtr() as well.
okay, getCtr is a function that returns an other function.
It also contains a var called "i" which is set to 0.
"i" is also available in the scope of the returned function.
the preincrement of "i" before logging it to the console causes that it increases by 1 every time the returned function, which is stored in "ctr", is called.
When executed, function getCtr returns an inner anonymous function.
This function is now referenced by variable ctr
Because the anonymous function was created inside getCtr it will have access to getCtr private scope object, which contains variable 'i'. This is known as a closure.
var ctr = getCtr()
Every time the anonymous function is executed it pre-increments i, and writes in in the console.
ctr()
Lets break it down using terms you might know from classical inheritance based OOP languages:
// In javascript functions are first-class objects
// This function is being used like a class would be in Java
function getCtr(){
// You can think of this as a private variable of the getCtr "class"
var i = 0;
// Because it is returned, this is effectively a public method of getCtr
return function(){
// Which increments i and then prints it.
console.log(++i);
}
}
// This makes the variable ctrl an instance of getCtr.
var ctr = getCtr();
// This calls ctr's only public method.
ctr();
ctr();
So the output would be "1, 2".
What this question is meant to do is test if you understand Javascript's prototypal inheritance, ability to have anonymous functions, and closures.
A clarified version of that could that would do the same thing would be:
var myProtoype = function() {
var privateVariable = 0;
var privateMethod = function () {
privateVariable++;
console.log(privateVariable);
}
return {
publicMethod: privateMethod
};
}
var myInstance = new myPrototype();
myInstance.publicMethod();
myInstance.publicMethod();
That function is a Javascript Module. You can have a good reading about it on Javascript: the Good Parts, which is a great book and I highly recommend. A Module uses Javascript closures to create private variables and if assigned to a var the var will retain it's vars each time it's called instead of redefining the vars.
A module works like this
function moduleName(privateVar1){
var privateVar1;
var privateVar2;
return {
exposedFunction1: function (var1) {
// Do stuff... using private vars
return something;
},
exposedFunction2: function (var1, var2) {
// Do stuff...
return something;
}
}
}
var moduleInstance = moduleName(privateVar1);
moduleInstance.exposedFunction(var1);