My JS function does not return the value I want

Viewed 69

Why does the value of (a) not change, despite this function:

var a = 0;

function myFunction() {
  a = 1;
}

if (a === 1) {
  alert(a);
}
<button onclick="myFunction()">1</button>

3 Answers

your button calls the myFunction but you if statement is outside of the function

let a = 0;
       function myFunction(myValue) {
        a = parseInt(myValue) ;

        if (a === 1) { 
            alert(a);
            }
        else {
            alert("a isn't = 1, it is = " + a)
        }
       }
<input type="number" name="a" id="a"><br>
    
    <button onclick="myFunction(document.getElementById('a').value)">Click me</button>

It's because you are implementing the condition outside your function().That means you are not getting the condition while button click. So you need to place the condition inside the function().

var a = 0;
function myFunction() {
 a = 1;
 if(a === 1){
  alert(a)}
}
<button onclick="myFunction()">1</button>
Or you can make another function and call it inside myFunction

var a = 0;
function myFunction() {
 a = 1;
 check()
}
function check(){
  if(a === 1){
  alert(a) }
}
<button onclick="myFunction()">1</button>

Everyone here answered your question with a normal approach, I thought to put a different method to achieve this using an observable object which is created using a proxy.

Use this if you wish to have multiple state-changing functions.

var a,b,c, ...;
function set_a() {a = 1}
function set_b() {b = 0}
function set_c() {c = 4}
...

Otherwise, it is unnecessary to create such an observer to capture a single variable change.

// creating an observable object using a proxy.
function useState(stateCallback) {
  const state = {}
  return new Proxy(state, {
    get(target, key, value) {
      return Reflect.get(target, key, value)
    },
    set(target, key, value) {
      const prev = {...target};
      Reflect.set(target, key, value)
      stateCallback({prev, current: state})
      return true;
    }
  })

}


const state = useState(callback)
state.a = 0;


function myfunction() {
  state.a = 1;
}

function callback({prev, current}) {
  // when the state object changes this callback will be called.
  console.log(`prev object is ${prev} and it changes to ${current}`)

 if(current.a === 1) alert('a is ', a)
}


Related