JavaScript : Operators, Conditionals and Functions (Part 2)
Get link
Facebook
X
Pinterest
Email
Other Apps
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 totalconst totalMarks = mathMarks + scienceMarks;
console.log(totalMarks); // Output: 170
Here are the basic arithmetic operators in JavaScript:
Operator
Name
Example
Result
+
Addition
10 + 5
15
-
Subtraction
10 - 5
5
*
Multiplication
10 * 5
50
/
Division
10 / 5
2
%
Modulus
10 % 3
1
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:
Brackets : Anything in parentheses is done first.
Exponentiation : (e.g., 2 ** 3 is 2 to the power of 3).
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:
Operator
Meaning
Example
Result
>
Greater than
10 > 5
true
<
Less than
10 < 5
false
>=
Greater than or equal to
10 >= 10
true
<=
Less than or equal to
10 <= 5
false
===
Strictly equal to
5 === 5
true
!==
Strictly not equal to
5 !== '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.
&& (AND): Returns true only if both sides are true.
Example: To log into a secure system, usernameCorrect === true && passwordCorrect === true.
|| (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:
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.
A 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)functioncalculateSquare(number) {
// The 'return' keyword sends the result back out of the functionreturnnumber * number;
}
// 2. CALL the function (use the recipe)let result1 = calculateSquare(3); // The function runs with 'number' = 3let result2 = calculateSquare(7); // The function runs with 'number' = 7let result3 = calculateSquare(24); // The function runs with 'number' = 24console.log(result1); // Output: 9console.log(result2); // Output: 49console.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., 3, 7, 24). 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 parametersfunctionsayHello() {
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
JavaScript 101: Your First Step into the World of Code (Part 1) Welcome to the start of your programming journey! If you've ever wondered how websites go from being static pages to interactive, dynamic experiences, you're in the right place. The magic behind it all is a powerful language called JavaScript . This series is designed for absolute beginners. We'll start from scratch, and by the end of this first post, you'll not only understand what JavaScript is but also write your very first lines of code. Ready? Let's get our laptops ready and dive in! What You'll Learn in This Session: Why we need JavaScript and where it's used. How to write and see the output of your first program. The basic "ingredients" of code: Primitive Data Types. How to store information using Variables ( var , let , and const ). The do's and don'ts of naming your variables. Why Do We Even Need JavaScript? Imagine you're building a house. HTML (HyperText Marku...
JavaScript 101: Acing the Interview - The Ultimate Q&A Guide (Part 11) Welcome to the final, and perhaps most practical, session of our JavaScript 101 series. You've learned the syntax, mastered the concepts, and even built a final project. Now, it's time to learn how to articulate that knowledge. Acing a technical interview isn't just about knowing the right answer; it's about explaining it clearly, confidently, and with examples that demonstrate true understanding. This post is your personal interview prep guide. We will cover the most common and crucial junior developer interview questions that have been touched upon throughout this series. We'll break down not just what to say, but how to say it, using real-world analogies to make your answers memorable and impressive. Acing Your Answers: The Structure for Success For each question, a strong answer generally follows this structure: Direct Definition: Start with a clear, concise definition. Key Diffe...
JavaScript 101: Automating Tasks with Loops & Managing Data with Arrays (Part 4) Hello and welcome back! In our last session, we leveled up our program's intelligence with advanced decision-making and took a deep dive into manipulating text with strings. You've learned how to make your code smart. Now, it's time to make it powerful and efficient . Imagine you had to send a personalized email to 1,000 users or calculate the total price of 50 items in a shopping cart. Doing this one by one would be impossible. This is where we introduce two of the most fundamental concepts in all of programming: Loops for automating repetitive tasks, and Arrays for managing lists of data. When you combine loops and arrays, you unlock the ability to process huge amounts of information with just a few lines of code. Let's get started! What You'll Learn in This Session: How to stop repeating yourself using the loop . How to create and manage ordered lists ...
Comments
Post a Comment