Operators

Operators

Operators in JavaScript are used to perform operations on variables and values. They are essential tools for manipulating data and implementing logic in your programs. Let's explore the different types of operators available in JavaScript.

1. Arithmetic Operators

Arithmetic operators are used to perform basic mathematical operations.

Example:

let a = 10;
let b = 3;

console.log(a + b); // Outputs: 13
console.log(a - b); // Outputs: 7
console.log(a * b); // Outputs: 30
console.log(a / b); // Outputs: 3.3333333333333335
console.log(a % b); // Outputs: 1

2. Assignment Operators

Assignment operators are used to assign values to variables.

Example:

let x = 10;
x += 5; // Equivalent to x = x + 5
console.log(x); // Outputs: 15

x -= 2; // Equivalent to x = x - 2
console.log(x); // Outputs: 13

x *= 3; // Equivalent to x = x * 3
console.log(x); // Outputs: 39

x /= 3; // Equivalent to x = x / 3
console.log(x); // Outputs: 13

x %= 2; // Equivalent to x = x % 2
console.log(x); // Outputs: 1

3. Comparison Operators

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

Example:

let a = 5;
let b = '5';

console.log(a == b); // Outputs: true (non-strict equality)
console.log(a === b); // Outputs: false (strict equality)
console.log(a != b); // Outputs: false (non-strict inequality)
console.log(a !== b); // Outputs: true (strict inequality)
console.log(a > 2); // Outputs: true
console.log(a < 10); // Outputs: true
console.log(a >= 5); // Outputs: true
console.log(a <= 5); // Outputs: true

4. Logical Operators

Logical operators are used to combine multiple boolean expressions.

Example:

let a = true;
let b = false;

console.log(a && b); // Outputs: false (AND)
console.log(a || b); // Outputs: true (OR)
console.log(!a); // Outputs: false (NOT)

5. String Operators

The concatenation operator (+) is used to combine strings.

Example:

let firstName = 'codeswith';
let lastName = 'pankaj';

let fullName = firstName + lastName;
console.log(fullName); // Outputs: codeswithpankaj

6. Conditional (Ternary) Operator

The conditional (ternary) operator is a shorthand for the if-else statement. It takes three operands: a condition, an expression to execute if the condition is true, and an expression to execute if the condition is false.

Syntax:

condition ? expressionIfTrue : expressionIfFalse

Example:

let age = 18;
let message = age >= 18 ? 'You are an adult' : 'You are a minor';
console.log(message); // Outputs: You are an adult

Summary

Operators are essential tools for performing various operations on variables and values in JavaScript. By understanding arithmetic, assignment, comparison, logical, string, and conditional operators, you can effectively manipulate data and implement logic in your programs.


Last updated