Search code examples
javascriptfunctionparametersboolean

How to change the value of the boolean by implementing the boolean to the function as a parametr


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?


Solution

  • 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);