Javascript Introduction

JS Operators


JavaScript Operators

An operator in JavaScript is a special symbol used to perform operations on operands, which can be values or variables. Let's explore various types of operators in JavaScript:

Assignment Operators

Assignment operators are used to assign values to variables. The commonly used assignment operator is =. Other assignment operators include +=, -=, *=, /=, %=, and **=.

const x = 5;
let a = 7;
a += 5; // equivalent to a = a + 5

Arithmetic Operators

Arithmetic operators are used for mathematical calculations such as addition (+), subtraction (-), multiplication (*), division (/), remainder (%), increment (++), decrement (--), and exponentiation (**).

let x = 5;
let y = 3;

console.log('x + y = ', x + y);  // 8
console.log('x - y = ', x - y);  // 2
console.log('x * y = ', x * y);  // 15
console.log('x / y = ', x / y);  // 1.6666666666666667
console.log('x % y = ', x % y);   // 2
console.log('++x = ', ++x); // x is now 6

Comparison Operators

Comparison operators compare two values and return a boolean value (true or false). Common comparison operators include ==, !=, ===, !==, >, >=, <, and <=.

const a = 3, b = 2;
console.log(a > b); // true
console.log(2 === '2'); // false

Logical Operators

Logical operators perform logical operations and return a boolean value. Common logical operators include && (AND), || (OR), and ! (NOT).

const x = 5, y = 3;
console.log((x < 6) && (y < 5)); // true
console.log(!true); // false

Bitwise Operators

Bitwise operators perform operations on binary representations of numbers. They include &, |, ^, ~, <<, >>, and >>>.

String Operators

In JavaScript, the + operator can also concatenate strings.

console.log('hello' + 'world'); // helloworld
let a = 'JavaScript';
a += ' tutorial';  // a = a + ' tutorial';
console.log(a); // JavaScript tutorial

Other Operators

JavaScript also includes other operators like ,, ?:, delete, typeof, void, in, and instanceof.

let a = (1, 3 , 4); // 4
console.log((5 > 3) ? 'success' : 'error'); // "success"
delete x;
console.log(typeof 3); // "number"
void(x);
console.log('prop' in object);
console.log(object instanceof object_type);

These operators serve various purposes in JavaScript programming and are used in different contexts based on specific requirements.