Search code examples
javascriptreduction

Can I reduce this Javascript code?


Can I reduce

function n()
  {
  var a; 
  if(a = document.getElementById('fb0')) 
    {
    a.onclick = i0;
    document.getElementById('fb1').onclick = i1;
    }
  }

to

function n()
  {
  if(document.getElementById('fb0').onclick = i0) 
    {
    document.getElementById('fb1').onclick = i1;
    }
  }

I don't have a debugger right now. I know that document.getElementById('fb0') returns a value because the first snippet works fine. But does it need the assignment to be evaluated in the if statement?


Solution

  • No, you can't.

    document.getElementById('fb0'), as the function name already says, returns the html element with has the id equal to fb0. After that you are accessing the attribute onclick. But it the get fails it will break the script.

    On the first scenario you test if the assignment works, if does it means the element exists and will only execute if it exists.

    Those are different behaviors.