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?

Sachin Karia
  • 547
  • 2
  • 8
  • 22

1 Answers1

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);
Community
  • 1
  • 1
cmac
  • 3,123
  • 6
  • 36
  • 49
  • 1
    @PankajParkar I was putting together example code for him just moving little slow cause on iPhone not in front of computer. ;) – cmac Mar 30 '17 at 11:49
  • yes this worked, I thought there might've been a cleaner solution without using objects, thanks. – Sachin Karia Mar 30 '17 at 13:58