JavaScript Operators, Loops, and Flow Control: A Comprehensive Guide

Home > Blog > JavaScript Operators, Loops, and Flow Control: A Comprehensive Guide

Explore the world of JavaScript operators, loops, and control flow in this comprehensive guide. Learn how to assign values to variables, perform arithmetic operations, and use compound operators. Discover the power of logical operators and the importance of operator precedence. Dive into conditional statements, including if, if/else, and the versatile ternary operator. Explore the switch statement for multiple condition handling and uncover the magic of for, while, and do/while loops. Understand how break and continue can control loop execution. Labels and the for/in loop allow for advanced iteration techniques, while the for/of loop simplifies iterating over iterable data structures. This guide provides a complete overview of JavaScript's core concepts, essential for mastering web development.

JavaScript Operators, Loops, and Flow Control: A Comprehensive GuideJavaScript Operators, Loops, and Flow Control: A Comprehensive Guide

Assignment Operators

Using = for Variable Assignment

Arithmetic Operators

Arithmetic Operators Include:

  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • / (Division)
  • % (Modulus)
let a = 5, b = 3;
console.log(a * b); // 15
console.log(a % b); // 2

Compound Operators

Compound Operators Include:

  • *=
  • /=
  • +=
  • -=
  • %=

You can use these to shorthand arithmetic operations, like n *= 2 is equivalent to n = n * 2.

let n = 2;
n *= 2;
console.log(n);

Unary Operators

Prefix Operations

Prefix operations are executed first in an expression.

let n = 1;
++n;
console.log(n);

--n;
console.log(n);

Using ++n is a shorthand for n = n + 1.

Postfix Operations

Postfix operations are executed last in an expression.

let n = 2;
let f = 30 + ++n;
console.log(f);

Comparison Operators

Comparison operators allow you to compare values. Here are some examples:

let a = 1, b = 2, c = '1';

console.log(a < b); // true
console.log(a == b); // false
console.log(a == c); // true
console.log(a === c); // false
console.log(a == true); // true
console.log(a === true); // false

Conditional Statement Example

Prevent age from exceeding 90 years:

<input type="text" name="age" />
<span id="msg"></span>
<script>
  let span = document.querySelector("#msg");
  document
    .querySelector('[name="age"]')
    .addEventListener("keyup", function() {
      span.innerHTML = this.value >= 90 ? "Age cannot exceed 90 years" : "";
    });
</script>

Logical Operators

Logical AND

Using && to represent logical AND. The expression is true when both sides are true.

let a = true, b = true;
if (a && b) {
    console.log('Expression is true');
}

Logical OR

Using || to represent logical OR. The expression is true if either side is true.

let a = true, b = false;
if (a || b) {
    console.log('Expression is true');
}

Logical NOT

Using ! to represent logical NOT. It reverses the value.

let a = true, b = false;
if (a && !b) {
    console.log('Expression is true');
}

Operator Precedence

You can use parentheses () to control operator precedence:

console.log(true || false && false); // true
console.log((true || false) && false); // false

Password Matching Example

Matching passwords and displaying an error message:

<input type="text" name="password" />
<input type="text" name="confirm_password" />
<br />
<span name="msg"></span>
<script>
  function queryByName(name) {
    return document.querySelector(`[name='${name}']`);
  }
  let inputs = document.querySelectorAll(
    "[name='password'],[name='confirm_password']"
  );

  [...inputs].map(item => {
    item.addEventListener("keyup", () => {
      let msg = "";
      if (
        queryByName("password").value !=
          queryByName("confirm_password").value ||
        queryByName("password").value.length < 5
      ) {
        msg = "Passwords do not match or are too short";
      }
      queryByName("msg").innerHTML = msg;
    });
  });
</script>

Short-Circuit Evaluation

Example using short-circuit evaluation:

let a = true, f = false;
console.log(a || f); // true
let a = true, f = false;
console.log(f && a); // false

Using short-circuit evaluation for assignment:

let sex = prompt("What is your gender?") || "Secret";
console.log(sex);

Control Flow

if Statement

Execute a code block if a condition is true.

let state = true;
if (true) {
    console.log('Expression is true');
}

You can omit braces {} if there's only one statement:

let state = true;
if (true)
    console.log('Expression is true');
console.log('Always displayed content');

if/else Statement

Example of using multiple conditions to determine password strength:

<body>
  <input type="password" name="title" />
  <span></span>
</body>
<script>
  let input = document.querySelector("[name='title']");
  input.addEventListener("keyup", function() {
    let length = this.value.length;
    let msg;
    if (length > 10) {
      msg = "Password is very strong";
    } else if (length > 6) {
      msg = "Password is moderately strong";
    } else {
      msg = "This password is weak";
    }
    document.querySelector("span").innerHTML = msg;
  });
</script>

Ternary Operator

A shorthand for if statements:

let n = true ? 1 : 2;
console.log(n); // 1

let f = true ? (1 == true ? 'yes' : 'no') : 3;
console.log(f); // yes

Setting initial values for creating a div element using the ternary operator:

function div(options = {}) {
  let div = document.createElement("div");
  div.style.width = options.width ? options.width : "100px";
  div.style.height = options.height ? options.height : "100px";
  div.style.backgroundColor = options.bgcolor ? options.bgcolor : "red";
  document.body.appendChild(div);
}
div();

switch Statement

A structured way to use if with multiple conditions:

let name = 'Video';
switch (name) {
    case 'Product':
        console.log('zgycms.com');
        break;
    case 'Video':
        console.log('zguyun.com');
        break;
    default:
        console.log('houdunwang.com');
}

Using multiple case values together:

let error = 'warning';
switch (error) {
  case 'notice':
  case 'warning':
      console.log('Warning or Notice');
      break;
  case 'error':
      console.log('Error');
}

Using expressions in switch and case:

function message(age) {
  switch (true) {
    case age < 15:
      console.log("Child");
      break;
    case age < 25:
      console.log("Teenager");
      break

;
    case age < 40:
      console.log("Young Adult");
      break;
    case age < 60:
      console.log("Middle-Aged");
      break;
    case age < 100:
      console.log("Elderly");
      break;
    default:
      console.log("Age Output Error");
  }
}
message(10);

Example without break in switch:

switch (1) {
  case 1:
    console.log(1);
  case 2:
    console.log(2);
  default:
    console.log("Default");
}

while Loop

A loop that executes a statement as long as a specified condition is true:

let row = 5;
document.write(`<table border="1" width="100">`);
while (row-- != 0) {
  document.write(`<tr><td>${row}</td></tr>`);
}
document.write(`</table>`);

do/while Loop

A loop that always executes its block of code at least once:

function zgy(row = 5) {
  let start = 0;
  do {
    let n = 0;
    do {
      document.write("*");
    } while (++n <= start);
    document.write("<br/>");
  } while (++start <= row);
}
zgy();

for Loop

A loop that is often used for a specific number of iterations:

for (let i = 10; i > 0; i--) {
    for (let n = 0; n < i; n++) {
        document.write('*');
    }
    document.write("<br/>");
}

Creating a Pascal's Triangle using a for loop:

for (let i = 1; i <= 5; i++) {
  for (let n = 5 - i; n > 0; n--) {
      document.write('^');
  }
  for (let m = i * 2 - 1; m > 0; m--) {
      document.write('*');
  }
  document.write("<br/>");
}

Omitting some parameters in a for loop:

let i = 1;
for (; i < 10; ) {
  console.log(i++);
}

break/continue Statements

Using break to exit a loop and continue to skip the current iteration:

for (let i = 1; i <= 10; i++) {
  if (i % 2) continue;
  console.log(i);
}

let count = 0, num = 3;
for (let i = 1; i <= 10; i++) {
  if (i % 2) {
    console.log(i);
    if (++count == num) break;
  }
}

Labels

Labels allow you to use continue and break to jump to a specific location in your code:

zguyun: for (let i = 1; i <= 10; i++) {
  zgycms: for (let n = 1; n <= 10; n++) {
    if (n % 2 != 0) {
      continue zgycms;
    }
    console.log(i, n);
    if (i + n > 15) {
      break zguyun;
    }
  }
}

for/in Loop

Used to iterate over the properties of an object. Not recommended for arrays.

Iterating over an array:

let zgy = [
  { title: "Chapter 1: Exploring the JavaScript Abyss", lesson: 3 },
  { title: "Setting Up a Productive Programming Environment with Ubuntu 19.10", lesson: 5 },
  { title: "Creating a Responsive Layout with Media Queries", lesson: 8 }
];
document.write(`
  <table border="1" width="100%">
  <thead><tr><th>Title</th><th>Lessons</th></thead>
`);
for (let key in zgy) {
  document.write(`
  <tr>
  <td>${zgy[key].title}</td>
  <td>${zgy[key].lesson}</td>
  </tr>
  `);
}
document.write("</table>");

Iterating over an object's properties:

let info = {
  name: "ZGY",
  url: "zguyun.com"
};
for (const key in info) {
  if (info.hasOwnProperty(key)) {
    console.log(info[key]);
  }
}

Iterating over all properties of the window object:

for (name in window) {
  console.log(window[name]);
}

for/of Loop

Used to iterate over iterable data structures like arrays, strings, maps, sets, etc. Unlike for/in, it retrieves the values instead of the indices.

Iterating over an array:

let arr = [1, 2, 3];
for (const iterator of arr) {
    console.log(iterator);
}

Iterating over a string:

let str = 'zguyun';
for (const iterator of str) {
    console.log(iterator);
}

Using for/of to iterate over an array with entries:

const zgy = ["zgycms", "zguyun"];

for (const [key, value] of zgy.entries()) {
  console.log(key, value); // This allows for easy iteration
}

Using for/of to iterate over DOM elements:

<body>
  <ul>
    <li></li>
    <li></li>
  </ul>
</body>
<script>
  let lis = document.querySelectorAll("li");
  for (const li of lis) {
    li.addEventListener("click", function() {
      this.style.backgroundColor = "red";
    });
  }
</script>

Reference:

Learn more:

Article Link:https://zguyun.com/blog/javascript-operators-loops-and-flow-control-a-comprehensive-guide/
ZGY:Share more fun programming knowledge.