0

I've been struggling with making a function that changes the value of the boolean if the requirement is completed.

Below he code:

let width = false
let height = false


function ___(boolean){

  if (document.getElementById("input").value == ""){
    boolean = false
    console.log(width)
    console.log(height)

  }
  else if (document.getElementById("input").value !== ""){
    boolean = true
    console.log(width)
    console.log(height)
  }

}


document.getElementById("input").addEventListener('keyup', function(){___(width)})


The problem is that booleans of width and height do not change. How to fix this problem?

Marcel
  • 15
  • 3

1 Answers1

0

Assigning value to a function parameter won't change the value of the passed variable. This is because a parameter is a local variable within the function.

There are two options for how the desired effect could be achieved.

Option 1

function setParam(ref)
{
  // here we are changing a property within the ref and not the ref itself
  ref.value = true;
}
let param = { value: false };
setParam(param);

Option 2

function setParam(callback)
{
  callback(true);
}

let param = false;
// here, we extract the value known within the setParam
// using callback
setParam((val) => param = val);
RAllen
  • 1,235
  • 1
  • 7
  • 10