JavaScript : Operators, Conditionals and Functions (Part 2)

 

JavaScript 101: Making Decisions and Reusing Code (Part 2)

Welcome back! In Part 1, we covered the absolute basics: what JavaScript is, how to log messages to the console, and how to store information in variables using let and const. We built the foundation.

Now, it's time to start building on it. Storing data is great, but the real power comes when we can do things with that data. In this session, we're going to learn how to perform calculations, make comparisons, and teach our programs to make decisions. We'll also learn the secret to writing efficient, reusable code with functions.

Let's get started!

What You'll Learn in This Session:

  • How to perform math with Arithmetic Operators.

  • The importance of Operator Precedence (the order of operations).

  • How to compare values using Relational and Logical Operators.

  • How to control the flow of your program with  statements.

  • How to write reusable blocks of code called Functions.


Doing the Math: Expressions and Arithmetic Operators

An expression is any piece of code that results in a single value.

  • 10 is an expression. Its value is 10.

  • "hello" is an expression. Its value is "hello".

  • 5 + 3 is an expression. Its value is 8.

The symbols that perform actions in expressions, like the + sign, are called operators. Let's start with the ones you already know from math class: Arithmetic Operators.

Imagine you're tracking a student's test scores.

const mathMarks = 90;
const scienceMarks = 80;

// We can use the addition operator (+) to find the total
const totalMarks = mathMarks + scienceMarks;

console.log(totalMarks); // Output: 170

Here are the basic arithmetic operators in JavaScript:

OperatorNameExampleResult
+Addition10 + 515
-Subtraction10 - 55
*Multiplication10 * 550
/Division10 / 52
%Modulus10 % 31

The "What's Left Over?" Operator: Modulus (%)

The Modulus operator (%) might be new to you. It performs division but gives you the remainder. It's incredibly useful.

Adaptive Example: Imagine you have 10 cookies to share equally among 3 friends.

  • Each friend gets 3 cookies (3 * 3 = 9).

  • There will be 1 cookie left over.

That's what Modulus tells you!

console.log(10 % 3); // Output: 1 (The remainder when 10 is divided by 3)
console.log(12 % 2); // Output: 0 (12 is an even number, so no remainder)

The Order of Operations: Operator Precedence

What is the result of this expression?

let result = 3 + 4 * 5;

Is it 7 * 5 = 35? Or is it 3 + 20 = 23?

Just like in school math (remember PEMDAS/BODMAS?), JavaScript has a defined order of precedence. Multiplication and Division are done before Addition and Subtraction. So, the correct answer is 23.

The general order is:

  1. Brackets : Anything in parentheses is done first.

  2. Exponentiation : (e.g., 2 ** 3 is 2 to the power of 3).

  3. Multiplication : (Done left-to-right).

  4. Addition : (Done left-to-right).

// Multiplication first: 4 * 5 = 20. Then addition: 3 + 20.
console.log(3 + 4 * 5); // Output: 23

// Exponentiation first: 2 ** 3 = 8.
// Then Multiplication: 8 * 4 = 32.
// Then Division: 32 / 5 = 6.4.
// Finally, Addition: 1 + 6.4.
console.log(1 + 2 ** 3 * 4 / 5); // Output: 7.4

Pro Tip: When in doubt, use parentheses () to make the order clear. (3 + 4) * 5 is very different from 3 + (4 * 5).


Making Comparisons: Relational and Logical Operators

Now that we can work with numbers, let's compare them. Relational Operators check the relationship between two values and always return a boolean (true or false).

Adaptive Example: Think of a bouncer at a club checking your ID to see if you can enter. The question is, "Is your age 21 or greater?" The answer can only be true or false.

let myAge = 25;
let entryAge = 21;

console.log(myAge >= entryAge); // Output: true

Here are the key relational operators:

OperatorMeaningExampleResult
>Greater than10 > 5true
<Less than10 < 5false
>=Greater than or equal to10 >= 10true
<=Less than or equal to10 <= 5false
===Strictly equal to5 === 5true
!==Strictly not equal to5 !== '5'true

The Most Important Comparison: === vs. ==

This is one of the most common interview questions for junior developers!

  • == (Loose Equality): Only checks if the values are the same. It will try to convert types to match.

  • === (Strict Equality): Checks if both the values AND the data types are the same.

Adaptive Example: Is the number 5 the same as the text '5'?

console.log(5 == '5');  // Output: true. Loose equality says "Yeah, they both represent five."
console.log(5 === '5'); // Output: false. Strict equality says "No, one is a number, the other is text."

Best Practice: To avoid unexpected bugs, always use  for comparisons.

Combining Comparisons: Logical Operators

What if you need to check multiple conditions? For example, to get a movie ticket discount, you might need to be a student OR a senior.

Logical Operators let you combine boolean expressions.

  1. && (AND): Returns true only if both sides are true.

    • Example: To log into a secure system, usernameCorrect === true && passwordCorrect === true.

  2. || (OR): Returns true if at least one side is true.

    • Example: To get on the ride, heightInCm > 120 || hasAdultAccompaniment === true.

let hasCoupon = true;
let isMember = false;

// Do I get a discount? (coupon AND member)
console.log(hasCoupon && isMember); // Output: false

// Can I enter? (coupon OR member)
console.log(hasCoupon || isMember); // Output: true

Making Decisions: The if...else Statement

Now we have all the tools we need to make our program intelligent. The if...else statement allows you to run different blocks of code based on a condition.

The structure is simple:
if (this condition is true) {
// ...run this code.
else {
// ...otherwise, run this code instead.
}

Let's put our bouncer example into a full statement:

let personAge = 19;
const entryAge = 21;

if (personAge >= entryAge) {
  console.log("Welcome to the club!");
} else {
  console.log("Sorry, you are not old enough to enter.");
}
// Output: Sorry, you are not old enough to enter.

The code inside the if block only runs if the condition is true. Otherwise, the code inside the else block runs.


Don't Repeat Yourself: An Introduction to Functions

Imagine you're building a calculator app. You need a feature to find the square of a number (e.g., 3² = 9). You could write:

console.log(3 ** 2);
console.log(7 ** 2);
console.log(24 ** 2);

But this is repetitive. What if you need to calculate the square 100 times? And what if you later decide to calculate the cube instead? You'd have to change the code in 100 different places!

This is where functions come in.

function is a reusable block of code that performs a specific task. You can "call" it whenever you need it.

Adaptive Example: A function is like a recipe.

  • Defining the function is writing down the recipe (ingredients, steps).

  • Calling the function is actually following the recipe to bake a cake.

Let's create a function to calculate the square of any number.

// 1. DEFINE the function (write the recipe)
function calculateSquare(number) {
  // The 'return' keyword sends the result back out of the function
  return number * number;
}

// 2. CALL the function (use the recipe)
let result1 = calculateSquare(3);  // The function runs with 'number' = 3
let result2 = calculateSquare(7);  // The function runs with 'number' = 7
let result3 = calculateSquare(24); // The function runs with 'number' = 24

console.log(result1); // Output: 9
console.log(result2); // Output: 49
console.log(result3); // Output: 576

Parameters vs. Arguments

This is another key concept and common interview question.

  • Parameter: The variable name inside the function's parentheses when you define it (e.g., number). It's a placeholder, like an ingredient name in a recipe.

  • Argument: The actual value you pass into the function when you call it (e.g., 3724). It's the real ingredient you use.

Sometimes, a function doesn't need any input. These are called non-parametric functions.

// A function with no parameters
function sayHello() {
  console.log("Hello! Welcome to the application.");
}

// Call it
sayHello(); // Output: Hello! Welcome to the application.

Conclusion & What's Next

Incredible progress! You've moved from simply storing data to manipulating it, comparing it, and controlling your program's flow.

Today you learned:

  • How to use operators to perform math (+-*/%) and make comparisons (===>&&||).

  • How if...else statements use true/false conditions to make decisions.

  • How functions package up code so you can reuse it easily, making your programs organized and powerful.

You now have the core building blocks for almost any program you can imagine. In our next session, we'll explore how to make our programs perform actions over and over again using loops, and how to store lists of data in arrays.

Keep experimenting in the console and get ready for the next step

Comments

Popular posts from this blog

JavaScript: Data Types and Variables (Part 1)

JavaScript : Acing the Interview - The Ultimate Q&A Guide (Part 11)

JavaScript : Loops and Arrays (Part 4)