0

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

1
  • You are missing the return and you should remove the outpuVar because it's useless. Commented Feb 7, 2018 at 12:53

1 Answer 1

8

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 = "";
        }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Really liked the ways answer is evolving :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.