Module 3 - Operators and Expressions

Introduction

JavaScript, one of the most widely used programming languages for web development, relies heavily on the concepts of operators and expressions to perform various tasks and calculations. These fundamental elements are essential for manipulating and transforming data within JavaScript programs, enabling developers to create dynamic and interactive web applications. In this introduction, we'll explore the core concepts of operators and expressions in JavaScript, providing a foundational understanding of how they work and their significance in the language.

Operators in JavaScript:

Operators are symbols used in JavaScript to perform operations on data. These operations can range from basic arithmetic calculations to more complex comparisons and assignments. Operators can be categorized into several types, each with its specific purpose. While we won't delve into specific operators in this introduction, we will discuss the broad categories they fall into:

Arithmetic Operators: 

These operators are used for mathematical calculations, such as addition, subtraction, multiplication, and division. They allow developers to perform tasks like calculating the sum of two numbers or finding the remainder of a division.

Comparison Operators

Comparison operators are used to compare values, determining whether they are equal, not equal, greater than, less than, or a combination of these. These operators are crucial for creating conditional statements and making decisions in your code.

Logical Operators

Logical operators are used to combine or manipulate boolean values, such as true and false. They are essential for building complex conditional statements and controlling the flow of your program.

Assignment Operators

Assignment operators are used to assign values to variables. They also allow for shorthand assignments, making it easier to update the value of a variable based on its current value.

Bitwise Operators

Bitwise operators are used for low-level bit manipulation in numbers. While they are not commonly used in everyday JavaScript programming, they have their applications in specific scenarios.

Expressions in JavaScript:

An expression is a combination of values, variables, and operators that can be evaluated to produce a result. Expressions are the building blocks of JavaScript code, allowing developers to create and manipulate data dynamically. They can be as simple as a single variable or a complex combination of multiple operators and values.

Here are some examples of expressions in JavaScript:

Arithmetic Expression: 

3 + 5 is an arithmetic expression that evaluates to 8. It combines two values using the addition operator.

Variable Assignment Expression: 

let x = 10; is an expression that assigns the value 10 to the variable x. It combines a variable, an assignment operator, and a value.

Comparison Expression: 

age >= 18 is a comparison expression that checks if the variable age is greater than or equal to 18. It combines a variable and a comparison operator.

Complex Expression: 

(x + y) * (z - 5) is a complex expression that combines multiple arithmetic operators and values. It evaluates the result of the enclosed mathematical operations.

Understanding operators and expressions is crucial for writing effective JavaScript code. They are the foundation for performing calculations, making decisions, and creating dynamic behaviors within web applications. By mastering these concepts, developers gain the ability to manipulate data, control program flow, and create interactive and responsive web experiences.



Arithmetic Operators

In JavaScript, arithmetic operators are used to perform mathematical operations on numeric values. These operators allow you to manipulate numbers in various ways, such as addition, subtraction, multiplication, division, and more. Here's a thorough description of all available arithmetic operators in JavaScript, along with their proper usage and examples:

Addition Operator (+):

The addition operator is used to add two numbers together.
Usage: operand1 + operand2

Example:

let sum = 5 + 3; // sum will be 8

Subtraction Operator (-):

The subtraction operator is used to subtract the right operand from the left operand.
Usage: operand1 - operand2

Example:

let difference = 10 - 4; // difference will be 6

Multiplication Operator (*):

The multiplication operator is used to multiply two numbers.
Usage: operand1 * operand2

Example:

let product = 6 * 7; // product will be 42

Division Operator (/):

The division operator is used to divide the left operand by the right operand.
Usage: operand1 / operand2

Example:

let quotient = 20 / 4; // quotient will be 5

Modulus Operator (%):

The modulus operator calculates the remainder when the left operand is divided by the right operand.
Usage: operand1 % operand2

Example:

let remainder = 17 % 5; // remainder will be 2 (17 divided by 5 leaves remainder of 2)

Exponentiation Operator ():**

The exponentiation operator raises the left operand to the power of the right operand.
Usage: operand1 ** operand2

Example:

let result = 2 ** 3; // result will be 8 (2^3 = 8)

Increment Operator (++) and Decrement Operator (--):

The increment operator (++) adds 1 to the operand, and the decrement operator (--) subtracts 1 from the operand.
Usage: ++variable and --variable

Example:

let count = 5;
count++; // count is now 6
count--; // count is now 5 again

These arithmetic operators can be combined with variables, constants, or numeric values to perform a wide range of mathematical calculations in JavaScript. It's important to keep in mind that these operators follow the standard order of operations (PEMDAS/BODMAS), which dictates the sequence in which operations are performed when multiple operators are used together. Parentheses can be used to control the order of evaluation when necessary.

Understanding and using arithmetic operators is essential for performing calculations, solving problems, and building mathematical functionality in JavaScript programs. Whether you're working on simple calculations or complex algorithms, these operators are a fundamental part of the language.



Comparison Operators

Comparison operators in JavaScript are used to compare two values or expressions, determining whether they are equal, not equal, greater than, less than, or a combination of these conditions. These operators return a Boolean value (true or false) based on the comparison. Here's a thorough description of all available comparison operators in JavaScript, along with their proper usage and examples:

Equality Operator (==):

The equality operator checks if two values are equal, performing type coercion if necessary (i.e., converting one or both values to a common type for comparison).
Usage: operand1 == operand2

Example:

let isEqual = 5 == '5'; // isEqual will be true (type coercion converts string '5' to the number 5 for comparison)

Inequality Operator (!=):

The inequality operator checks if two values are not equal, performing type coercion if necessary.
Usage: operand1 != operand2

Example:

let isNotEqual = 5 != '7'; // isNotEqual will be true (type coercion converts string '7' to the number 7 for comparison)

Strict Equality Operator (===):

The strict equality operator checks if two values are equal without type coercion; both the value and the data type must match.
Usage: operand1 === operand2

Example:

let isStrictEqual = 5 === 5; // isStrictEqual will be true (both values are numbers and equal)

Strict Inequality Operator (!==):

The strict inequality operator checks if two values are not equal without type coercion.
Usage: operand1 !== operand2

Example:

let isStrictNotEqual = 5 !== '5'; // isStrictNotEqual will be true (one value is a number, and the other is a string)

Greater Than Operator (>):

The greater than operator checks if the left operand is greater than the right operand.
Usage: operand1 > operand2

Example:

let isGreaterThan = 10 > 7; // isGreaterThan will be true

Less Than Operator (<):

The less than operator checks if the left operand is less than the right operand.
Usage: operand1 < operand2

Example:

let isLessThan = 3 < 6; // isLessThan will be true

Greater Than or Equal To Operator (>=):

The greater than or equal to operator checks if the left operand is greater than or equal to the right operand.
Usage: operand1 >= operand2

Example:

let isGreaterThanOrEqual = 5 >= 5; // isGreaterThanOrEqual will be true

Less Than or Equal To Operator (<=):

The less than or equal to operator checks if the left operand is less than or equal to the right operand.
Usage: operand1 <= operand2

Example:

let isLessThanOrEqual = 8 <= 10; // isLessThanOrEqual will be true

These comparison operators are crucial for making decisions in your JavaScript code. They are often used in conditional statements, such as if statements, to control the flow of your program based on the results of the comparisons. Understanding the differences between the equality operators and the strict equality operators is particularly important to avoid unexpected type coercion behavior.



Logical Operators

Logical operators in JavaScript are used to combine or manipulate boolean values, such as true and false. These operators are essential for building complex conditional statements, controlling the flow of your code, and making decisions based on multiple conditions. Here's a thorough description of all available logical operators in JavaScript, along with their proper usage and examples:

Logical AND (&&) Operator:

The logical AND operator returns true if both operands are true. Otherwise, it returns false.
Usage: operand1 && operand2

Example:

let isTrue1 = true;
let isTrue2 = false;
let result = isTrue1 && isTrue2; // result will be false

Logical OR (||) Operator:

The logical OR operator returns true if at least one of the operands is true. It returns false if both operands are false.
Usage: operand1 || operand2

Example:

let isTrue1 = true;
let isTrue2 = false;
let result = isTrue1 || isTrue2; // result will be true

Logical NOT (!) Operator:

The logical NOT operator is a unary operator that negates the boolean value of its operand. If the operand is true, ! makes it false, and vice versa.
Usage: !operand

Example:

let isTrue = true;
let isFalse = !isTrue; // isFalse will be false

Logical XOR (Exclusive OR) Operator:

JavaScript doesn't have a built-in XOR operator, but you can achieve XOR behavior by using a combination of the logical NOT and logical OR operators. An XOR operation returns true if exactly one of the operands is true.
Usage (XOR): operand1 !== operand2

Example:

let isTrue1 = true;
let isTrue2 = false;
let isXOR = isTrue1 !== isTrue2; // isXOR will be true (exactly one operand is true)

Logical Short-Circuiting:

Logical operators in JavaScript use short-circuit evaluation. This means that in expressions involving && and ||, the second operand is only evaluated if necessary. For &&, if the first operand is false, there's no need to check the second operand because the result will be false. For ||, if the first operand is true, there's no need to check the second operand because the result will be true.

Logical operators are commonly used to create conditional statements and perform actions based on the values of variables. They are integral to decision-making processes and help control the flow of your JavaScript code. Understanding how these operators work and how to combine them effectively is crucial for writing robust and logical code.



Assignment Operators

Assignment operators in JavaScript are used to assign values to variables. They are essential for initializing variables, updating their values, and performing various operations in a concise manner. Here's a thorough description of all available assignment operators in JavaScript, along with their proper usage and examples:

Assignment Operator (=):

The basic assignment operator assigns the value of the right operand to the variable on the left.
Usage: variable = value

Example:

let x = 10; // x is assigned the value 10

Addition Assignment Operator (+=):

The addition assignment operator adds the value of the right operand to the variable on the left and assigns the result to the variable.
Usage: variable += value

Example:

let count = 5;
count += 3; // count is now 8 (5 + 3)

Subtraction Assignment Operator (-=):

The subtraction assignment operator subtracts the value of the right operand from the variable on the left and assigns the result to the variable.
Usage: variable -= value

Example:

let total = 20;
total -= 7; // total is now 13 (20 - 7)

Multiplication Assignment Operator (*=):

The multiplication assignment operator multiplies the variable on the left by the value of the right operand and assigns the result to the variable.
Usage: variable *= value

Example:

let price = 5;
price *= 4; // price is now 20 (5 * 4)

Division Assignment Operator (/=):

The division assignment operator divides the variable on the left by the value of the right operand and assigns the result to the variable.
Usage: variable /= value

Example:

let total = 50;
total /= 5; // total is now 10 (50 / 5)

Modulus Assignment Operator (%=):

The modulus assignment operator calculates the remainder when the variable on the left is divided by the value of the right operand and assigns the result to the variable.
Usage: variable %= value

Example:

let remainder = 17;
remainder %= 5; // remainder is now 2 (17 % 5)

Exponentiation Assignment Operator (=):**

The exponentiation assignment operator raises the variable on the left to the power of the value of the right operand and assigns the result to the variable.
Usage: variable **= value

Example:

let result = 2;
result **= 3; // result is now 8 (2^3)

Assignment operators are fundamental for working with variables in JavaScript. They not only set initial values but also update variables in a concise and efficient manner. These operators are commonly used in loops, calculations, and other operations throughout your code to manage and modify data dynamically.



Bitwise Operators

Bitwise operators in JavaScript are used for low-level bit manipulation of numeric values. While we may not cover their use extensively in this course, they are important to know about as your skill in JavaScript grows. These operators perform operations at the binary level, manipulating individual bits within numbers. While they are not as commonly used in everyday JavaScript programming, they are essential in scenarios where you need to work with binary representations or perform operations at the bit level. Here's a thorough description of all available bitwise operators in JavaScript, along with their proper usage and examples:

Bitwise AND Operator (&):

The bitwise AND operator performs a binary AND operation on each pair of corresponding bits in two numbers. It returns a new number where each bit is 1 if both bits in the same position are 1, otherwise, it's 0.
Usage: operand1 & operand2

Example:

let result = 5 & 3; // result will be 1 (binary: 0101 & 0011 = 0001)

Bitwise OR Operator (|):

The bitwise OR operator performs a binary OR operation on each pair of corresponding bits in two numbers. It returns a new number where each bit is 1 if at least one of the bits in the same position is 1.
Usage: operand1 | operand2

Example:

let result = 5 | 3; // result will be 7 (binary: 0101 | 0011 = 0111)

Bitwise XOR Operator (^):

The bitwise XOR operator performs a binary XOR operation on each pair of corresponding bits in two numbers. It returns a new number where each bit is 1 if the bits in the same position are different.
Usage: operand1 ^ operand2

Example:

let result = 5 ^ 3; // result will be 6 (binary: 0101 ^ 0011 = 0110)

Bitwise NOT Operator (~):

The bitwise NOT operator (also known as the one's complement) inverts all the bits of a number, turning 0s into 1s and 1s into 0s. It operates on a single operand.
Usage: ~operand

Example:

let result = ~5; // result will be -6 (binary: ~0101 = 1010 in two's complement, which represents -6)

Left Shift Operator (<<):

The left shift operator shifts the bits of a number to the left by a specified number of positions, filling the vacant positions with zeros.
Usage: operand << shiftAmount

Example:

let result = 5 << 2; // result will be 20 (binary: 0101 << 2 = 10100)

Right Shift Operator (>>):

The right shift operator shifts the bits of a number to the right by a specified number of positions, filling the vacant positions with the sign bit (the leftmost bit).
Usage: operand >> shiftAmount

Example:

let result = -16 >> 2; // result will be -4 (binary: 11111111111111111111111111110000 >> 2 = 11111111111111111111111111111100)

Zero-Fill Right Shift Operator (>>>):

The zero-fill right shift operator shifts the bits of a number to the right by a specified number of positions, filling the vacant positions with zeros.
Usage: operand >>> shiftAmount

Example:

let result = -16 >>> 2; // result will be 1073741820 (binary: 11111111111111111111111111110000 >>> 2 = 00111111111111111111111111111100)

Bitwise operators are typically used in scenarios where you need to work with binary data, optimize code for efficiency, or perform specific bit-level calculations. They are not as commonly used as other operators in JavaScript but are essential for certain low-level programming tasks.



User Input - Forms

Getting input from users via an HTML form field using JavaScript is a fundamental aspect of web development. This process allows you to collect data, interact with users, and process their inputs within your web application. Here's a thorough description of how to accomplish this task:

1. Create an HTML Form:

Start by creating an HTML form element in your webpage. Forms are used to collect user input. You can use the <form> tag to define the form.

<form id="myForm">
<!-- Form fields go here -->
</form>

2. Add Input Fields:

Inside the form, add input fields that users will interact with. Common types of input fields include text inputs, checkboxes, radio buttons, and more. Use the appropriate HTML tags (e.g., <input>, <textarea>, <select>) for each input type.

<label for="username">Username:</label>
<input type="text" id="username" name="username" />

<label for="password">Password:</label>
<input type="password" id="password" name="password" />

3. Add a Submit Button:

Include a submit button inside the form to allow users to submit their input. The submit button triggers the form submission process.

<input type="submit" value="Submit" />

4. Handle Form Submission:

To collect user input when the form is submitted, you'll need to add an event listener to the form. This event listener can be added in a <script> element at the bottom of your HTML file or in an external JavaScript file. You typically want to prevent the default form submission action to handle it with JavaScript.

<script>
const form = document.getElementById("myForm");

form.addEventListener("submit", function (event) {
event.preventDefault(); // Prevent the default form submission
// Your JavaScript code to handle user input goes here
});
</script>

5. Access Input Values:

Inside the event listener function, you can access the input field values using the value property of the input elements. The name attribute can be used to uniquely identify each input field.

const usernameInput = document.getElementById("username");
const passwordInput = document.getElementById("password");

const username = usernameInput.value;
const password = passwordInput.value;

// Now you can work with 'username' and 'password' values

6. Perform Validation and Processing:

You can perform validation and data processing on the collected user input as needed. Check for data integrity, enforce rules, and execute relevant actions based on the user's input.

if (username && password) {
// Perform validation and processing here
// e.g., sending data to a server, displaying a message to the user, or updating the UI
}

7. Display Feedback:

You can provide feedback to the user based on the results of your validation and processing. This could involve displaying success messages, error messages, or updating the user interface.

if (username && password) {
// Display a success message
alert("Form submitted successfully!");
} else {
// Display an error message
alert("Please fill out both fields.");
}

By following these steps, you can create an HTML form and use JavaScript to collect, process, and provide feedback on user input. This allows you to create interactive and user-friendly web applications that respond to user actions.



User Input - Dialog Box

To get input from users via a dialog box using JavaScript, you can use the window.prompt() or window.confirm() methods. These built-in browser methods allow you to interact with users and collect information in a simple pop-up dialog. Here's a thorough description of how to use these methods to get input from users:

1. Using window.prompt() to Get User Input:

window.prompt() displays a dialog box with an input field and a "OK" and "Cancel" button. It allows you to prompt the user for input and retrieve the entered value.

Here's how to use window.prompt():

const userInput = window.prompt("Please enter your name:", "John Doe");

if (userInput !== null) {
// User clicked "OK" and provided input
console.log("User entered: " + userInput);
} else {
// User clicked "Cancel" or closed the prompt
console.log("User canceled or closed the prompt.");
}

In the above example:

  • The first argument of window.prompt() is the message displayed to the user.
  • The second argument is the default value displayed in the input field. If the user doesn't provide input and clicks "OK," the default value is returned.

2. Using window.confirm() to Get User Confirmation:

window.confirm() displays a dialog box with "OK" and "Cancel" buttons and allows you to get a simple boolean response (true or false) from the user.

Here's how to use window.confirm():

const userConfirmed = window.confirm("Are you sure you want to proceed?");

if (userConfirmed) {
// User clicked "OK" (true)
console.log("User confirmed the action.");
} else {
// User clicked "Cancel" (false)
console.log("User canceled the action.");
}

In the above example:

The argument of window.confirm() is the message or question displayed to the user.

3. Validating User Input:

When using window.prompt(), it's important to validate the user's input, as it can be any text or even an empty string. You can use conditional statements to check for valid input and handle different scenarios accordingly.

For example, to ensure the user provides a non-empty string:

const userInput = window.prompt("Please enter your name:");

if (userInput !== null && userInput.trim() !== "") {
console.log("User entered: " + userInput);
} else if (userInput !== null) {
console.log("User entered an empty string.");
} else {
console.log("User canceled or closed the prompt.");
}

4. Handling User Actions:

Remember to handle user actions, such as clicking "OK" or "Cancel" or closing the dialog box. You can use conditional statements to respond accordingly, performing actions or providing feedback to the user.

Using window.prompt() and window.confirm() is a straightforward way to collect user input and make simple decisions in your JavaScript applications. However, for more complex interactions, you may want to consider creating custom dialog boxes or using more sophisticated modal libraries.



Showing and Hiding Divs

To show and hide <div> elements in response to options selected from an HTML <select> menu using JavaScript, you can follow these steps:

Create the HTML Structure:

First, create the HTML structure for your <select> menu and the corresponding <div> elements that you want to show and hide. Each <div> should have an id or class that you can use to target it with JavaScript.

<label htmlFor="options">Select an Option:</label>
<select id="options">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>

<div id="option1-div">
<!-- Content for Option 1 -->
</div>

<div id="option2-div">
<!-- Content for Option 2 -->
</div>

<div id="option3-div">
<!-- Content for Option 3 -->
</div>

Add CSS for Initial Hiding:

By default, you can hide all the <div> elements using CSS. You can set their display property to none to make them invisible when the page initially loads.

#option1-div,
#option2-div,
#option3-div {
display: none;
}

Write JavaScript for Handling the Selection:

You'll use JavaScript to listen for changes in the <select> menu and show/hide the corresponding <div> elements based on the selected option.

// Get references to the select element and the divs
const select = document.getElementById('options');
const option1Div = document.getElementById('option1-div');
const option2Div = document.getElementById('option2-div');
const option3Div = document.getElementById('option3-div');

// Add an event listener to the select element
select.addEventListener('change', function () {
// Get the selected option's value
const selectedOption = select.value;

// Hide all divs
option1Div.style.display = 'none';
option2Div.style.display = 'none';
option3Div.style.display = 'none';

// Show the corresponding div based on the selected option
if (selectedOption === 'option1') {
option1Div.style.display = 'block';
} else if (selectedOption === 'option2') {
option2Div.style.display = 'block';
} else if (selectedOption === 'option3') {
option3Div.style.display = 'block';
}
});

In this JavaScript code, we:

  1. Get references to the <select> element and all the <div> elements.
  2. Add an event listener to the <select> element to listen for changes.
  3. When a change occurs (an option is selected), we get the selected option's value and hide all the <div> elements.
  4. Then, we show the corresponding <div> based on the selected option.

Testing:

Test your HTML and JavaScript by opening the HTML file in a web browser. When you select different options from the <select> menu, the corresponding <div> elements should be shown and hidden as expected.

By following these steps, you can easily show and hide <div> elements based on the options selected from an HTML <select> menu using JavaScript. This approach allows you to create dynamic and interactive content on your web pages.

Videos for Module 3 - Operators and Expressions

Key Terms for Module 3 - Operators and Expressions

No terms have been published for this module.

Quiz Yourself - Module 3 - Operators and Expressions

Test your knowledge of this module by choosing options below. You can keep trying until you get the right answer.

Skip to the Next Question