Reputation: 1316
How to set variable which I pass to a function
function checkSetName(inputVar, outputVar, txt){
if (inputVar.length) {
outputVar = txt + ': ' + inputVar.val();
} else {
outputVar = "";
}
}
checkSetName(name, nameTxt, 'Hello world ');
I pass the empty variable nameTxt and I expect it to be set the value inside of function, but after function executes the variable is undefined
How to set variable that I pass to a function in JavaScript
Upvotes: 0
Views: 57
Reputation: 214969
You can't because JS is a strictly pass-by-value language, there are no ByRef
parameters. Just return a value.
function checkSetName(inputVar, txt){
if (inputVar.length) {
return txt + ': ' + inputVar.val();
} else {
return = "";
}
Another (worse) option is to pass an object and modify its state:
function checkSetName(inputVar, state, txt){
if (inputVar.length) {
state.output = txt + ': ' + inputVar.val();
} else {
state.output = "";
}
Finally, you can make your a function a method and modify this
instead of a parameter object:
class Validations {
checkSetName(inputVar, txt){
if (inputVar.length) {
this.output = txt + ': ' + inputVar.val();
} else {
this.output = "";
}
}
Upvotes: 8