Not able to change value of Global var from inside function - javascript

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;
}

Related

Javascript Get Prototype Function Name

Disclaimer: This code was written by another developer, previously on the project and I can't change it - I'm not allowed too.
What I'm trying to do is get the name of the parent(?) function within this.foobar() from BaseDialog.
Is it possible?
var BaseDialog = new function () {
this.foobar = function () {
// get the prototype function name that called me? E.g DialogOne
}
}
DialogOne.prototype = BaseDialog;
function DialogOne() {
this.foobar();
}
DialogTwo.prototype = BaseDialog;
function DialogTwo() {
this.foobar();
}
let callerName = arguments.callee.caller.name.toString();
console.log("caller is " + callerName );

Calling another function after value is not working

I have a simple code to call a value from another function and its not working :
function ABC() {
var ID = XYZ(id);
Logger.log(ID); //throws error not defined.
}
function XYZ(id) {
var id = "1234"
return id;
}
What I wan to do is capture the value of id from function XYZ and Logger.log it into function ABC. But this reflects error.
Still not sure what you are trying to do with your code. This code is an "Impure Function" which is not recommended in JavaScript. How much I understood your code, below are my suggestions:
First
function abc() {
var id = xyz();
Logger.log(id);
}
function xyz() {
// Add whatever logic you want here to return ID value
var id = "1234"
return id;
}
Second
function abc() {
// Pass any value as an argument based on your requirement
var results = xyz('', '', '');
Logger.log(results.id);
Logger.log(results.name);
Logger.log(results.number);
}
function xyz(id, name, number) {
// Add whatever logic you want here
var newId = id || "1234";
var newName = name || "Mask";
var newNumber = number || "1234567890";
return { id: newId, name: newName, number: newNumber };
}
Based on what suits your requirement, you can take help of these codes.
Here you go -
function ABC() {
var ID = XYZ();
Logger.log(ID); // No longer throws the error :)
}
function XYZ() {
var id = "1234"
return id;
}
You do not need two functions, here is a simple function that will return the ID passed in.
const ABC = (id) => {
return id;
}
let a = ABC(122443);
console.log(a) // output 122443

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

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.

Passing values from an object inside a function

I have been working all day trying to pass the value of "returnData.salary" inside the "readData" function to
the object inside the "calculateTax" function which is suppose to take the salary value and calculate state and federal taxes. I am stumped, I can't find anything on the internet which provides a good example for me to work with. The examples are either way to simple or super complex. Any help would be appreciated.
I apologize in advance if I did not submit this question in the correct format. This is my first time asking for help on stackoverflow.
function readForm() {
var returnData = {};
returnData.name = $("#name").val();
returnData.lastName = $("#lastName").val();
returnData.age = $("#age").val();
returnData.gender = $("[name=gender]:checked").val();
returnData.salary = $("#salary").val();
returnData.isManager = $("#isManager").val();
returnData.myTextArea = $("#myTextArea").val();
$("#name2").text(returnData.name);
$("#lastName2").text(returnData.lastName);
$("#age2").text(returnData.age);
$("#gender2").text(returnData.gender);
$("#salary2").text(returnData.salary);
$("#myTextArea2").text(returnData.myTextArea);
if ($(isManager).is(':checked')) {
$("#isManager2").text("Yes");
}
else {
$("#isManager2").text("No");
}
//$("#employeeForm")[0].reset();
} //end of readForm function
function calculateTax() {
console.log("Button Works");
var calculateTax = {
state: function(num) {
num *= 0.09;
return num;
}
, federal: function(num) {
if (num > 10000) {
num *= 0.2;
return num;
}
else {
num * 0.1;
return num;
}
}
, exempt: true
};
}
//Invoke readForm function when the submit button is clicked.
$(document).ready(function () {
$("#btnSubmit").on("click", readForm);
$("#btnCalculate").on("click", calculateTax);
})
</script>
Well, simply put; you can't. Not like this anyway. Or, at least not pass the value to the function directly.
You are using global functions right now, which are not inside a class. If it was inside a class, you could instantiate the class and save it to this (which would be the class' instance). However, I'm assuming classes are a bit over complicated in this case. What you could do, is set variables globally so all functions can use them, like this;
//declare the global variable so it exists for every function
var returnData = {};
function readForm() {
//We do NOT redeclare the "var" again. It's global now.
returnData = {}; //Reset the global variable when this function is called
returnData.name = $("#name").val();
returnData.lastName = $("#lastName").val();
returnData.age = $("#age").val();
returnData.gender = $("[name=gender]:checked").val();
returnData.salary = $("#salary").val();
returnData.isManager = $("#isManager").val();
returnData.myTextArea = $("#myTextArea").val();
//Rest of your function
}
function calculateTax(){
console.log(returnData) //works here
}
Note that you do overwrite global variables, so it's best to reset them on every function call. You might get old data stuck in there, otherwise.

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 ... />

Categories