Simple javascript toggle div function
I think that is easier to write and understand the state change if you don't need to think about the edge cases.
In the first case, you already start in the state that you want and only need to invert the both states. In the second, you just need to &quot;turn off&quot; every states and &quot;turn on&quot; the one that you want to.
I think that is simplier if you think this way.
Two sidebars
I think that you can use DOMTokenList.toggle():


const sidebars = document.querySelectorAll('.sidebar');
const icon = document.getElementById('icon');

const toggle = el =&gt; el.classList.toggle('hidden');

icon.addEventListener('click',() =&gt; sidebars.forEach(toggle));
/* the display value of a div is block by default */
.hidden {
  display: none;
}
&lt;!-- you don't need to find which sidebar is open in your js --&gt;
&lt;div class="sidebar"&gt;first&lt;/div&gt;
&lt;div class="sidebar hidden"&gt;second&lt;/div&gt;
&lt;span id="icon"&gt;icon&lt;/span&gt;



Docs:

DOMTokenList
Element.classList
DOMTokenList.forEach()


More than two sidebars
Maybe toggle can't be useful in this case. However, I think that datasets might help


const sidebars = document.querySelectorAll('.sidebar');
const btns = document.querySelectorAll('.btn');

const getSidebar = btn =&gt; btn.dataset.sidebar;

const hide = el =&gt; el.classList.add('hidden');

btns.forEach(btn =&gt;
  btn.addEventListener('click', () =&gt; {
    const target = document.getElementById(getSidebar(btn));
    sidebars.forEach(hide);
    target.classList.remove('hidden');
  })
);
.hidden {
  display: none;
}
&lt;div class="sidebar" id="first"&gt;sidebar 1&lt;/div&gt;
&lt;div class="sidebar hidden" id="second"&gt;sidebar 2&lt;/div&gt;
&lt;div class="sidebar hidden" id="third"&gt;sidebar 3&lt;/div&gt;
&lt;button class="btn" data-sidebar="first"&gt;1&lt;/button&gt;
&lt;button class="btn" data-sidebar="second"&gt;2&lt;/button&gt;
&lt;button class="btn" data-sidebar="third"&gt;3&lt;/button&gt;