Bootstrap FreeKB - JavaScript - Getting Started with if else statements
JavaScript - Getting Started with if else statements

Updated:   |  JavaScript articles

An if statement in JavaScript has the following structure.

if (condition) {
  <do something>
} else if (condition) {
  <do something>
} else {
  <do something>
}

 

For example.

const foo = "Hello";
if (foo == "Hello") {
  console.log("foo equals Hello");
} else if (foo == "World") {
  console.log("foo equals World");
} else {
  console.log("foo does not equal Hello or World");
}

 

Following are common if statements. These examples are based on some HTML element such as a p or div or span element with id="demo".

<p id="demo">Hello World</p>

 

If the demo element exists (is defined)

if (document.getElementById("demo"))

if (document.querySelector("#demo"))

If the demo element innerHTML equals string Hello World

if (document.getElementById("demo").innerHTML === "Hello World")

if (document.querySelector("#demo").innerHTML === Hello World")

If the demo element innerHTML does not equal string Hello World

if (document.getElementById("demo").innerHTML !== "Hello World")

if (document.querySelector("#demo").innerHTML !== "Hello World")

If the demo element innerHTML contains string Hello World

const foo = document.getElementById("demo").innerHTML;

if (foo.match(/^(Hello World)$/))

If the demo element contains integer 5

if (document.getElementById("demo").innerHTML = 5)

if (document.querySelector("#demo").innerHTML = 5)

If the demo element does not contain integer 5

if (document.getElementById("demo").innerHTML != 5)

if (document.querySelector("#demo").innerHTML != 5)

Greater than

if (document.getElementById("demo").innerHTML > 5)

if (document.querySelector("#demo").innerHTML > 5)

Less than

if (document.getElementById("demo").innerHTML < 5)

if (document.querySelector("#demo").innerHTML < 5)

Greater than or equal to

if (document.getElementById("demo").innerHTML >= 5)

if (document.querySelector("#demo").innerHTML >= 5)

Less than or equal to

if (document.getElementById("demo").innerHTML <= 5)

if (document.querySelector("#demo").innerHTML <= 5)

URL endpoint equalsif (window.location.pathname == "/foo")

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 7ec3e2 in the box below so that we can be sure you are a human.