'Why is this function working on second click only?

I have a simple function that hides text on click. However it only works on the second click. I tried rewording the conditional statement but nothing has worked so far. jsfiddle https://jsfiddle.net/Montinyek/293hmpu1/18/

let btn = document.getElementById('btn');
let hello = document.getElementById('hello');

function test() {
  if (hello.style.display !== 'block') {
    hello.style.display = 'block';
  } else {
    hello.style.display = 'none';
  }
}

btn.addEventListener('click', test)
<div id='hello'>
  hello
</div>

<div id='btn'>
  button
</div>


Solution 1:[1]

At the start nothing has set the style so the test !==‘block’ will be true. And you then set the style to block so it needs another click to get it to none.

If you set things the other way round it will work because the style is not set to none so you then immediately set it to none.

The confusion often seems to arise because setting the style properties is not there initially, ie not set until you set them.

let btn = document.getElementById('btn');
let hello = document.getElementById('hello');

function test() {
  if (hello.style.display !== 'none') {
    hello.style.display = 'none';
  } else {
    hello.style.display = 'block';
  }
}

btn.addEventListener('click', test)
<div id='hello'>
  hello
</div>

<div id='btn'>
  button
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 A Haworth