Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Operators for UI Logic

Hello! Welcome back to our journey into JavaScript fundamentals.

In our last lesson, we covered the essential "nouns" of JavaScript: the primitive data types like string, number, and boolean that represent the information in an application.

Today, we'll learn about the "verbs": the operators that let us work with that data. The goal for this lesson is to use arithmetic, comparison, and logical operators to perform calculations and create conditions for UI logic. These operators are the foundation for adding interactivity to your designs, from calculating a shopping cart total to deciding whether to show an error message.

Recap: Data Types

As a quick reminder, we've learned about:

  • Variables declared with let (for values that can change) and const (for constant values).
  • Data Types like string (for text), number (for quantities), and boolean (true/false for toggles).

Today, we'll see how to manipulate and compare these values.

1. Arithmetic Operators: The Math of UI

Arithmetic operators are used to perform mathematical calculations. As a designer, you often need the UI to perform calculations, such as determining the total price of items in a cart, figuring out the dimensions of an element, or counting remaining characters in a text field.

Let's start with a quick video that covers the basic arithmetic operators in JavaScript.

JavaScript - Arithmetic Operators - W3Schools.com

This short video from w3schools.com provides a clear and concise overview of JavaScript's arithmetic operators.

Watch the entire video. It covers addition, subtraction, multiplication, division, and a few others that are very useful.

As you saw, the main arithmetic operators are:

Operator Name Example Description
+ Addition 10 + 5 Adds two numbers.
- Subtraction 10 - 5 Subtracts one number from another.
* Multiplication 10 * 5 Multiplies two numbers.
/ Division 10 / 5 Divides one number by another.
% Remainder 10 % 3 Returns the remainder of a division (result is 1).
** Exponentiation 10 ** 2 Raises a number to the power of another (10²).

Here they are in action:

const itemPrice = 15;
const quantity = 3;
const shippingCost = 8;

const subtotal = itemPrice * quantity; // 15 * 3 = 45
const total = subtotal + shippingCost; // 45 + 8 = 53

console.log("Subtotal:", subtotal); // Outputs: Subtotal: 45
console.log("Total:", total);     // Outputs: Total: 53

Operator Precedence

Just like in school mathematics, JavaScript has an order of operations. Multiplication (*) and division (/) are performed before addition (+) and subtraction (-). You can use parentheses () to control the order.

let calculation = 10 + 5 * 2; // 5 * 2 is done first, so this is 10 + 10 = 20
let controlledCalculation = (10 + 5) * 2; // 10 + 5 is done first, so this is 15 * 2 = 30

2. Comparison Operators: Asking True/False Questions

Comparison operators are used to compare two values. The result of a comparison is always a boolean value: true or false. This is the core of all decision-making in an application. Should a "submit" button be enabled? Is the user's password long enough? Does the cart have items in it?

This next video introduces booleans and then dives into the comparison operators you'll use to produce them.

#6 JavaScript for Beginners: Booleans, Comparison and Logical Operators

This video from Programiz explains booleans and then clearly demonstrates the different comparison operators with code examples.

Please watch the first two sections of the video: Introduction to Booleans (00:00 - 02:34): A quick refresher on the boolean data type. Comparison Operators (02:34 - 10:32): Pay close attention to the different operators and how they work. The distinction between == and === is especially important.

Strict vs. Loose Equality: A Crucial Distinction

As the video explained, JavaScript has two sets of equality operators.

  • Strict Equality (=== and !==): Compares both the value and the data type. This is almost always what you want.
  • Loose Equality (== and !=): Tries to convert the values to a common type before comparing. This can lead to unexpected results.

Best Practice: Always use the strict equality operators (=== and !==) to avoid bugs.

const itemsInCart = 0;
const formInput = "5";

// Comparison examples
console.log(itemsInCart > 0);       // false
console.log(itemsInCart === 0);     // true
console.log(formInput === 5);       // false (string "5" is not the same type as number 5)
console.log(formInput == 5);        // true (loose equality converts the string to a number, can be confusing!)

3. Logical Operators: Combining Conditions

Often, a single condition isn't enough. You might need to check if a user is logged in and is an administrator, or if an error message should appear because a field is empty or the input is invalid. Logical operators let you combine multiple boolean expressions into a single true or false result.

Let's continue with the same video, which now covers the three logical operators.

#6 JavaScript for Beginners: Booleans, Comparison and Logical Operators

This final segment of the Programiz video explains the AND, OR, and NOT logical operators.

Watch the section on Logical Operators (10:32 - 14:52). Focus on how &&, ||, and ! are used to combine or invert boolean values.

Here's a summary of the logical operators:

Operator Name Example Description
&& AND isLoggedIn && isAdmin Returns true only if both sides are true.
` ` OR
! NOT !isFormSubmitted Inverts a boolean value (true becomes false, false becomes true).

Let's see a practical example related to UI logic:

const stockCount = 5;
const hasCoupon = false;
const isLoggedIn = true;

// A "Buy Now" button should only be active if the item is in stock AND the user is logged in.
const canPurchase = stockCount > 0 && isLoggedIn;
console.log("Can purchase?", canPurchase); // true, because 5 > 0 is true AND isLoggedIn is true.

// A special offer is shown if the user has a coupon OR the item is low in stock (less than 10).
const showSpecialOffer = hasCoupon || stockCount < 10;
console.log("Show offer?", showSpecialOffer); // true, because hasCoupon is false BUT stockCount < 10 is true.

// Show a "Please log in" message if the user is NOT logged in.
const needsLoginMessage = !isLoggedIn;
console.log("Show login message?", needsLoginMessage); // false, because isLoggedIn is true, and !true is false.

Your Turn: Writing UI Logic

Let's apply these concepts to a few scenarios you might encounter as a designer. For each one, write a single line of JavaScript that uses operators to produce a true or false value.

Scenario 1: A user is creating a password. For the password to be valid, it must be at least 8 characters long.
const password = "short";
const isPasswordValid = /* Your code here */;

Scenario 2: A "Clear All" button in a notification panel should only be visible if there is at least one notification.
const notificationCount = 5;
const isClearButtonVisible = /* Your code here */;

Scenario 3: A user gets free shipping if their cart total is over $50 or if they have a "free shipping" coupon.
const cartTotal = 62.50;
const hasFreeShippingCoupon = false;
const getsFreeShipping = /* Your code here */;

Click to see the solutions.
// Scenario 1
const password = "short";
const isPasswordValid = password.length >= 8; // false
console.log("Is password valid?", isPasswordValid);

// Scenario 2
const notificationCount = 5;
const isClearButtonVisible = notificationCount > 0; // true
console.log("Is clear button visible?", isClearButtonVisible);

// Scenario 3
const cartTotal = 62.50;
const hasFreeShippingCoupon = false;
const getsFreeShipping = cartTotal > 50 || hasFreeShippingCoupon; // true
console.log("Gets free shipping?", getsFreeShipping);

Conclusion

Excellent work! You've just learned the fundamental tools for creating logic in JavaScript.

Key Takeaways:

  • Arithmetic Operators (+, -, *, /, %) perform calculations on numbers.
  • Comparison Operators (===, !==, >, <, >=, <=) compare values and result in true or false.
  • Logical Operators (&&, ||, !) combine or invert boolean values to create more complex rules.
  • Always prefer strict equality (===) over loose equality (==) to prevent bugs.

These operators are the building blocks for making your applications responsive and intelligent. You've learned how to ask the questions; in our next lesson, we'll learn how to act on the answers using conditional logic (if/else statements). This will allow us to execute different code and show different UI based on the true or false results we generated today.

Can't find a good explanation? Sign up and we'll make it for you

Sign up