Lifetime of local variables inside an Object Constructor Function [duplicate] - javascript

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 7 months ago.
In this example, taken from the W3Schools JS Tutorial, how is it possible for the variable n to still be used in the next function ?
// Home Made Iterable
function myNumbers() {
let n = 0;
return {
next: function() {
n += 10;
return {value:n, done:false};
}
};
}
// Create Iterable
const n = myNumbers();
n.next(); // Returns 10
n.next(); // Returns 20
n.next(); // Returns 30
I'm coming from a C/C++ background and the lifetime of this variable makes no sense to me. It seems to behave like a global static variable but it should have been deleted when exiting myNumbers(), especially when declared with the let keyword. How can, then, the next method uses it without raising a ReferenceError and keeping its value updated ?

Because of a closure feature of the JavaScript, keep the variable accessible even if the containing function died, whenever there is a child function still need to access it.
For more resources.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

Related

Shall we declare a variable with zero value in JS for later use? [duplicate]

This question already has answers here:
Redeclaring a javascript variable
(8 answers)
Best place to declare variables in a function [duplicate]
(3 answers)
Closed 4 months ago.
If I am going to use the below example, should I declare a variable (initialize it with zero value in JS) or just use it normally later?
// Currency Converter
var currencyOne = 100; // $
var currencyTwo = 0; // Shall we do this to use as below for printing the result out or no need in JS to declare it with zero value?
var exchangeRate = 19.66; // EGP for Example
function CurrencyConverter(amount, rate) {
return amount * rate;
}
var currencyTwo = CurrencyConverter(currencyOne, exchangeRate); //I mean to use it here without any declaration first
console.log(currencyTwo);
First, you should use let and const, never var.
As to where to declare variables, there is absolutely no point declaring variables earlier than needed, it just makes your code more complicated to understand.

question about scope, closures and Let variables [duplicate]

This question already has answers here:
setTimeout in for-loop does not print consecutive values [duplicate]
(10 answers)
JavaScript closure inside loops – simple practical example
(44 answers)
What is the difference between "let" and "var"?
(39 answers)
Closed 1 year ago.
I am reading about closures, and I found these small exercises that I solved by chance, but I don't understand why they work.
The exercise is :
for (var i = 0; i < 3; i++) {
setTimeout(function log() {
console.log(i); // What is logged?
}, 1000);
}
I get that 3 will be printed 3 times because the value captured by log() when the for() ends.
Additionally, it was asked how to fix it for the console to print 0,1,2, and I found (by chance, to be honest), that it works by doing :
for ( let i =0 ...
But I guess because Let is block scoped, but i don't really know how to explain it in simple words.
The variables defined with let are blocked scope which means once you go out of the bracket it loses its value and if you try to access it will throw you an error. So, when the for is running the, i present in the console.log() will store the value for it like 0,1,etc.
whereas in the var part the var will be stored in memory and when the timeout is about to expire it will access the variable i in the memory and print whatever is there for that variable at that time.

Javascript Closure -Local variable nested function [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
I am trying to use a variable x defined inside a function P whose value I am trying to set in another function. It always comes undefined.
I tried applying my mind to use closure but it's just going off my head. It does not gives me a string rather a object.
The logic is as follows.
function P(i){
var x;
if(i!=null){
//this pulls the data correctly and i could see it in network tab response.
var dataFromQuery=widgets.DATA.create({
url:"abc/cde",
queryTemplate :"/query"+i+ "?"
});
//we query the data and set the value as per the logic.
dataFromQuery.query(function(data){
if(data[0].name){
x=data[0].name; // this stays undefined , and i understand this is a new local variable x.Also the value is here and comes fine here so no issues with the data but i want to set it to the variable defined outside as x.
}
})
}
else{
x="somehardcode";
}
};
I have tried storing the result dataFromQuery.query(function(data){ to a var and then setting it to x but it again comes as a object, which i need as a string.
Thanks
I think you're looking for something like this:
var P = (function() {
var x;
function _P(i) {
//your internal logic here
}
return _P;
})();
Both xand _P are wrapped in the enclosure and scoped only to the auto-executed anonymous function. _P is returned and available as var P in the outer scope, but x will remain hidden.

How does an iterator object keep track of its position in javascript? [duplicate]

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 6 years ago.
I am trying to lear generators but before going into that I want to know how/why this works
function makeIterator(array){
var nextIndex = 0;
return {
next: function(){
return nextIndex++
}
}
}
var it = makeIterator([1,2,3,4]);
Why is it that it.next() return 1 and another it.next() returns 2. How does it know?
Is there a way to see how it works behind the scenes?
An iterator is an object with state. In your case, the state is the private nextIndex closure variable, that's how it keeps track.
There's no magic going on behind the scenes here, if you didn't have that variable, you'd get an error.

How do I access a local variable dynamically (via a String form of its name) from a closure scope? [duplicate]

This question already has answers here:
How can I access local scope dynamically in javascript?
(4 answers)
Closed 8 years ago.
In Javascript, I'm used to being able to access variables within a known namespace "dynamically" (correct me if I'm using the wrong word here) by using the [] operator. For instance (from the global namespace):
var a = 1;
window['a']; # => 1
Or from a object-type namespace:
var a = { b: 1 };
a['b']; # => 1
And I'm familiar with the basics of how this is determined:
var a = function(){ return this['c']; };
var b = { c: 1 };
a.apply(b); # => 1;
But within a function itself, how do I access local variables I've just instantiated (or redefined) using var?
Namely, I want the following function call to return 1 but without calling a:
function(){
var a = 1;
return a;
}
You can't use window['a'] because a is defined locally, and you can't use this['a'] because this changes depending on the context from which the function is called.
In a realistic setting, I'd simply refactor to avoid dynamically creating and accessing local variables because it's generally a bad idea anyway, but as an academic question, I'm curious as to whether it's possible to access a via its string name at all.
You're mixing up local variables (which are not properties of an object) with properties (which are not local variables). There is no answer to your question, or, rather, the answer is "it can't be done".

Categories

Resources