if-else statement is one of the most widely used conditional statements in most programming languages to execute a certain action in (a task of) a program.

what is if statement?

In JS, you can do a conditional test to make a decision (write a decision code) with if statement.
if ( condition ) { do something here }

In general, if statement is used with logical operators such as AND &&, equal to ==/===, OR ||, and so forth. There are plenty of practical examples you can learn about the basic syntax of JS operators.
In this post, we are going through a little complex but interesting scenario focusing on if-else statement with the OR operator ||.

toggleBtn()

what is if-else statement?: toggleBtn()
toggleBtn()


index.html

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="./css/styles.css">
  </head>

  <body>
    <button onclick="toggleBtn()">click</button>
    <div id="myId">Hello World</div>
    <script type="text/javascript" src="./js/my.js"></script>  
  </body>
</html>

styles.css

button {
  background-color: white;
  color: black;
  border: 2px solid #4CAF50;
  font-size: 44px;
  transition-duration: 0.4s;
}
button:hover {
  background-color: #4CAF50;
  color: white;
}
#myId {
  display: none;
  font-size: xxx-large;
}

my.js

function toggleBtn() {

  let toggler = document.getElementById("myId");
  if (toggler.style.display === "" || toggler.style.display === "none") {      
    toggler.style.display = "block"; //show "Hello World"
 
  }else {
    toggler.style.display = "none"; //hide "Hello World"
  }
}

The code snippets above implement a toggle button that shows or hides the text “Hello World” every time user clicks the toggle button.
On clicking the toggle button in index.html, the function toggleBtn() in my.js is called and the variable toggler is given an access to the target element with id="myId" where contains the text content “Hello World”. That means, this is when toggler can toggle/manipulate a display (visibility) state of “Hello World” in the target element using if-else statement and the OR operator ||, and let’s get into how they work together in the function toggleBtn().

toggleBtn(); if statement and the OR operator ||

As mentioned earlier, if statement consists of an expression (condition) and a decision block, which fairly correspond to if cluse and main clause of the 1st conditional in English respectively.

what is if-else statement?: the structure of if statement
the structure of if statement


Within if clause, the OR operator || returns a boolean value TRUE if either or both operands is/are TRUE. Otherwise, it returns FALSE.
Now, let’s verify what that means by having a close look at each of the conditions.

if (toggler.style.display === "" || toggler.style.display === “none”)

  1. toggler is an instance of the target element <div id="myId">Hello World</div> having an access to the element; see the in-page commentary and/or HTML DOM method.
  2. toggler.style
    toggler accesses its style attribute, which is a CSSStyleDeclaration object having a list of all style properties.
  3. toggler.style.display
    toggler then further accesses a value of the property display in its inline style attribute.
  4. toggler.style.display === ""
    === is a strict equality operator that checks whether its two operands are equal.
    It checks if a display value of the style attribute in toggler is equal to an empty value "".


Taken all together, the 1st condition if (toggler.style.display === "") means “Is it TRUE that the value of toggler.style.display is equal to an empty value "" (no value in it)?”.

Why does the 1st condition check an empty value "" of toggler.style.display?
The target element <div id="myId">Hello World</div> where accessed by toggler, initially has no inline css style attribute and display property in it (meaning that it literally has no style configuration to manipulate a display state of its content “Hello World”), but has an external css code #myId {display: none;} making the text content “Hello World” hidden instead.

Thus, if the 1st condition toggler.style.display === "" returns TRUE, it is absolutely sure that:


The OR operator || then skips an execution of the 2nd condition, and a decision code toggler.style.display = "block"; showing Hello World” in browser is executed in the main clause; the if statement block within curly brackets {}.
In other words, the decision code toggler.style.display = "block"; adds (assigns) an inline style attribute with a property-value pair "display: block;" into the target element with id="myId".

<div id="myId" style="display: block;">
  Hello World
</div>

At the same time, the initial external css code that has been set for the same target element is canceled (ignored).

/* styles.css */
#myId {  
  display: none;
  font-size: xxx-large;
}

if (toggler.style.display === “” || toggler.style.display === "none")

Let’s move on to the 2nd condition toggler.style.display === "none" in the parenthesis () of if clause.

The logic is the same as the 1st condition except that the 2nd one looks for an actual value "none" that is the property display’s value in inline style attribute of the target element with id="myId" where accessed by toggler.
That means, when the 2nd condition toggler.style.display = "none" is read (executed) in if clause, it accesses the target element, and what it only checks is a state of the inline style attribute with "display: none;" that hides the content Hello World” in the element.

<div id="myId" style="display: none;">
  Hello World
</div>

Because, if Hello World” is hidden in browser before clicking the toggle button, that’s when the 1st condition in if clause is executed on/after clicking the button. If the 1st condition returns FALSE then, that means Hello World” is still hidden.

The if statement (the JS program) via the OR operator || then moves to and executes the 2nd condition toggler.style.display === "none" to see if it’s TRUE that the display’s value in style attribute of the target element with id="myId" is set to style="display: none;" (hidden).
Thus, if the 2nd condition returns TRUE in if clause, the same decision code toggler.style.display === "block" in main clause is executed to show Hello World” in browser.

<div id="myId" style="display: block;">
  Hello World
</div>

toggleBtn(); else statement

When using else statement, it must be used after if statement, as opposed to if statement that can be used alone multiple times.

if (condition) {  
  // make a decision here
} else {  
  // make (an opposite) decision here
}

In general, you want to put into else statement something opposite to a decision code used in if statement block, as else statement doesn’t allow any condition. Thus, it’s best practice to write and use as simple & clear code as possible -to avoid excessive use of endless inner if statements- in an else statement.

In the if statement earlier, we’ve coded “Hello World” in the target HTML element with id="myId" to become visible (shown) using the decision code toggler.style.display = "block"; when user clicks the toggle button.
Like so, on clicking the button again (unless forcing a page refresh), we want “Hello World” to become invisible (hidden) to browser using the opposite decision code toggler.style.display = "none"; in the else statement block.


what is if-else statement?: if-else statement & the OR operator ||
what is if-else statement?



what is if-else statement?: if-else statement & the OR operator ||
what is if-else statement?


source code

dedicated assistance to your jekyll website, blog, portfolio, or project (fiverr gig @whatthehekkist) dedicated assistance to your jekyll website, blog, portfolio, or project (fiverr gig @whatthehekkist)



What The Hekk is HTML/CSS/JS? a complete guide to creating a web app in 5 min from scratch!

Kindle Edition

What The Hekk is HTML/CSS/JS? a complete guide to creating a web app in 5 min from scratch!

PDF






You May Also Enjoy

  • Web Dev

    Nelify에 Jekyll 웹사이트 배포하기

    2022-07-10

    정적 웹사이트나 블로그에 관심이 많다면 Jekyll에 대해 들어 봤을 것이다. 간단한 구글링만으로도 Jekyll을 사용하여 어떻게 웹사이트나 블로그를 만드는지 쉽게 알 수 있다. 이 블로그 또한 Jekyll 기반이고, Better Jeong님과 Jihye Leee님의 블로그 포스트를 참고하여 커스터마이징하였다. Nelify에...

  • Web Dev

    [Gitpod] 웹에서 코딩하기

    2022-07-12

    Gitpod은 오픈소스 원격 개발 플랫폼이다. 이미 굉장히 많은 사용자들이 있고, 이 블로그 또한 처음부터 Gitpod 사용했다. 개인적으로 생각하는 Gitpod의 가장 큰 장점은 사용자가 본인 컴퓨터에 로컬 개발환경 세팅에 시간을 너무 많이 투자해야 할 필요가 없고, 모든 걸 Gitpod이 제공하는...

  • Web Dev

    how to use git

    2023-04-09

    Git is a version control system where you can upload, update, and track the source code of your project. Also, you can easily deploy codes in your Git repository to a deployment/hosting platform. There are so many benefits from...

  • Web Dev

    what is switch statement?

    2023-05-26

    what is switch statement? switch statement is a conditional statement in JS (and in most programming languages) to execute a certain action over multiple inner blocks called case. switch takes an expression (input condition) that looks for a match...

  • Web Dev

    [JS variables] what is var, let, and const?

    2023-04-08

    In any script/programming language, variable is a logical storage where you can assign value into, and JS has three types of variables; var, let, and const. Let’s get familiar with some of the variable-related terms first. Declaration...