For this Javascript example, can somebody please explain on a very basic level why this is not working and how you properly create another (not nested) function that passes back a value to the function it was invoked from.
function function1() {
var x = 5;
function2(x);
console.log(y);
function3(y);
console.log(z);
}
function function2(y) {
var y = y + 5;
return y;
}
function function3(z) {
var z = z + 5;
return z;
}
Even when declaring them in the main function, it doesn't work:
function function1() {
var x = 5;
var y = function2(x);
console.log(y);
var z = function3(y);
console.log(z);
When using global variables, no difference. I also tried following other examples where you create 1 global object to write global variables to, but that also always fails with "undefined":
function function1() {
x = 5;
y = function2(x);
console.log(y);
z = function3(y);
console.log(z);
I guess I don't understand some very basic concept. Please shine some light. I can see subroutines running and doing what they need to do, but they never pass back the final value to the function that invoked the function.
Follow up question
I do a request to an API where I get a roomId. Next I try to call a function that does another API call to translate the roomId to a roomName. I want to pass the roomName back to the other function to use it there. I tried many things already, untill now not able to pass back the variable. As the previous example seem to work, it must have something to do with something else (array/object, string/nostring/...).
function GetMemberships() {
var xhttp = new XMLHttpRequest();
var url = "HIDDEN";
var method = "GET";
var shouldBeAsync = true;
xhttp.open(method, url, shouldBeAsync);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.setRequestHeader("Authorization", "Bearer HIDDEN"); // API key of Bot
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var jsonObj = JSON.parse(xhttp.responseText);
var roomId = jsonObj.items[0].roomId;
var roomId = JSON.stringify(roomId);
var roomId = roomId.replace(/"/g,'');
var roomName = GetNameOfRoom(roomId);
console.log(roomName) // UNDEFINED
}
};
xhttp.send();
}
function GetNameOfRoom(roomId) {
var xhttp = new XMLHttpRequest();
var url = "HIDDEN" + roomId;
var method = "GET";
var shouldBeAsync = true;
xhttp.open(method, url, shouldBeAsync);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.setRequestHeader("Authorization", "Bearer HIDDEN");
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var jsonObj = JSON.parse(xhttp.responseText);
var roomName = jsonObj.title;
console.log(roomName); // SHOWS CORRECT VALUE
return roomName;
}
};
xhttp.send();
}