JS: Return Values Between Functions - Scope - javascript

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

Related

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.

Set the same value for multiple identifiers in a Javascript Object

i have an object that stores a table for converting a json response in a user readeable text. The thing is, the same text applies for multiple json conditions.
I want to know if there's a way to set the same value for 2 different Id's in a object.
Like, instead of:
var msg = {
"error_code1": "user_msg",
"error_code2": "user_msg",
}
Something like this
var msg = {
"error_code1" && "error_code2": "user_msg",
}
Is it possible?
First approach is using "getter" functions to reference the initial object:
var errorBindings = {
'errorCode101': 'Unauthorized request',
get 'errorCode102'() { return this.errorCode101; },
get 'errorCode103'() { return this.errorCode101; },
'errorCode104': 'All fields are required',
get 'errorCode105'() { return this.errorCode104; },
};
console.log(errorBindings.errorCode103); // "Unauthorized request"
Second approach is using an anonymous function with referencing properties from which we should borrow the needed value:
var messages = function(o) {
o.errorCode101 = 'Authorization error!';
o.errorCode102 = o.errorCode101;
o.errorCode103 = o.errorCode101;
o.errorCode104 = 'All fields are required';
return o;
}({});
console.log(messages.errorCode101); // "Authorization error!"
console.log(messages.errorCode103); // "Authorization error!"
What about:
var msg = {};
msg['a'] = msg['b'] = 'value';
But for such simple cases I prefer to repeat myself instead of doing premature optimizations.
Unfortunately in JSON all keys must be strings so what you are attempting will not work.
As a work around I can suggest storing a reference to the value of the user_msg and assigning it to each error code key.
For example:
var storedMessage = "user_msg";
var msg = {
"error_code1": storedMessage,
"error_code2": storedMessage
}
Let me know if you have any questions.

Javascript Typedef Error when using parameters

What am I doing wrong, and how can one pass variables to a different function within the same wrapping variable/function.
Example:
function customFunctionWrap(){
this.myVar1 = 0;
this.getCurrentPosition = function(){
if (navigation.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){});
}
},
this.doSomething = function(){ // Works
//Do something, return
this.callWithParams(); //Works
},
//If I remove passing in 'value1',calling it elsewhere works
this.doSomethingWithParams = function(value1){
//Use value1
//Return
},
this.callWithParams = function(){
var value1 = 'xyz'; //Is a variable that changes based on some DOM element values and is a dynamic DOM element
this.doSomethingWithParams(value1); //THROWS TYPEDEF ERROR: this.doSomethingWithParams is not a function
this.getCurrentPosition();
}
};
var local = new customFunctionWrap();
local.doSomething(); //WORKS
I know there is another way to do it and then directly use customFunctionWrap.callWithParams(), but am trying to understand why the former approach is erroring out.
var customFunctionWrap = {
myVar1 : 0,
callWithParams : function(){
}
}
What JS sees:
var customFunctionWrap = (some function)()
returned function is fired, because the last (), so it has to yield/return something, otherwise, like in your code it is "returning" undefined.
So your given code does not work.
The very first fix is to delete last 2 characters from
var customFunctionWrap = (some function)()
to make it return constructor.

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.

Use variable's value as variable in javascript

I have a variable with a value, let's say
var myVarMAX = 5;
In HTML I have an element with id="myVar".
I combine the id with the string MAX (creating a string myVarMAX). My question is how can I use this string to access a variable with the same name?
You COULD use eval, but if you have the var in the window scope, this is better
var myVarMAX = 5;
var id="MAX"; // likely not in a var
alert(window["myVar"+id]); // alerts 5
However Don't pollute the global scope!
A better solution is something like what is suggested in the link I posted
var myVars = {
"myVarMin":1,
"myVarMax":5,
"otherVarXX":"fred"
} // notice no comma after the last var
then you have
alert(myVars["myVar"+id]);
Since this post is referred to often, I would like to add a use case.
It is probably often a PHP programmer who gives Javascript/Nodejs a try, who runs into this problem.
// my variables in PHP
$dogs = [...]; //dog values
$cats = [...]; //cat values
$sheep = [...]; //sheep values
Let's say I want to save them each in their own file (dogs.json, cats.json, sheep.json), not all at the same time, without creating functions like savedogs, savecats, savesheep. An example command would be save('dogs')
In PHP it works like this:
function save($animal) {
if(!$animal) return false;
file_put_contents($animal.'.json', json_encode($$animal));
return true;
}
In Nodejs/Javascript it could be done like this
// my variables in NodeJS/Javascript
let dogs = [...]; //dog values
let cats = [...]; //cat values
let sheep = [...]; //sheep values
function save(animal) {
if (!animal) return false;
let animalType = {};
animalType.dogs = dogs;
animalType.cats = cats;
animalType.sheep = sheep;
fs.writeFile(animal + '.json', JSON.stringify(animalType[animal]), function (err){
if (err) return false;
});
return true;
}

Categories