how to access variable outside of my function? [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 24 days ago.
Improve this question
Im having trouble accessing my variable outside of my function. I don't have 'var' so I dont know how to access it in another function because the variables "rev_value" and "currency" come back undefined
//this function is being invoked first
FundraiseUp.on('donationComplete', function(details) {
rev_value = details.donation.amount; //these are the variables i need to use outside of the function
currency = details.donation.currency; //and this one
});
function uet_report_conversion() {
window.uetq = window.uetq || [];
window.uetq.push('event', 'Donation', {
"revenue_value": rev_value, //using them in this function
"currency": currency //and here
});
}

In JavaScript, variables declared within a function are only accessible within that function, and are not accessible outside of it. This is known as variable scoping. To access a variable outside of a function, you can do one of the following:
Declare the variable outside of the function: You can declare the variable rev_value and currency outside of the FundraiseUp.on function, and then assign them values inside the function. This way, the variables will be accessible outside of the function as well.
let rev_value;
let currency;
FundraiseUp.on('donationComplete', function(details) {
rev_value = details.donation.amount;
currency = details.donation.currency;
});
function uet_report_conversion() { window.uetq = window.uetq || [];
window.uetq.push('event', 'Donation',
{"revenue_value":rev_value,"currency":currency}); }
Pass the variables as arguments to the second function: You can pass the rev_value and currency variables as arguments to the uet_report_conversion function, and then access them inside the function.
FundraiseUp.on('donationComplete', function(details) {
let rev_value = details.donation.amount;
let currency = details.donation.currency;
uet_report_conversion(rev_value, currency);
});
function uet_report_conversion(rev_value, currency) { window.uetq =
window.uetq || []; window.uetq.push('event', 'Donation',
{"revenue_value":rev_value,"currency":currency}); }
You can use closure to make the variables accessible from inside the second function.
FundraiseUp.on('donationComplete', function(details) {
let rev_value = details.donation.amount;
let currency = details.donation.currency;
return function(){
window.uetq = window.uetq || [];
window.uetq.push('event', 'Donation',
{"revenue_value":rev_value,"currency":currency});
}
});
let uet_report_conversion = FundraiseUp.on('donationComplete')();

The callback function provided to the FundraiseUp.on doesn't immediately gets executed. Therefore, the only way for the uet_report_conversion() function to access the data is to execute it after the donationComplete event triggers. The code would be something like this:
FundraiseUp.on('donationComplete', function(details) {
rev_value = details.donation.amount;
currency = details.donation.currency;
uet_report_conversion(rev_value, currency)
});
function uet_report_conversion(rev_value, currency) {
window.uetq.....

Related

Pass variable into function to be defined [duplicate]

This question already has answers here:
What's the difference between passing by reference vs. passing by value?
(18 answers)
Closed last year.
EDIT 2: Why has this very specific question been marked as a duplicate of this very conceptual one: What's the difference between passing by reference vs. passing by value?. If someone else had the same question as me, they wouldn't end up with this one on Google by searching for it and - even if they did - it wouldn't answer their question.
EDIT: Thanks everyone for your help so far. Pretty difficult stuff to understand from my point of view. The reason I'm doing this is that I've set up a function which I'm calling multiple times and in which I define a variable (a unique one with each call). I need to be able to refer back to each unique variable afterwards. Here is my actual attempted code below. What would the right way to do this be?
let newSeq1
let newSeq2
function sequenceClip(sample, length, sequenceVariable) {
let currentPosition = Tone.Transport.position
let whenToStart
if (currentPosition === '0:0:0') {
whenToStart = '0:0:0'
} else {
const barToStartOn = +currentPosition.slice(0, currentPosition.indexOf(':'))
whenToStart = `${barToStartOn + 1}:0:0`
}
sequenceVariable = new Tone.Sequence((time, note) => {
sampler.triggerAttackRelease(note, '4m', time)
}, [sample], length).start(whenToStart);
}
loop1.addEventListener('mousedown', () => {
sequenceClip("C3", '1m', newSeq1)
})
loop2.addEventListener('mousedown', () => {
sequenceClip("C#3", '4m', newSeq2)
})
How do I pass a variable into a function in Javascript to be assigned a value. E.g.:
Why does the variable not get assigned the value 5? And what's the way around this?
let a
function defineVariable(var2beDefined) {
var2beDefined = 5
}
defineVariable(a)
console.log(a === 5)
You would typically write an initializer function that returns a value and assign that return value to the relevant global variable. For example:
let newSeq1
let newSeq2
function sequenceClip(sample, length, sequenceVariable) {
let currentPosition = Tone.Transport.position
let whenToStart
if (currentPosition === '0:0:0') {
whenToStart = '0:0:0'
} else {
const barToStartOn = +currentPosition.slice(0, currentPosition.indexOf(':'))
whenToStart = `${barToStartOn + 1}:0:0`
}
return new Tone.Sequence((time, note) => {
sampler.triggerAttackRelease(note, '4m', time)
}, [sample], length).start(whenToStart);
}
loop1.addEventListener('mousedown', () => {
newSeq1 = sequenceClip("C3", '1m')
})
loop2.addEventListener('mousedown', () => {
newSeq2 = sequenceClip("C#3", '4m')
})
Note that both newSeq1 and newSeq2 will be undefined until the first mousedown/mouseup events.
Reassigning an identifier, by itself, never has any side-effects (in most circumstances) - the only change resulting from someIdentifier = someNewValue will be when other parts of the code reference that same someIdentifier.
If you want to pass in something to be assigned to, pass in a function which, when called, assigns to the outer variable.
let a;
function defineVariable(callback) {
callback(5);
}
defineVariable(newVal => a = newVal);
console.log(a === 5)
The only time that assigning to an identifier will have side effects is if:
Inside a function with a simple argument list, you reassign one of the parameters (in which case the arguments object will be changed as well)
You're using ES6 modules, and you reassign an identifier that's being exported, in which case other modules that import it will see the change as well

how to access global variable from function in javascript

I am trying to access global variable from function, i want to call variable outside from inside function variable.This is what I tried.
Note: the query function should be work after click on query function from html drop down selection.
Thank you for helping.
HTML
<select name="myInput" id="choice1">
<li><option value="6011">apib_cadastral:bivel</option></li>
<li><option value="6012">apib_cadastral:burhchaura</option></li>
</select>
javascript
var layer_name;
function query() {
var text_value = document.getElementsByName('myInput')[0];
var layer_name = text_value.options[text_value.selectedIndex].text;
}
query();
var config = {
geojson: layer_name,
};
Remove the "var" inside the function. With that you define a new variable that exists inside the function.
You should change your code in this way.
Because, when you re-declare variable inside query() it will occupy another cell from memory with different address. And, variable inside config object cannot access it. It will access layer_name [first defined] which contains undefined value
var layer_name ;
function query() {
var text_value = document.getElementsByName('myInput')[0]
layer_name = text_value.options[text_value.selectedIndex].text;
}
query();
var config = {
geojson: layer_name
}
In addition to other answers, which correctly state that you should remove var from the variable declaration inside the query() function, you could change the function to return the value, rather than relying on shared/global state.
function query() {
var text_value = document.getElementsByName('myInput')[0];
return text_value.options[text_value.selectedIndex].text;
}
var config = {
geojson: query()
};
Note that this may have a performance impact depending on how many times you call query() as the return value would have to be computed each time, but it's worth considering from the perspective of alleviating the need for shared/global state.
Also note, consider replacing var with more modern const and let...
const when the variable is initialised and never needs to change.
let when the variable needs to change beyond initialisation.
function query() {
const text_value = document.getElementsByName('myInput')[0];
return text_value.options[text_value.selectedIndex].text;
}
const config = {
geojson: query()
};

JavaScript arrow function to count time it gets called but does not take any parameter

I receive a challenge to create a function (arrow function) that count the times it gets called or invoked. BUT, this function can't take any parameter or interact with outside scope likes the normal way below.
Normal way:
var count = 0;
var countTimesCalled = (count) => {
count+=1;
return count;
}
console.log(countTimesCalled(count))
Is it possible to have created a function that does not take any parameter and not interact with outside scope to count the times it gets called? Where to store the times (var count) on runtime and after runtime?
Please help!
Use an IIFE to hold the count variable in a local scope:
var countTimesCalled = (() => {
var count = 0;
return () => ++count;
})();
console.log(countTimesCalled());
console.log(countTimesCalled());
console.log(countTimesCalled());
not interact with outside scope
That is not possible, but you could do something that looks kind of like it does that:
var countTimesCalled = (count => _ => ++count)(0);
console.log(countTimesCalled());
console.log(countTimesCalled());
console.log(countTimesCalled());
In reality there are two arrow functions there, an outer one to hold the count variable that is called once, and an inner one that is returned and referenced by countTimesCalled. That inner one is interacting with a scope outside of itself, but only as far out as the outer arrow function.
You could use .bind to capture state, if you really wanted to avoid accessing another closure scope entirely, e.g.
var countTimesCalled = function() {
return this.counter++
}.bind({ counter: 1 });
Set an attribute to the function, i.e: countTimesCalled.i
var countTimesCalled = () => (countTimesCalled.i = (countTimesCalled.i || 0) + 1);
console.log(countTimesCalled())
console.log(countTimesCalled())
console.log(countTimesCalled())

Table data is not appending when in a function

Whenever I write my code iteratively the program runs as it is supposed to, but when I place in a function like this it breaks.
function create_tableElements() {
Let myArticle = document.createElement(‘tr’);
Let rank = document.createElement(‘td’);
}
function assign_tableElements() {
Let count = 1
rank1 = count;
rank.textContent = rank1;
heroes_name.textContent = heroes[i].name;
}
function append_tableElements() {
myArticle.appendChild(rank);
myArticle.appendChild(heroes_name);
}
Does anyone know why this may happen? Is there a way for me to call a function within a function? I am using a for loop to loop through JSON. Now if I do not place in a function and just write the code, it will run perfectly fine. Just working on readability, and organizing my code better
There's a couple issues with the code you pasted (Let instead of let or the fancy single quotes).
I'm going to assume your phone or whatever tool you used corrected it. So let's say this is your code :
function create_tableElements() {
let myArticle = document.createElement('tr');
let rank = document.createElement('td');
}
function assign_tableElements() {
let count = 1;
rank1 = count;
rank.textContent = rank1;
heroes_name.textContent = heroes[i].name;
}
function append_tableElements() {
myArticle.appendChild(rank);
myArticle.appendChild(heroes_name);
}
Your code can't work because :
the rank variable is local to the create_tableElements function and can't be accessed by the append_tableElements function
same goes for the heroes_name function, it's local to the assign_tableElements function
You can fix this by :
either declaring these variables as global variables, outside of any function. It's not really a best practice, though.
change your function's definition so that they can access the same local variables : do you really need a function to create elements and another to append them to the DOM?
you could also use an Immediately Invoked Function Expression.
(function() {
// these variables will be visible to all the functions defined in this function, but won't be global :
let rank, myArticle, heroes_name;
function create_tableElements() {
myArticle = document.createElement('tr');
rank = document.createElement('td');
}
function assign_tableElements() {
let count = 1;
rank1 = count;
rank.textContent = rank1;
heroes_name.textContent = heroes[i].name;
}
function append_tableElements() {
myArticle.appendChild(rank);
myArticle.appendChild(heroes_name);
}
// invoking your functions :
create_tableElements();
assign_tableElements();
append_tableElements();
})();

Put local variable in angular.forEach loop in the global

Hello I have created a variable inside the angular.forEach loop that I need outside the loop to bind to the $scope, but i don´t know how to get outside this variable miAlumno.
Thanks.
'use strict';
angular.module('jarciaApp')
.controller('alumnoCtrl', function($routeParams, $firebaseArray) {
var ref = firebase.database().ref('PrimeroA');
var JarciaArray = $firebaseArray(ref);
var id = $routeParams.id;
var curso = $routeParams.curso;
var miAlumno;
JarciaArray.$loaded()
.then(function(miAlumno) {
angular.forEach(JarciaArray, function(alumno, miAlumno) {
if (alumno.Id == id) {
var miAlumno = alumno;
}
})
});
console.log(miAlumno);
});
Don't declare variable miAlumno in loop. Declare it outside and it will be visible.
Pay attention at that console.log(miAlumno), it probably will be always null because of the asynchronous assignement.
If I understand correctly, you are wanting to use the alumno variable you have passed into the function outside the scope of that function?
You can go about it by creating/declaring a global variable outside the function just as you did with miAlumno, then simply assign your global variable to the value your function produces. Also you have miAlumno declared twice, once outside as a global, then inside the for loop.
Apologies if I'm misunderstanding, and if so, please elaborate.
It sounds like you're using the ControllerAs syntax, which means what traditionally would be scope variables are automatically bound as properties of the controller. You can simply set the variable inside of the loop, using a cached value of this:
'use strict';
angular.module('jarciaApp')
.controller('alumnoCtrl', function($routeParams, $firebaseArray) {
var ref = firebase.database().ref('PrimeroA');
var JarciaArray = $firebaseArray(ref);
var id = $routeParams.id;
var curso = $routeParams.curso;
var me = this;
JarciaArray.$loaded()
.then(function() {
angular.forEach(JarciaArray, function(alumno) {
if (alumno.Id == id) {
me.miAlumno = alumno;
}
});
// This will work to show the value
console.log(me.miAlumno);
});
// This still won't work, since $loaded is asynchronous
console.log(this.miAlumno);
});
I've also removed the extra attempts to pass miAlumno to the then function and the callback for forEach; those are unnecessary.
Do note the comments about console.log. I believe the $loaded() is asynchronous; thus it will not be set until whatever process that is actually finishes. If you move the log to inside the then(), you'll see the result.

Categories

Resources