I don't understand why my global variable isn't updating? - javascript

I posted about this yesterday but I am still dumbfounded.
I can't seem to figure out this problem. I want to update the parkEndpoint URL with a new value for the stateName variable when the user clicks on a state SVG. It keeps coming up as the original value in line 1.
I have tried looking in the console and after the function getStateName runs it does update the stateName variable, but when I console log the parkEndpoint variable after that function has run, it still shows the old variable, which I just set to nothing.
var stateName = "";
const alertEndpoint = ("https://developer.nps.gov/api/v1/alerts?
&limit=400&api_key=" + apikey );
var parkEndpoint = ("https://developer.nps.gov/api/v1/parks?
stateCode=" + stateName + "&limit=100&api_key=" + apikey);
const elements = document.querySelectorAll('path');
console.log(elements);
// add event listeners
elements.forEach(function(el) {
el.addEventListener("click", getStateName);
});
function getStateName(nodeList){
stateName = nodeList.path[0].id;
outputStateName(stateName);
}
function outputStateName(stateName) {
console.log(stateName);
console.log(parkEndpoint);
}
I just want it to update the stateName variable in the URL.

Your statName variable is empty in the beginning and even after you are getting the state name from stateName = nodeList.path[0].id; the variable parkEndpoint is never being updated.
var stateName = '';
var parkEndpoint = parkEndpointUpdate();
function parkEndpointUpdate(){
return `https://developer.nps.gov/api/v1/parks?
stateCode=${stateName}&limit=100&api_key=${apikey}`
}
function getStateName(){
stateName = nodeList.path[0].id;
parkEndpoint = parkEndpointUpdate(); // This func will updated your variable of parkEndPont
outputStateName(stateName);
}

It's because you don't update the value of parkEndpoint
In javascript, string are stored by reference. Meaning parkEndpoint references to the string defined L3, and is not reassigned later.
You need to reassign it in your getStateName function.

Related

Not able to change value of Global var from inside function

I tried using this solution but it didn't work for me. In my case I am trying to save a variable using 1 function and call it from another
var postalcode = "code didn't change";
export function save_postal_code(code) {
var localcode = code
let postalcode = localcode;
console.log(code);
}
export function get_postal_code() {
console.log(postalcode);
return postalcode;
}
The save_postal_code function logs the correct value, but the get_postal_code function doesn't. I don't know what I am doing wrong.
You're redeclaring postalcode inside save_postal_code() instead of updating its value.
The code needs further revision, but that's outside the scope of this answer.
To have postalcode updated inside save_postal_code(), try:
var postalcode = "code didn't change";
function save_postal_code(code) {
let localcode = code
postalcode = localcode;
}
function get_postal_code() {
return postalcode;
}
save_postal_code("123")
console.log(get_postal_code())
This happens because you're instantiating the variable again using the let keyword (making a more immediate local variable with the same name)
removing the let keyword should fix your issue
var postalcode = "code didn't change";
export function save_postal_code(code) {
var localcode = code
postalcode = localcode;
console.log(code);
}
export function get_postal_code() {
console.log(postalcode);
return postalcode;
}

JS: Return Values Between Functions - Scope

First post; did a little digging but can't find what I'm looking for (maybe just too inexperienced with the site). Hopefully, you guys can help:
--EDIT--
Researching after discussion shows that what I was looking for was how to use return to pass a value resulting from one function, to another.
How does this relate to global/local scope? Is a value returned to a function from another local or global scope? It's local to it's original function, but accessible to global?
Example has been changed*
var addition = function add(a, b) {
var addTotal = (a+b);
return addTotal; }
var multiply = function(c) {
var multiplyTotal = c * 2 ;
return multiplyTotal; }
multiply(addition(2,3));
Make getUser return the userName, then when calling lowerUserName, pass that returned value to it as argument:
var getUser = function(userName) {
var userName = prompt("Please enter your username?") || ''; //defend against null
return userName; // return userName
};
var lowerUserName = function(userName) { // expect user name as parameter (you can name this variable anything you want, it's only local to lowerUserName)
var userNameLower = userName.toLowerCase();
// you should probably return userNameLower if you want to use it somewhere else
};
lowerUserName(getUser()); // call getUser and pass its return value directly to lowerUserName
lowerUserName(getUser()); can be broken into two steps to make it easy to understand:
var returnedValue = getUser(); // the return value of getUser will be the value of userName
lowerUserName(returnValue); // then we pass that value to lowerUserName when we call it
I think you might be over-complicating this, the following works, because prompt returns a string (EDIT: or null as pointed out in the first comment and I therefore trivially updated the one-liner to reflect this); see https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt:
var userName = (prompt("Please enter your username?") || '').toLowerCase(); //FOOBAR
console.log(userName); //foobar

Javascript, Update variable on input change

I'm not very experienced with JavaScript (This is my first real thing I've made with it), so my syntax is probably horrendous. I'm trying to get 5 variables to update whenever the input box is changed, however for some reason, they just won't update! I've Googled for solutions but nothing seems to work
document.getElementById("name").addEventListener("keyup", updateName);
document.getElementById("id").addEventListener("keyup", updateID);
document.getElementById("quantity").addEventListener("keyup", updateNumber);
document.getElementById("buybase").addEventListener("keyup", updateBuy);
document.getElementById("sellbase").addEventListener("keyup", updateSell);
Here's a JSFiddle
http://jsfiddle.net/q1w6v12u/
Here's the live site
http://ts-mc.net/pricing/chest.html
You have declared all those variables as local variables(since you have used var inside the method), which exists only inside the methods in which they are declared, declare them as global variables.
So now you have a global variable and a local one which exists only inside the method, so any changes you have done to the variable inside the method will not get reflected in the variable which is in the global scope.
function updateName() {
ITEMNAME = document.getElementById("name").value;
}
Why are you declaring variables twice:
var ITEMNAME = "NULL";//first
function updateName() {
var ITEMNAME = document.getElementById("name").value;
^^^==========>second
}
Just do this:
var ITEMNAME = "NULL";
function updateName() {
ITEMNAME = document.getElementById("name").value;
}
To solve your immediate issue with variables not updating you could change your JS to this:
...
function updateName() {
ITEMNAME = document.getElementById("name").value;
}
function updateID() {
ITEMID = document.getElementById("id").value;
}
function updateNumber() {
NUMBER = document.getElementById("quantity").value;
}
function updateBuy() {
BUYCOST = document.getElementById("buybase").value;
}
function updateSell() {
SELLCOST = document.getElementById("sellbase").value;
}
function Replace() {
BUYCOST = BUYCOST * 4 * NUMBER;
SELLCOST = SELLCOST / 4 * NUMBER;
var DONE = BASE.replace(/ITEMNAME/igm, ITEMNAME);
var DONE = DONE.replace(/ITEMID/igm, ITEMID);
var DONE = DONE.replace(/NUMBER/igm, NUMBER);
var DONE = DONE.replace(/BUYCOST/igm, BUYCOST);
var DONE = DONE.replace(/SELLCOST/igm, SELLCOST);
document.getElementById("output").innerHTML = DONE;
}
The cause of the problem is due to you redefining your variables within function scope instead of using the ones already existing in the parent.
There are some issues with your HTML also, with not terminating your elements properly for example <input ... />

Why I can't pass parameter into .then function (AngularJS)?

I have this function
$scope.updateValue = function(key, selectedProductname, numberUsed){
var selectedKey = key;
var selectedProductname = selectedProductname;
var numberUsed = numberUsed;
var useageRef = ref.child('/useage/');
var updateObj = $firebase(useageRef);
var myData = {
productName : selectedProductname,
numberUsed : numberUsed
}
var decrementLocation = inventoryRef.child(key + '/amount')
updateObj.$push(myData).then(
decrementLocation.transaction(function (current_value, numberUsed) {
console.log(numberUsed);
return (current_value || 0) - 1;
})
);
}
I pass "numberUsed" into $scope.updateValue and use it inside myData and then push it to the server and there is no problem with that but when I use it at this line "decrementLocation.transaction(function (current_value, numberUsed) {" and then I try to console.log(numberUsed); the console says undefined. Why? and how can I use numberUsed in this line "decrementLocation.transaction(function (current_value, numberUsed) {" ? how to code it successfully?
There is a number of things going on here.
First of all, in the following code:
decrementLocation.transaction(function (current_value, numberUsed) {
console.log(numberUsed);
return (current_value || 0) - 1;
})
You are re-declaring numberUsed as the second parameter of the .transaction() callback function. Thus, whatever numberUsed was outside of this small function does not matter. If you want to use the var from the surrounding function, you would need to do:
decrementLocation.transaction(function (current_value) {
console.log(numberUsed);
return (current_value || 0) - 1;
})
Second of all, there is no closing ; to your .transaction() function. I don't think it will materially affect your operating here, but cannot be sure. This should be run through jslint/jshint.
Third, you are redeclaring numberUsed inside the entire surrounding $scope.updateValue() function.
$scope.updateValue = function(key, selectedProductname, numberUsed){
var numberUsed = numberUsed;
So you are declaring a new variable numberUsed, whose value will be, well, numberUsed, but it is a new var, so it should be set to undefined. If it is set to anything at all, that would be surprising. If you need the var, then you should do:
$scope.updateValue = function(key, selectedProductname, numberUsed){
var nu2 = numberUsed;
or something similar. But even then, why bother to redeclare the var? It is copied by value anyways.
A good linter will catch any of this.

Method, doesn't set property value

I have the following code:
function Show() {
this.showId = $("#meta-show-id").val();
this.title = $("#meta-title").val();
this.season = $("#meta-season").val();
this.episode = $("#meta-episode").val();
this.storageId = $("#meta-show-id").val() + '-' + $("#meta-season").val() + '-' + $("#meta-episode").val();
this.torrents = [];
this.putioId = null;
this.status = null;
this.subtitle = null;
}
Show.prototype = {
constructor: Show,
checkStorage: function() {
var storage = new Storage();
storage.get(this.storageId, function(data){
if (jQuery.isEmptyObject(data)){
console.log("empty");
}
else {
this.subtitle = data.subtitle;
}
});
}
}
When I call the checkStorage() method on object, method checks in chrome.storage.sync for data, and sets object this.subtitle property.
But this doesn't seem to work, this.subtitle value doesn't change.
What am I doing wrong?
This is a normal result, and it happens because of scope changing. I don't know if Storage is has your own implementation (because it is used with getItem instead of get), but anyways, you are calling a method that I guess calls back the function you provide as a second argument, right?
And because this function is called from somewhere else, this is not the object that you want.
Here is a simple example: http://jsfiddle.net/6c2e6/1/
Check out logs, and see what this is. It's the Window, because my test function is at top level..

Categories