Page Content

Tutorials

What are JavaScript Operators and How Do They Work?

JavaScript Operators

JavaScript is built on operators and expressions. Understanding them is essential for dynamic scripting.

JavaScript Operators and expressions
JavaScript Operators and expressions

A piece of code that JavaScript can evaluate to generate a value is called an expression. The “phrases” of JavaScript are expressions. Simple examples include variable names and literal values like “psychoanalysis” or Parentheses also contain expressions. Simpler expressions can be used to construct more complex ones. In a JavaScript program, you obtain a value by evaluating an expression.

Operators are unique symbols or keywords that are used in expressions to manipulate variables or values. To create a new value, they combine the operands also known as arguments that they operate on. Operators are similar to the “verb” to the “noun” in an expression.

How many operands do operators take?

  • Unary Operators, such as -x,!myBool, and typeof value, only have one operand.
  • Binary Operators: Two operands are used by binary operators (e.g., a + b, x > y, num = 10).
  • Ternary operator: With three operands (condition? valueIfTrue : valueIfFalse), the Ternary operator is unique.

JavaScript offers several types of operators, including:

  • Arithmetic operators calculate addition (+), subtraction (-), multiplication (*), division (/), exponentiation (**), and modulus. An unary increment (++) or decrement (–) operator adds or subtracts 1 from a variable. Keep in mind that when the + operator is used with strings, it also concatenates the strings.
  • Assignment operators give a variable or property a value. = is the straightforward assignment. Compound assignment operators, such as +=, -=, *=, /=, and %=, combine assignment with an arithmetic or bitwise operation.
  • Comparison Operators: When two values are compared, comparison operators also known as relational operators always yield a true or false Boolean result. Examples include <, >, <=, and >=. In order to determine whether two values are equal, equality operators check for inequality. == checks for equal value only, whereas === checks for equal value and equal data type.
  • Logical Operators: Boolean values can be combined or inverted using logical operators. If and only if both operands are true, the logical AND (&&) yields true. If one operand is true, the logical OR (||) yields true. Operand Boolean value is inverted by NOT (!). Because of their unique “short-circuiting” behaviour, && and || may not evaluate the second operand.
  • Conditional Operator: A basic if…else expression is substituted with the ternary conditional operator (?:). The process starts with a condition (an expression), followed by?, then returns the value or expression if the condition is true, followed by :, and if the condition is false, the value or expression is returned.

The sequence in which operations are carried out in a single expression is determined by the precedence of the operators utilised. Higher precedence operators are assessed before lower precedence operators. The sequence of evaluation for operators with the same precedence typically left-to-right or right-to-left is determined by associativity. Operator precedence can be overridden by grouping using brackets (…).

Here is a code example demonstrating various expressions and operators:

// Variable declaration and assignment using the assignment operator (=)
let quantity = 5; // ‘quantity’ is a variable expression, 5 is a literal expression
let price = 10.50; // ‘price’ is a variable expression, 10.50 is a literal expression

// Arithmetic operator (+) used in an expression (price + 2.00)
// The entire line is an assignment expression with a side effect
price = price + 2.00; // price + 2.00 is an expression that evaluates to 12.50

// Compound assignment operator (*=)
// (quantity * price) is an expression evaluating to a total
let totalCost = quantity * price; // The line is an assignment expression

// console.log() is a function invocation expression
// The argument (“Total: ” + totalCost) is an expression using the + operator for string concatenation
console.log(“Total: ” + totalCost);

// Comparison operator (>) used in an expression (totalCost > 50)
// This expression evaluates to a boolean value
let isExpensive = totalCost > 50; // Assignment expression

console.log(“Is it expensive? ” + isExpensive);

// Logical AND operator (&&) used to combine two comparison expressions
let meetsCriteria = (quantity > 3) && (price < 15); // Grouping with parentheses

console.log(“Meets criteria? ” + meetsCriteria);

// Conditional (Ternary) operator (?:)
let status = isExpensive ? “High cost” : “Standard cost”; // Evaluates to a string based on isExpensive

console.log(“Status: ” + status);

This example shows how variables, literals, and operators are used to create expressions that yield values. These values are then frequently utilised in statements (such as function calls or assignments) to carry out operations or change the state of the program.