🎮Leveling Up with JavaScript: Operators, Conditionals and Loops🕹️
Tags: javascript, webdev, learning, beginners
Published: 2024-01-25 18:16:15

Hello, Code Warriors! 🎉 Today, we're stepping into the JavaScript battleground to tackle Operators, Conditionals, and Loops. Get ready to level up your JavaScript skills, and remember - in the world of JavaScript, even the smallest operator can have a big impact! 🌟

---

## 🎮 Mastering JavaScript Operators

Operators in JavaScript are the magical spells that perform operations on our values. Let's break down these mystical entities!

### Arithmetic Operators: The Basic Spell Book 📖

From conjuring the sum of two numbers with + to harnessing the power of exponentiation with **, arithmetic operators are your weapons of choice for numerical wizardry. 🧙‍♂️

[JavaScript.info — Operators](https://javascript.info/operators)

The following math operations are supported:

- Addition (`+`) :

```javascript
console.log(10+2)
//Output: 12
```


- Subtraction (`-`) :

```javascript
console.log(10-2)
//Output: 8
```


- Multiplication (`*`) :

```javascript
console.log(10*2)
//Output: 20
```


- Division (`/`) :

```javascript
console.log(10/2)
//Output: 5
```


- Remainder (`%`) : The remainder operator %, despite its appearance, is not related to percents. The result is the remainder of integer divsion of two operands.

```javascript
console.log(10%2)
//Output: 0
```


- Exponentiation (`**`) : The exponentiation operator raises a to the power b or here `10` to the power of `2` .

```javascript
console.log(10**2)
//Output: 100
```


#### Quirky Behavior😜


![Meme regarding quirky behavior of js for arithmetic operators](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h58afxomnpsw7hpzp7fd.png)


```javascript
let stringConcatenation = "10" + 5;  // Result: "105"
let subtractionSurprise = 10 - "5";  // Result: 5
```

Welcome to JavaScript, the magical realm where arithmetic operators have a mind of their own. Behold the addition operator (‘+’), a versatile performer that can switch between adding numbers and joining strings, blurring the lines between math and art. Watch the amazing spectacle of “10” + 5, resulting in the unexpected fusion of “105”! And let’s not forget the subtraction operator (‘-’), which, when confronted with a string, unleashes its inner translator and gracefully produces numerical results, like a puzzle waiting to be cracked.


### Assignment Operators: Commanding the Variables 💼

Assignment operators equip variables with values. They’re the quartermasters of JavaScript, ensuring every variable is ready for battle. `=` is the basic assignment operator, but why just assign when you can add (`+=`) or subtract (`-=`) at the same time? Efficiency is key on the battlefield! 💪

```javascript
let healthPoints = 100;
healthPoints += 20; // Power up!
console.log(healthPoints); // 120
```


### Comparison Operators: The Gatekeepers 🚪

Comparison operators (`==`, `===`, `!=`, `!==`, `>`, `<`, `>=`, `<=`) are the gatekeepers of JavaScript. They compare two values and decide whether to let the code pass through or not. Remember, `===` and `!==` are the strict bouncers - they check for type as well as value! All comparison operators return a `Boolean` value!

[JavaScript.info — Comparison Operators](https://javascript.info/comparison)

- **Equality(==):** This operator is used to compare the equality of two operands. If equal then the condition is true otherwise false.

> Syntax: x == y


- **Strict equality(===):** This operator is used to compare the equality of two operands with type. If both value and type are equal then the condition is true otherwise false.

> Syntax: x === y


- **Strict inequality(!==):** This operator is used to compare the inequality of two operands with type. If both value and type are not equal then the condition is true otherwise false.

> Syntax: x !== y


- **Greater than operator(>):** This operator is used to check whether the left side value is greater than the right side value. If value is greater then the condition is true otherwise false.

> Syntax: x > y


- **Greater than or equal operator(>=):** This operator is used to check whether the left side operand is greater than or equal to the right side operand. If value is greater than or equal, then the condition is true otherwise false.

> Syntax : x >= y


- **Less than operator(<):** This operator is used to check whether the left side value is less than right side value. If yes then the condition is true otherwise false.

> Syntax: x < y


- **Less than or equal operator(<=):** This operator is used to check whether the left side operand value is less than or equal to the right side operand value. If yes then the condition is true otherwise false.

> Syntax: x <= y

```javascript
console.log(2 > 1);  // true 
console.log(2 == 1); // false
console.log(2 == "2"); //true
console.log(2 != 1); // true
console.log(2 === 2); // false
console.log(2 !== "2"); // true
console.log(2 > 1); //true
console.log(2 >= 2); //true
console.log(2 < 1); //false
console.log(2 <= 2); //true
```



![JavaScript meme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fu2zas3t1a8arhjyr8jx.jpg)


### Logical Operators: Mapping Strategy 🧭

Logical operators (`&&`, `||`, `!`) are the strategists of the JavaScript army, mapping out the logic between variables or values. They're crucial in making tactical decisions on the fly. ⚔️

[JavaScript.info — Logical Operators](https://javascript.info/logical-operators)

- **NOT(!=):** It reverses the boolean result of the operand (or condition).

```javascript
let geek = 1;
console.log(!geek); // false
```

The operator converted the value `1` to `Boolean` and it resulted in `true` then after it flipped(inversed) that value and that’s why when we finally alert the value we get `false`.


- **AND(&&):** It evaluates the operands from left to right, for each operand, it will first convert it to a boolean. If the result is false, stops and returns the original value of that operand, otherwise if all were truthy it will return the last truthy value.

```javascript
console.log( 0 && 1 ); // 0
console.log( 1 && 3 ); // 3
console.log( null && true ); // null
console.log( 1 && 2 && 3 && 4); // 4
```


- **OR(||):** It evaluates the operand from left to right, for each operand, it will first convert it to a boolean. If the result is true, stops and returns the original value of that operand. Otherwise if all the values are falsy, it will return the last value.

```javascript
console.log( 0 || 1 ); // 1
console.log( 1 || 3 ); // 1
console.log( null || true ); // true
console.log( -1 || -2 || -3 || -4); // -1
```


> Values that are coerced into true are called truthy, while those coerced into false are called falsy. This whimsical behavior can lead to unexpected outcomes, such as the string “0” being truthy while the number 0 is falsy, and an empty array or object being truthy despite their emptiness. JavaScript’s unique approach to truthy and falsy values keeps developers on their toes, adding a touch of surprise to the coding experience. So, while other languages may stick to the conventional, JavaScript embraces the unconventional, infusing a sense of playfulness into its very core.


### Special Operators: The Secret Weapons 🗝️

JavaScript also boasts of special operators like the nullish coalescing operator (`??`), and optional chaining operator (`?.`). These operators give JavaScript its unique flavor, adding a bit of spice to our code. 🌶️

[Nullish coalescing operator ‘??’ (javascript.info)](https://javascript.info/nullish-coalescing-operator)


- **Nullish coalescing operator(??):** It is a new feature introduced in this ECMA proposal has now been adopted into the official JavaScript Specification. This operator returns the right hand value if the left hand value is null or undefined. If not `null` or `undefined` then it will return left hand value.

> Syntax: `value` ?? `default_value`

```javascript
let power = null;
let defaultPower = 50;
let finalPower = power ?? defaultPower;  // 50
```

- **Optional Chaining operator(?.):** When navigating through deeply nested objects, the optional chaining operator gracefully short-circuits if a property along the chain is null or undefined, gracefully returning undefined without causing a TypeError. With its introduction as part of the ES2020 standard, the optional chaining operator has become a staple in modern JavaScript development, empowering developers to simplify their code and enhance overall readability.

```javascript
// Example of Optional Chaining Operator
const adventurer = {
  name: 'Alice',
  equipment: {
    weapon: {
      type: 'sword',
      damage: 25
    }
  }
};

// Accessing a nested property without optional chaining
// This would throw a TypeError if equipment or weapon is undefined
// const damage = adventurer.equipment.weapon.damage;

// Accessing a nested property with optional chaining
const damage = adventurer.equipment?.weapon?.damage;

console.log(damage);  // Output: 25
```

In this example, the optional chaining operator (?.) gracefully handles the access of nested properties. Without the optional chaining operator, accessing `adventurer.equipment.weapon.damage` directly could potentially lead to a TypeError if `equipment` or `weapon` were to be undefined along the chain.

> The optional chaining operator in JavaScript is a very useful and elegant feature for accessing values from APIs. APIs often return complex nested JSON objects, and the data structure may vary. The optional chaining operator allows developers to traverse the nested properties of the API response safely and avoid ‘undefined’ errors.

---

## JavaScript Conditionals: Navigating the Terrain 🌍

Conditionals in JavaScript are like the quest maps in RPG games. They guide the flow of execution and help us make decisions based on conditions. Let’s start the quest!

### If, Else, Else-If Statements: Choosing the Path 🚶‍♀️

`if` statement is that first step you take towards your quest, `else-if` is the alternative path you can choose, and `else` is the path you take when all else fails. Always remember that in the game of JavaScript, every decision counts!

[Conditional branching: if, ‘?’ (javascript.info)](https://javascript.info/ifelse)


```javascript
let enemy = "Dragon";

if (enemy === "Dragon") {
    // 👈 Using if statement for decision making
    console.log("Equip sword 🗡️");
} else if (enemy === "Wizard") {
    console.log("Equip shield 🛡️");
} else {
    console.log("Run away! 🏃‍♂️");
}
```


### Switch Statements: The Multi-Door Dungeon 🚪

The `switch` statement is like a multi-door dungeon. Based on your choice, only one door will open, leading to treasures untold! 🏦

```javascript
let playerClass = "Rogue";

switch (playerClass) {
    case "Warrior":
        console.log("Equip sword and shield");
        break;
    case "Mage":
        console.log("Prepare the arcane spells");
        break;
    case "Rogue":
        console.log("Sharpen the daggers");
        break;
    default:
        console.log("Choose your class wisely");
}
// Output: Sharpen the daggers
```


### 🎭 Ternary Operator

A quick decision-making potion! A shorthand tale of `if-else`, where the condition unfolds in a swift dance.

```javascript
let healthPoints = 30;
let heroStatus = healthPoints > 0 ? "Alive" : "Defeated";
console.log(heroStatus); // Alive
```

---

## Loops: Running the Gauntlet 🎽

Loops (`for`, `while`, `do...while`) are your endless running tracks. They help perform tasks repeatedly based on a condition. It's like running a gauntlet but in code! 🏃‍♀️

[Loops: while and for (javascript.info)](https://javascript.info/while-for)

- **While loop:** A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.

```javascript
//Syntax

//while (boolean condition)
//{
//   loop statements...
//}

//Example
var i=1;
while(i <= 10)
{
    console.log("Hello World!");
    i++;
}
// This code will output "Hello World" ten times.
```

1. While loop starts with checking the condition. If it is evaluated to be true, then the loop body statements are executed otherwise first statement following the loop is executed. For this reason, it is also called the **Entry control loop**.

2. Once the condition is evaluated to be true, the statements in the loop body are executed. Normally the statements contain an update value for the variable being processed for the next iteration.

3. When the condition becomes false, the loop terminates which marks the end of its life cycle.


- **Do-while loop:** The `do...while` statement creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.

```javascript
//Syntax

// do{
//  statement
//}while(condition);

//Example:
let result = 0;
let i = 5;

do {
  i += 1;
  result = result + i;
} while (i > 5);
console.log(result);
// Output: 6
```

1. The do-while loop starts with the execution of the statement(s). There is no checking of any condition for the first time.

2. After the execution of the statements, and update of the variable value, the condition is checked for a true or false value. If it is evaluated to be true, the next iteration of the loop starts.

3. When the condition becomes false, the loop terminates which marks the end of its life cycle.

4. It is important to note that the do-while loop will execute its statements at least once before any condition is checked, and therefore is an example of the exit control loop.


- **For loop:** For loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy-to-debug structure of looping.

```javascript
//Syntax

//for (initialization condition; testing condition; increment/decrement)
//{
//    statement(s)
//}


//Example
var i;
for (i = 0; i < 10; i++)
{
    console.log("Hello World!");
}
// This code will print "Hello World" ten times.
```

1. **Initialization condition:** Here, we initialize the variable in use. It marks the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only.

2. **Testing Condition:** It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.

3. **Statement execution:** Once the condition is evaluated to be true, the statements in the loop body are executed.
Increment/ Decrement: It is used for updating the variable for the next iteration.

4. **Loop termination:** When the condition becomes false, the loop terminates marking the end of its life cycle.

---

## Conclusion

That’s our journey through the exciting world of JavaScript operators, conditionals, and loops. Remember, JavaScript is a game where every player, from the smallest operator to the largest loop, holds their unique importance. So, keep exploring, keep learning, and let’s meet in the next level of our JavaScript gaming quest! 🎮🚀

Happy Coding! 💻👾