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

convert your manuscript to epub (fiverr gig @whatthehekkist) convert your manuscript to epub (fiverr gig @whatthehekkist) 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

    [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 is...

  • Web Dev

    Batch Image Loader

    2023-08-20

    Features lazy load batch (bulk) images zoom in an image on click load more images on every 100 entry skip broken or blocked image source URLs (src) Tech Stack Frameworks: Jekyll (Ruby) & Liquid template Frontend: HTML/CSS/JS & Jquery Data:...

  • Web Hack

    Insert screenshot into Markdown doc in a second

    2022-07-11

    What is Markdown? Markdown is a free open-source web-focused markup language that gives you hassle-free writing experiences (indeed, once you get familiar with it). As you can so easily find many of how-to-posts on syntax, structure, and so...

  • Programming

    Image crawling with Python on Chrome browser

    2022-07-09

    Step by step insturction 1. Install selenium and beautiful soup on terminal pip install bs4 pip...

  • ebook

    6 Useful Hacks for ebook Publish in 2023

    2023-07-19

    Choose a legit ebook editing software/program If you plan to write and publish an ebook, it’s best practice to pick a robust ebook editing program for your manuscript. There are plenty of ebook editing softwares/programs you can go for...