JavaScript global scope - javascript

I ran this code in my console but got undefined. However I expected it to return 1 because function 2 returns a, which is a var in the global scope.
Can you please explain where I'm mistaken? thank you.
var a = 1;
function f1() {var a = 1; f2();}
function f2() {return a;}
f1();

You aren't doing anything with the return value of f2. You'd need to do this:
var a = 1;
function f1() {var a = 1; return f2();} // NB pass the return value on
function f2() {return a;}
f1();

Related

A Javascript quiz about hoisting

var d = 1;
(function(){
d = '2'
console.log(typeof d)
function d() {
}
})()
console.log(typeof d)
Could you explain why the second log prints out "number"?
var d = 1;
(function(){
d = '2'
console.log(typeof d)
})()
console.log(typeof d)
I tried to remove the function from the IIFE, and the result of second log becomes "string". I am very confused about it.
The first code:
var d = 1;
(function(){
d = '2'
function d() {
}
})()
because of function hoisting (function definitions are hoisted to the top of the containing scope - I think I worded that right), it's identical to
var d = 1;
(function(){
function d() {
}
d = '2'
})()
Now, d inside the IIFE is declared locally, so the "global" d is irrelevant and untouched by d='2'

Functions and parenthesis in Javascript

I don't understand how all those f() function work, can someone explain why it prints two '1', I know it prints '1' for every '()' after f(f), but I don't know why.
function f(y) {
let x = y;
var i = 0;
return () => {
console.log(++i);
return x(y);
};
}
f(f)()();
And why does the 'i' doesn't increase?
Thank you.
function f(y) {
let x = y;
var i = 0;
return () => {
console.log(++i);
return x(y);
};
}
f(f)()();
is equivalent to
function f() {
var i = 0;
return () => {
console.log(++i);
return f();
};
}
const t1 = f();
const t2 = t1();
t2();
is equivalent to
function f() {
var i = 0;
return () => {
console.log(++i);
};
}
const t1 = f();
t1();
const t2 = f();
t2();
If you did call each of t1 or t2 multiple times instead of just once, you'd increment the i from the respective closure some more. But if you instead just chain them, they call f again and initialise a new var i = 0 for a different closure.
First, the f(y) function essentially calling y onto itself. Executing f(y) would return a new function, which when executed, would execute x(y) and return the results.
To reduce the confusion, it's just calling f(f) for each f() you executed in this example, as x === y and y === f. The important part of why i never seems to increase, is that every execution creates a new i.
What happens in behind are:
f(f)()();
// is same as
const f1 = f(f);
const f2 = f1();
const f3 = f2();
// f(f) would execute first, and returns () => {
// console.log(++i);
// return x(y); // which is same as returning f(f) in this example
// }
Notice that executing f(f) returns x(y) which x(y) seems to be equal to f(f). Seems as it is similar in code, but different instance. Another point is that i was never carried to this new function, nor are shared to the other instances. Each f(f) creates a new i, never passed to the next function.
Let's name the function at line 4 , function A.
return result of function f() is function A.(at line 4 you define a function, you don't call it.)
the body of A is gonna be this and since you use those variables in an inner function, they are not gonna be exposed(i = 0, x = y = f ):
function A(){
console.log(++i);
return x(y);
so what you have now is: A()().
First parenthesis: A() prints a '1' and returns result of f(f) which is function A.(the first i is exposed and a new i is created)
Second parenthesis : A is executed like I said and return another A, since there are no any parenthesis left, there is no more call.
You declare in f always a new i.
Instead, you could store the count into a property of the function itself.
function f(y) {
let x = y;
f.i = f.i || 0;
return () => {
console.log(++f.i);
return x(y);
};
}
f(f)()()();

Why multiple functions inside an IIFE execute the last function?

I have actually no idea how the output of this code is a number. Someone kindly help understanding with what logic is JS running in this example?
<script>
var f = (
function f(){ return "1"; },
function g(){ return 2; }
)();
console.log(typeof f);
</script>
You're using the comma operator. You're basically executing g here
The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.
var f = (
function f(){ return "1"; },
function g(){ return 2; }
)()
is similar to:
var temp = function g(){ return 2; }
f = temp() // returns 2
Because of the comma operator.
x = a, b;
This evaluates a, then it evaluates b, and the result of b is used. That is, a is only evaluated for its side effects, otherwise its result is discarded.
That means that
var f = (
function f(){ return "1"; },
function g(){ return 2; }
)();
is a fancy way of writing
var f = (function g(){ return 2; })();
which is a fancy way of writing
var f = 2;
and 2 is a number.
Here f is not a function.
Instead contains the value returned by g function.
f currently holds to the value returned in IIFE
var f = (
function f(){ return "1"; },
function g(){ return 2; }
)();
console.log(f);
</script>
So, right, the comma operator. But more important is the change of the context of the functions. They are not anymore accessable from the global scope.
Some expanations may be in this answer of Does the comma operator influence the execution context in Javascript?:
var f = (
function f() { return "1"; },
function g() { return 2; }
)();
console.log(f);
console.log(typeof f);
console.log(g()); // throws error: 'g' is not defined

Same function name in javascript (Nested function and outside function ) [duplicate]

This question already has answers here:
What is the purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Closed 5 years ago.
I have a function as below.
My Problem is that I need to print function b() inside a function. Here function a() is parent function. and I have done it by taking c= new a() and console.log(b()) . I got the right value as I expected. But inside the parent function I have another function named test() and with same name there is another function outside the parent function. After printing function b() I call the function test() . But it return the value from the parent function. I need to get an alert as needed answer which is in outer function. Is there any way to get my expected result without changing the function name.? Both functions test() are needed.
Expected result: function b() = 2 and function test() = needed answer
Current result : function b() = 2 and function test() = 4
Any help will be appreciated. Thank You.
function a() {
var val = 1;
var otherval = 2;
b = function() {
return val + 1;
}
test = function() {
qwerty = otherval + b();
alert(qwerty);
}
return 'OK';
}
function test(){
alert('needed answer');
}
c = new a();
console.log(b()); //return 2
test(); //alert 4 but I needed alert needed answer
As Rajesh Pointed out, declaring a function without using var will make it a global variable. Use var before test function to get expected value. But this will make it inaccessible outside the function a(). For that, assign the functions to this object and access then as shown below.
function a() {
var val = 1;
var otherval = 2;
this.b = function() { //prepend this
return val + 1;
}
this.test = function() { //prepend this
qwerty = otherval + b();
alert(qwerty);
}
return 'OK';
}
function test(){
alert('needed answer');
}
c = new a();
console.log(c.b()); //return 2
test(); //alert 4
You need slight modification in your code. Do this and it will work as per your requirement -
function a() {
var val = 1;
var otherval = 2;
b = function() {
return val + 1;
}
this.test = function() {
qwerty = otherval + b();
alert(qwerty);
}
return 'OK';
}
function test(){
alert('needed answer');
}
c = new a();
alert(this.b()); //return 2
test(); //alert 4

How to have function recall private variable between invocations

Here's an easy one straight from the text book I can't seem to find.
I have a javascript function. I want it to contain a private variable which remembers its value between invocations.
Can someone jog my memory please.
Create it using a closure:
function f() {
var x = 0;
return function() {return x++;};
}
Then use it as follows:
> g = f()
function () {return x++}
> g()
0
> g()
1
> g()
2
var accumulator = (function() {
var accum = 0;
return function(increment) {
return accum += increment;
}
})();
alert(accumulator(10));
alert(accumulatot(15));
Displays 10 then 25.
I am not sure if I understood correctly but maybe something like this would do the trick :
function Foo() {
var x = "some private data";
return {
getPrivateData : function(){
return x;
}
};
};
var xx = new Foo();
xx.getPrivateData();
Here is a truly private implementation
(function() {
var privateVar = 0;
window.getPreviousValue = function(arg) {
var previousVal = privateVar;
privateVar = arg;
return previousVal;
}
})()
alert(getPreviousValue(1));
alert(getPreviousValue(2));
Cheers

Categories