Drani Academy – Interview Question, Search Job, Tuitorials, Cheat Sheet, Project, eBook

JavaScript

Tutorials – JavaScript


Chapter 3 – Operators and Expressions


Operators and expressions are fundamental components of JavaScript, allowing you to perform operations on data and create complex logic in your code. In Chapter 3 of our JavaScript guide, we will explore the various operators available in JavaScript, including arithmetic, assignment, comparison, logical, and more. We’ll also delve into the world of expressions and their role in creating dynamic code.

What are Operators?

Operators are special symbols or keywords that perform operations on one or more values, called operands. JavaScript provides a wide range of operators, each serving a specific purpose. Understanding how to use these operators is essential for performing mathematical calculations, making decisions, and manipulating data in your code.
Let’s categorize JavaScript operators based on their functions:

1. Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations, such as addition, subtraction, multiplication, division, and more.

  • Addition (+): Adds two values.
  • Subtraction (-): Subtracts the second value from the first.
  • Multiplication (*): Multiplies two values.
  • Division (/): Divides the first value by the second.
  • Modulus (%): Returns the remainder of a division.
  • Exponentiation ():** Raises the first value to the power of the second.

Examples of Arithmetic Operators:

let x = 10;
let y = 3;
let sum = x + y;  // 13
let difference = x - y;  // 7
let product = x * y;  // 30
let quotient = x / y;  // 3.3333...
let remainder = x % y;  // 1
let power = x ** y;  // 1000

2. Assignment Operators

Assignment operators are used to assign values to variables.

  • Assignment (=): Assigns the value on the right to the variable on the left.

Examples of Assignment Operators:

let age = 30;  // Assigns the value 30 to the variable 'age'

Assignment operators can also be combined with arithmetic operators for concise assignments.

  • Addition Assignment (+=): Adds the right value to the variable on the left and assigns the result to the variable.
let count = 5;
count += 2;  // Equivalent to count = count + 2; Result: 7

3. Comparison Operators

Comparison operators are used to compare two values and return a boolean result (true or false).

  • Equality (==): Checks if two values are equal.
  • Inequality (!=): Checks if two values are not equal.
  • Strict Equality (===): Checks if two values are equal without type conversion.
  • Strict Inequality (!==): Checks if two values are not equal without type conversion.
  • Greater Than (>): Checks if the left value is greater than the right.
  • Less Than (<): Checks if the left value is less than the right.
  • Greater Than or Equal (>=): Checks if the left value is greater than or equal to the right.
  • Less Than or Equal (<=): Checks if the left value is less than or equal to the right.

Examples of Comparison Operators:

let a = 5;
let b = "5";
let isEqual = a == b;  // true (equality)
let isNotEqual = a != b;  // false (inequality)
let isStrictEqual = a === b;  // false (strict equality)
let isStrictNotEqual = a !== b;  // true (strict inequality)
let isGreater = a > 3;  // true (greater than)
let isLess = a < 2;  // false (less than)
let isGreaterOrEqual = a >= 5;  // true (greater than or equal)
let isLessOrEqual = a <= 5;  // true (less than or equal)

4. Logical Operators

Logical operators are used to perform logical operations and return boolean values.

  • Logical AND (&&): Returns true if both operands are true.
  • Logical OR (||): Returns true if at least one operand is true.
  • Logical NOT (!): Inverts the boolean value of the operand.

Examples of Logical Operators:

let x = true;
let y = false;
let resultAnd = x && y;  // false (true && false)
let resultOr = x || y;  // true (true || false)
let resultNot = !x;  // false (!true)

5. Increment and Decrement Operators

Increment and decrement operators are used to increase or decrease the value of a variable by one.

  • Increment (++): Increases the value by 1.
  • Decrement (–): Decreases the value by 1.

These operators can be used as either pre-increment/decrement (operator before the variable) or post-increment/decrement (operator after the variable), and they produce different results.

Examples of Increment and Decrement Operators:

let count = 5;
let preIncrement = ++count;  // Increases 'count' to 6 and returns 6
let postIncrement = count++;  // Returns 6 and then increases 'count' to 7
let preDecrement = --count;  // Decreases 'count' to 6 and returns 6
let postDecrement = count--;  // Returns 6 and then decreases 'count' to 5

6. Ternary (Conditional) Operator

The ternary operator is a concise way to express conditional statements.

  • Ternary (Conditional) Operator (?:): Evaluates a condition and returns one of two values based on the condition’s result.
let isAdult = age >= 18 ? "Adult" : "Minor";

In the example, if age is greater than or equal to 18, the variable isAdult will be assigned the string “Adult”; otherwise, it will be assigned “Minor.”

7. String Concatenation

The + operator can be used for string concatenation, joining two strings together.

let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;  // "John Doe"

8. Bitwise Operators

Bitwise operators are used to manipulate the binary representation of numbers at the bit level. These operators are rarely used in typical web development and are more common in lower-level programming.

9. Other Operators

JavaScript also provides other operators, such as the typeof operator for checking the data type of a value, the instanceof operator for checking if an object is an instance of a particular class or constructor, and the in operator for checking if an object has a specific property.

Operator Precedence

In JavaScript, operators have precedence levels that determine the order in which they are evaluated. When multiple operators are used in an expression, the operator with higher precedence is evaluated first. You can use parentheses to override the default precedence and explicitly specify the order of operations.

Here is a simplified list of operator precedence from highest to lowest:

  • Member Access (.property and [index])
  • Function Call ( () )
  • New ( new )
  • Increment/Decrement ( ++ and )
  • Logical NOT ( ! )
  • Unary Plus/Minus ( + and )
  • Multiplication/Division/Modulus ( *, /, % )
  • Addition/Subtraction ( + and )
  • Bitwise Shifts ( <<, >>, and >>> )
  • Relational Operators ( <, >, <=, >=, instanceof, and in )
  • Equality/Inequality ( ==, !=, ===, and !== )
  • Bitwise AND ( & )
  • Bitwise XOR ( ^ )
  • Bitwise OR ( | )
  • Logical AND ( && )
  • Logical OR ( || )
  • Ternary/Conditional ( ? : )
  • Assignment ( =, +=, -=, and more )
  • Comma ( , )

It’s crucial to understand operator precedence to write clear and unambiguous expressions. For example, in an expression like a + b * c, the multiplication operator * has a higher precedence than the addition operator +, so b * c is evaluated before adding a.

Using parentheses is a good practice to explicitly specify the desired order of operations. For example, (a + b) * c ensures that the addition is performed before the multiplication.

What are Expressions?

Expressions in JavaScript are combinations of values, variables, operators, and function calls that produce a resulting value. Expressions are used to perform computations, make decisions, and create dynamic behavior in your code. They are an essential part of JavaScript programming.

Let’s explore different types of expressions:

1. Arithmetic Expressions

Arithmetic expressions involve mathematical operations and produce numeric values.

let x = 5;
let y = 3;
let result = x + (y * 2);  // An arithmetic expression with addition and multiplication

2. String Expressions

String expressions involve string concatenation and produce string values.

let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;  // A string expression for concatenation

3. Boolean Expressions

Boolean expressions evaluate to either true or false and are often used in conditional statements.

let age = 25;
let isAdult = age >= 18;  // A boolean expression for checking if 'age' is greater than or equal to 18

4. Conditional Expressions

Conditional expressions, often using the ternary operator, allow you to choose between two values based on a condition.

let isRaining = true;
let weather = isRaining ? "Take an umbrella" : "Enjoy the sunshine";  // A conditional expression

5. Function Call Expressions

Function call expressions execute a function and return the result.

function square(x) {
  return x * x;
}
let result = square(4);  // A function call expression with the 'square' function

6. Complex Expressions

Complex expressions can involve multiple operators and values to perform more intricate calculations.

let base = 10;
let exponent = 3;
let result = Math.pow(base, exponent) + (base * 2);  // A complex expression

Understanding expressions is vital for writing effective code. Expressions can be used in various contexts, such as assigning values to variables, passing arguments to functions, making decisions in conditional statements, and more.

Operator Shorthand

JavaScript offers shorthand notations for common operations that simplify your code and make it more concise. Here are some examples:

Shorthand for Increment and Decrement

You can use ++ and directly with variables to increment or decrement their values.

let count = 5;
count++;  // Equivalent to count = count + 1;
count--;  // Equivalent to count = count - 1;

Shorthand for Assignment

Assignment operators can be combined with arithmetic operators for concise assignments.

let total = 0;
total += 10;  // Equivalent to total = total + 10;
total -= 5;   // Equivalent to total = total - 5;

Shorthand for String Concatenation

You can use += to concatenate strings.

let message = "Hello";
message += " World";  // Equivalent to message = message + " World";

Shorthand notations improve code readability and help reduce redundancy.

Summary

In this chapter, we’ve explored the world of operators and expressions in JavaScript. Operators are symbols and keywords that perform operations on values, while expressions are combinations of values, variables, and operators that produce results. Here’s a quick recap of what we’ve covered:

  • Arithmetic Operators: These operators perform mathematical calculations, including addition, subtraction, multiplication, division, modulus, and exponentiation.
  • Assignment Operators: These operators assign values to variables, and some can be combined with arithmetic operations for concise assignments.
  • Comparison Operators: These operators compare two values and return a boolean result, indicating equality, inequality, or relative magnitude.
  • Logical Operators: These operators perform logical operations and return boolean values, often used in conditional statements.
  • Increment and Decrement Operators: These operators increase or decrease a variable’s value by one, with pre-increment, post-increment, pre-decrement, and post-decrement variations.
  • Ternary (Conditional) Operator: A concise way to express conditional statements, which evaluates a condition and returns one of two values based on the result.
  • String Concatenation: The + operator can be used to concatenate strings.
  • Bitwise Operators: Used to manipulate the binary representation of numbers, typically used in low-level programming.
  • Operator Precedence: Understanding operator precedence is crucial for correctly evaluating expressions with multiple operators.
  • Expressions: Combinations of values, variables, operators, and function calls that produce a resulting value. Expressions are used for computations, decision-making, and dynamic behavior in code.
  • Operator Shorthand: JavaScript provides shorthand notations for common operations, such as incrementing/decrementing variables, assigning values, and concatenating strings.

Mastering operators and expressions is essential for writing effective JavaScript code. These concepts are the building blocks of your programs and are used in various aspects of web development, from simple calculations to complex decision-making processes.

In the next chapter, we will explore control structures in JavaScript. Control structures, including conditional statements and loops, are fundamental for creating dynamic and interactive programs. Get ready to take your JavaScript skills to the next level in Chapter 4!

Next Chapter: Chapter 4 – Control Structures in JavaScript

In Chapter 4, we will dive into control structures in JavaScript. These constructs, including conditional statements and loops, enable you to create dynamic and interactive code. You’ll learn how to make decisions, repeat actions, and create complex behavior in your programs. Join us in the exciting journey of mastering control structures!

Scroll to Top