1

I would like to create a re-usable function that changes the boolean value of the variable that is passed in.

My example is below however this doesn't work as the first part of the statement 'item' is not assigned to the variable passed in.

let editable = true;

     function toggleEditMode (item){
            item = !item;
        }

toggleEditMode(editable);

Any help?

3
  • I updated the link. Read new one. Commented Mar 30, 2017 at 11:37
  • did that solve your problem? Commented Mar 30, 2017 at 11:54
  • This worked. @cmac Commented Mar 30, 2017 at 13:59

1 Answer 1

3

You have to learn how js passes function arguments. It is passing by value here. Read this by value vs reference

Basically you can't pass by reference like you are trying to. You can make an object and then change a property on that object inside your function and it will work how you are expecting.

var i = { a:true }

function c(o){
  o.a = !o.a
}

c(i)
console.log(i);
Sign up to request clarification or add additional context in comments.

2 Comments

@PankajParkar I was putting together example code for him just moving little slow cause on iPhone not in front of computer. ;)
yes this worked, I thought there might've been a cleaner solution without using objects, thanks.

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.