Expressions and operators in java script
In JavaScript, expressions can be categorized into several types based on their functionality and the kind of operations they perform. Here, we'll explore different types of expressions along with examples.
1. Arithmetic Expressions
Arithmetic expressions perform mathematical calculations on numeric values.
let sum = 10 + 5; // Addition
let difference = 10 - 5; // Subtraction
let product = 10 * 5; // Multiplication
let quotient = 10 / 5; // Division
let remainder = 10 % 5; // Modulus
let exponentiation = 10 ** 2; // Exponentiation
2. String Expressions
String expressions involve operations on strings.
let greeting = "Hello" + " " + "World"; // Concatenation
let shout = "hello".toUpperCase(); // Method call
let whisper = "HELLO".toLowerCase(); // Method call
3. Logical Expressions
Logical expressions evaluate to true or false using logical operators.
let andExpression = true && false; // Logical AND
let orExpression = true || false; // Logical OR
let notExpression = !true; // Logical NOT
4. Comparison Expressions
Comparison expressions compare values and return a boolean.
let isEqual = 10 == "10"; // Equality (loose)
let isStrictEqual = 10 === 10; // Equality (strict)
let isNotEqual = 10 != 5; // Inequality (loose)
let isStrictNotEqual = 10 !== "10"; // Inequality (strict)
let isGreater = 10 > 5; // Greater than
let isLess = 5 < 10; // Less than
let isGreaterOrEqual = 10 >= 5; // Greater than or equal
let isLessOrEqual = 5 <= 10; // Less than or equal
5. Assignment Expressions
Assignment expressions assign values to variables.
let x = 10; // Simple assignment
x += 5; // Addition assignment
x -= 5; // Subtraction assignment
x *= 5; // Multiplication assignment
x /= 5; // Division assignment
x %= 3; // Remainder assignment
x **= 2; // Exponentiation assignment
6. Ternary (Conditional) Expressions
The ternary expression is a shorthand for if-else statements.
let age = 18;
let canVote = (age >= 18) ? "Yes" : "No"; // Ternary operator
7. Function Expressions
Function expressions define functions and can be assigned to variables.
let greet = function(name) {
return "Hello " + name;
};
console.log(greet("Alice")); // "Hello Alice"
8. Array Expressions
Array expressions define arrays.
let numbers = [1, 2, 3, 4, 5];
let colors = ["red", "green", "blue"];
9. Object Expressions
Object expressions define objects with properties and methods.
let person = {
name: "Alice",
age: 25,
greet: function() {
return "Hello " + this.name;
}
};
console.log(person.greet()); // "Hello Alice"
10. Arrow Function Expressions
Arrow function expressions provide a concise syntax to define functions.
let sum = (a, b) => a + b;
console.log(sum(5, 10)); // 15
11. Regular Expressions
Regular expressions are patterns used to match character combinations in strings.
let regex = /hello/i; // Case-insensitive match for "hello"
let result = regex.test("Hello world");
console.log(result); // true
12. Unary Expressions
Unary expressions operate on a single operand.
let x = 5;
let increment = ++x; // Pre-increment
let decrement = --x; // Pre-decrement
let negation = -x; // Negation
let type = typeof x; // Typeof operator
13. Spread and Rest Expressions
The spread operator expands elements, and the rest operator collects multiple elements.
let numbers = [1, 2, 3];
let newNumbers = [...numbers, 4, 5]; // Spread
function sum(...args) { // Rest
return args.reduce((acc, val) => acc + val, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
14. Destructuring Expressions
Destructuring expressions unpack values from arrays or objects into variables.
let [a, b] = [1, 2]; // Array destructuring
let {name, age} = {name: "Alice", age: 25}; // Object destructuring
15. Optional Chaining Expressions
Optional chaining allows safe access to deeply nested properties.
let user = { name: "Alice", address: { city: "Wonderland" } };
let city = user?.address?.city; // "Wonderland"
let country = user?.address?.country; // undefined
16. Nullish Coalescing Expressions
The nullish coalescing operator returns the right-hand side operand if the left-hand side is null or undefined.
let user = null;
let userName = user ?? "Guest"; // "Guest"
let anotherUser = "John";
let anotherUserName = anotherUser ?? "Guest"; // "John"
17. Comma Operator
The comma operator evaluates multiple expressions and returns the result of the last one.
let a = (1, 2, 3); // a is 3
let b = (a++, a); // b is 4, a is 4
18. Void Operator
The void operator evaluates an expression and returns undefined
.
void (0); // undefined
let result = void (function() { console.log("Hello"); }()); // "Hello", result is undefined
19. Grouping Operator
The grouping operator controls the precedence of expressions.
let result = (2 + 3) * 4; // 20
20. New Operator
The new operator creates an instance of a user-defined object type or one of the built-in object types.
function Person(name, age) {
this.name = name;
this.age = age;
}
let alice = new Person("Alice", 30);
console.log(alice.name); // "Alice"
21. This Keyword
The this
keyword refers to the current context of execution.
let person = {
name: "Alice",
greet: function() {
console.log("Hello, " + this.name);
}
};
person.greet(); // "Hello, Alice"
22. Yield and Yield Operators*
The yield
keyword is used in generator functions to pause and resume execution.
function* generatorFunction() {
yield "First";
yield "Second";
yield "Third";
}
let generator = generatorFunction();
console.log(generator.next().value); // "First"
console.log(generator.next().value); // "Second"
console.log(generator.next().value); // "Third"
Operators in java script
JavaScript operators are special symbols or keywords that perform operations on operands (values or variables) and produce a result. They can be broadly categorized into several types based on the operations they perform. Here, we'll explore different types of operators along with examples.
1. Arithmetic Operators
Arithmetic operators perform basic mathematical operations.
-
Addition (
+
): Adds two numbers.let sum = 10 + 5; // 15
-
Subtraction (
-
): Subtracts the second number from the first.let difference = 10 - 5; // 5
-
Multiplication (
*
): Multiplies two numbers.let product = 10 * 5; // 50
-
Division (
/
): Divides the first number by the second.let quotient = 10 / 5; // 2
-
Modulus (
%
): Returns the remainder of the division of two numbers.let remainder = 10 % 3; // 1
-
Exponentiation (
**
): Raises the first number to the power of the second.let power = 2 ** 3; // 8
2. Assignment Operators
Assignment operators assign values to variables.
-
Assignment (
=
): Assigns the value of the right operand to the left operand.let x = 10;
-
Addition Assignment (
+=
): Adds the right operand to the left operand and assigns the result to the left operand.x += 5; // x is now 15
-
Subtraction Assignment (
-=
): Subtracts the right operand from the left operand and assigns the result to the left operand.x -= 3; // x is now 12
-
Multiplication Assignment (
*=
): Multiplies the right operand by the left operand and assigns the result to the left operand.x *= 2; // x is now 24
-
Division Assignment (
/=
): Divides the left operand by the right operand and assigns the result to the left operand.x /= 4; // x is now 6
-
Modulus Assignment (
%=
): Takes the modulus using the two operands and assigns the result to the left operand.x %= 5; // x is now 1
-
Exponentiation Assignment (
**=
): Raises the left operand to the power of the right operand and assigns the result to the left operand.x **= 2; // x is now 1 (1^2)
3. Comparison Operators
Comparison operators compare two values and return a boolean result.
-
Equal (
==
): Checks if two values are equal (type conversion occurs).let isEqual = (10 == "10"); // true
-
Strict Equal (
===
): Checks if two values are equal (no type conversion).let isStrictEqual = (10 === 10); // true
-
Not Equal (
!=
): Checks if two values are not equal (type conversion occurs).let isNotEqual = (10 != 5); // true
-
Strict Not Equal (
!==
): Checks if two values are not equal (no type conversion).let isStrictNotEqual = (10 !== "10"); // true
-
Greater Than (
>
): Checks if the left operand is greater than the right operand.let isGreater = (10 > 5); // true
-
Less Than (
<
): Checks if the left operand is less than the right operand.let isLess = (5 < 10); // true
-
Greater Than or Equal (
>=
): Checks if the left operand is greater than or equal to the right operand.let isGreaterOrEqual = (10 >= 5); // true
-
Less Than or Equal (
<=
): Checks if the left operand is less than or equal to the right operand.let isLessOrEqual = (5 <= 10); // true
4. Logical Operators
Logical operators perform logical operations and return a boolean result.
-
Logical AND (
&&
): Returns true if both operands are true.let andResult = (true && false); // false
-
Logical OR (
||
): Returns true if at least one operand is true.let orResult = (true || false); // true
-
Logical NOT (
!
): Returns the opposite boolean value of the operand.let notResult = (!true); // false
5. Bitwise Operators
Bitwise operators perform bitwise operations on binary representations of numbers.
-
Bitwise AND (
&
): Performs a logical AND operation on each bit.let andBitwise = (5 & 1); // 1 (0101 & 0001 = 0001)
-
Bitwise OR (
|
): Performs a logical OR operation on each bit.let orBitwise = (5 | 1); // 5 (0101 | 0001 = 0101)
-
Bitwise XOR (
^
): Performs a logical XOR operation on each bit.let xorBitwise = (5 ^ 1); // 4 (0101 ^ 0001 = 0100)
-
Bitwise NOT (
~
): Inverts all the bits.let notBitwise = (~5); // -6 (~0101 = 1010, which is -6 in two's complement)
-
Left Shift (
<<
): Shifts bits to the left, filling with zeroes.let leftShift = (5 << 1); // 10 (0101 << 1 = 1010)
-
Right Shift (
>>
): Shifts bits to the right, preserving the sign bit.let rightShift = (5 >> 1); // 2 (0101 >> 1 = 0010)
-
Unsigned Right Shift (
>>>
): Shifts bits to the right, filling with zeroes.let unsignedRightShift = (5 >>> 1); // 2 (0101 >>> 1 = 0010)
6. String Operators
String operators are used to perform operations on strings.
- Concatenation (
+
): Joins two or more strings.let hello = "Hello";
let world = "World";
let greeting = hello + " " + world; // "Hello World"
7. Conditional (Ternary) Operator
The ternary operator is a shorthand for if-else statements.
let age = 18;
let canVote = (age >= 18) ? "Yes" : "No"; // "Yes"
8. Comma Operator
The comma operator allows you to evaluate multiple expressions, returning the result of the last expression.
let a, b;
a = (b = 3, b + 1); // a is 4, b is 3
9. Unary Operators
Unary operators operate on a single operand.
-
Unary Plus (
+
): Converts the operand to a number.let num = +"10"; // 10
-
Unary Negation (
-
): Converts the operand to a number and negates it.let negativeNum = -"10"; // -10
-
Increment (
++
): Increases the operand by 1.let count = 1;
count++; // 2 -
Decrement (
--
): Decreases the operand by 1.let count = 2;
count--; // 1 -
Logical NOT (
!
): Converts the operand to a boolean and negates it.let isFalse = !true; // false
-
Bitwise NOT (
~
): Inverts all the bits.let notBitwise = ~5; // -6
-
typeof: Returns the type of the operand.
let type = typeof "Hello"; // "string"
-
void: Evaluates the expression and returns
undefined
.let result = void (0); // undefined
-
delete: Deletes a property from an object.
let obj = {name: "
Alice"}; delete obj.name; // true, obj is now
### 10. **Relational Operators**
Relational operators compare the relationship between two operands.
- **in**: Checks if the specified property is in the object.
```javascript
let obj = {name: "Alice"};
let hasName = "name" in obj; // true
- instanceof: Checks if the object is an instance of a specific class or constructor.
let today = new Date();
let isDate = today instanceof Date; // true
Sure, let's continue with a few more types of operators and their examples:
11. Spread Operator
The spread operator (...
) allows an iterable (such as an array or string) to be expanded in places where zero or more arguments or elements are expected.
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5, 6]; // [1, 2, 3, 4, 5, 6]
let obj1 = {a: 1, b: 2};
let obj2 = {...obj1, c: 3}; // {a: 1, b: 2, c: 3}
12. Rest Operator
The rest operator (...
) is used to collect all remaining elements into an array.
function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
let total = sum(1, 2, 3, 4); // 10
13. Destructuring Assignment
Destructuring assignment allows for extracting values from arrays or properties from objects into distinct variables.
-
Array Destructuring:
let [a, b, c] = [1, 2, 3]; // a=1, b=2, c=3
-
Object Destructuring:
let {name, age} = {name: "Alice", age: 25}; // name="Alice", age=25
14. Optional Chaining Operator
The optional chaining operator (?.
) allows you to safely access deeply nested properties.
let user = { name: "Alice", address: { city: "Wonderland" } };
let city = user?.address?.city; // "Wonderland"
let country = user?.address?.country; // undefined
15. Nullish Coalescing Operator
The nullish coalescing operator (??
) returns the right-hand operand when the left-hand operand is null
or undefined
.
let user = null;
let userName = user ?? "Guest"; // "Guest"
let anotherUser = "John";
let anotherUserName = anotherUser ?? "Guest"; // "John"
16. Comma Operator
The comma operator (,
) evaluates each of its operands (from left to right) and returns the value of the last operand.
let a = (1, 2, 3); // a is 3
let x = 0;
let y = (x++, x); // y is 1, x is 1
17. Void Operator
The void operator (void
) evaluates the given expression and returns undefined
.
let result = void (0); // undefined
let example = void (function() { console.log("Hello"); }()); // "Hello", example is undefined
18. Grouping Operator
The grouping operator (()
) controls the precedence of evaluation in expressions.
let result = (2 + 3) * 4; // 20
19. New Operator
The new
operator creates an instance of a user-defined object type or one of the built-in object types.
function Person(name, age) {
this.name = name;
this.age = age;
}
let alice = new Person("Alice", 30);
console.log(alice.name); // "Alice"
20. This Keyword
The this
keyword refers to the current context of execution.
let person = {
name: "Alice",
greet: function() {
console.log("Hello, " + this.name);
}
};
person.greet(); // "Hello, Alice"
21. Yield and Yield Operators*
The yield
keyword is used in generator functions to pause and resume execution.
function* generatorFunction() {
yield "First";
yield "Second";
yield "Third";
}
let generator = generatorFunction();
console.log(generator.next().value); // "First"
console.log(generator.next().value); // "Second"
console.log(generator.next().value); // "Third"
Summary
JavaScript operators provide a powerful toolkit for manipulating data, controlling program flow, and performing complex calculations. Here is a summary of the operators we've discussed:
- Arithmetic Operators:
+
,-
,*
,/
,%
,**
- Assignment Operators:
=
,+=
,-=
,*=
,/=
,%=
,**=
- Comparison Operators:
==
,===
,!=
,!==
,>
,<
,>=
,<=
- Logical Operators:
&&
,||
,!
- Bitwise Operators:
&
,|
,^
,~
,<<
,>>
,>>>
- String Operator:
+
- Conditional (Ternary) Operator:
? :
- Comma Operator:
,
- Unary Operators:
+
,-
,++
,--
,!
,~
,typeof
,void
,delete
- Relational Operators:
in
,instanceof
- Spread Operator:
...
- Rest Operator:
...
- Destructuring Assignment:
[]
,{}
- Optional Chaining Operator:
?.
- Nullish Coalescing Operator:
??
- Grouping Operator:
()
- New Operator:
new
- This Keyword:
this
- Yield and Yield Operators*:
yield
,yield*
Understanding these operators and how they work is crucial for writing efficient and effective JavaScript code.