Javascript Operators And Expressions Complete Guide
Understanding the Core Concepts of JavaScript Operators and Expressions
JavaScript Operators and Expressions
1. Arithmetic Operators
Arithmetic operators perform mathematical operations on numbers.
+
- Additionlet sum = 10 + 5; // 15
-
- Subtractionlet difference = 10 - 5; // 5
*
- Multiplicationlet product = 10 * 5; // 50
/
- Divisionlet quotient = 10 / 5; // 2
%
- Modulus (remainder after division)let remainder = 10 % 3; // 1
++
- Increment (increases value by one)let count = 5; count++; // count is now 6
--
- Decrement (decreases value by one)let score = 10; score--; // score is now 9
2. Assignment Operators
Assignment operators assign values to JavaScript variables.
=
- Assignlet x = 10;
+=
- Add and assignlet y = 5; y += 10; // y is now 15
-=
- Subtract and assignlet z = 15; z -= 5; // z is now 10
*=
- Multiply and assignlet w = 4; w *= 3; // w is now 12
/=
- Divide and assignlet a = 20; a /= 4; // a is now 5
%=
- Modulus and assignlet b = 17; b %= 5; // b is now 2
3. Comparison Operators
Comparison operators compare two values and return a boolean value (either true or false).
==
- Equal to (value comparison)let isEqual = 10 == '10'; // true
===
- Strictly equal to (value and type comparison)let isStrictEqual = 10 === '10'; // false
!=
- Not equal to (value comparison)let isNotEqual = 10 != '15'; // true
!==
- Not strictly equal to (value and type comparison)let isNotStrictEqual = 10 !== '10'; // true
>
- Greater thanlet isGreater = 20 > 10; // true
<
- Less thanlet isLess = 5 < 10; // true
>=
- Greater than or equal tolet isGreaterOrEqual = 10 >= 10; // true
<=
- Less than or equal tolet isLessOrEqual = 5 <= 10; // true
4. Logical Operators
Logical operators perform logical operations and return a boolean value.
&&
- Logical AND (returns true if both conditions are true)let logicalAnd = (10 > 5) && (10 < 20); // true
||
- Logical OR (returns true if at least one condition is true)let logicalOr = (10 > 20) || (10 < 20); // true
!
- Logical NOT (reverses the boolean value)let logicalNot = !(10 > 5); // false
5. Expressions
An expression is a combination of values, variables, and operators that are computed to produce another value. The simplest expressions are literal values.
Arithmetic Expression
let result = 10 + 20 * 2; // 50
Logical Expression
let boolResult = (10 > 5) && (20 < 30); // true
String Expression
let stringResult = "Hello " + "World"; // Hello World
6. Operator Precedence
Operator precedence is a set of rules that determine which operators are evaluated first in an expression. It helps in understanding the order in which operations are performed.
Example:
let precedence = 10 + 2 * 3; // 16, because multiplication is done first
Using parentheses can help override the default precedence:
let overriddenPrecedence = (10 + 2) * 3; // 36
7. Type Operators
Type operators are used to find the type of a JavaScript variable.
typeof
- Returns the type of a variabletypeof(10); // "number" typeof("Hello"); // "string" typeof(false); // "boolean"
instanceof
- Returns true if an object is an instance of an object type
Online Code run
Step-by-Step Guide: How to Implement JavaScript Operators and Expressions
JavaScript Operators and Expressions
1. Arithmetic Operators
Arithmetic operators are used to perform mathematical operations on numbers. The common arithmetic operators are:
+
(Addition)-
(Subtraction)*
(Multiplication)/
(Division)%
(Modulus/Remainder)**
(Exponentiation)++
(Increment)--
(Decrement)
Example:
let x = 10;
let y = 3;
console.log(x + y); // Output: 13
console.log(x - y); // Output: 7
console.log(x * y); // Output: 30
console.log(x / y); // Output: 3.3333333333333335
console.log(x % y); // Output: 1
console.log(x ** y); // Output: 1000
// Increment and Decrement
console.log(x++); // Output: 10, then x becomes 11
console.log(++x); // Output: 12
console.log(y--); // Output: 3, then y becomes 2
console.log(--y); // Output: 1
2. Assignment Operators
Assignment operators are used to assign values to variables.
=
(Simple assignment)+=
(Addition assignment)-=
(Subtraction assignment)*=
(Multiplication assignment)/=
(Division assignment)%=
(Remainder/Modulus assignment)**=
(Exponentiation assignment)
Example:
let a = 10;
a += 5; // a = a + 5
console.log(a); // Output: 15
a -= 3; // a = a - 3
console.log(a); // Output: 12
a *= 2; // a = a * 2
console.log(a); // Output: 24
a /= 3; // a = a / 3
console.log(a); // Output: 8
a %= 5; // a = a % 5
console.log(a); // Output: 3
a **= 2; // a = a ** 2
console.log(a); // Output: 9
3. Comparison Operators
Comparison operators are used to compare two values and return a Boolean true
or false
.
==
(Equal to)===
(Strictly Equal to)!=
(Not Equal to)!==
(Strictly Not Equal to)>
(Greater than)<
(Less than)>=
(Greater than or Equal to)<=
(Less than or Equal to)
Example:
let p = 5;
let q = 10;
console.log(p == q); // Output: false
console.log(p === q); // Output: false
console.log(p != q); // Output: true
console.log(p !== q); // Output: true
console.log(p > q); // Output: false
console.log(p < q); // Output: true
console.log(p >= q); // Output: false
console.log(p <= q); // Output: true
4. Logical Operators
Logical operators are used to determine the logic between variables or values.
&&
(Logical AND)||
(Logical OR)!
(Logical NOT)
Example:
let r = true;
let s = false;
console.log(r && s); // Output: false
console.log(r || s); // Output: true
console.log(!r); // Output: false
console.log(!s); // Output: true
5. Conditional/Ternary Operator
The ternary operator is a shorthand for an if-else
statement.
- Syntax:
condition ? expressionIfTrue : expressionIfFalse
Example:
let age = 18;
let message = (age >= 18) ? "You can vote" : "You cannot vote";
console.log(message); // Output: You can vote
6. Expressions
An expression is a combination of values, variables, and operators, which are computed to produce another value.
Example:
Top 10 Interview Questions & Answers on JavaScript Operators and Expressions
Top 10 Questions and Answers: JavaScript Operators and Expressions
JavaScript provides a variety of operators that can be broadly categorized into:
- Arithmetic Operators:
+
,-
,*
,/
,%
(modulus), and**
(exponentiation). - Assignment Operators:
=
,+=
,-=
,*=
,/=
,%=
, and**=
to assign values to variables. - Comparison Operators:
==
(equality),===
(strict equality),!=
(inequality),!==
(strict inequality),>
,<
,>=
, and<=
. - Logical Operators:
&&
(AND),||
(OR), and!
(NOT) to logically combine boolean expressions. - Bitwise Operators:
&
(AND),|
(OR),^
(XOR),~
(NOT),<<
(left shift),>>
(right shift), and>>>
(zero-fill right shift). - String Operators:
+
to concatenate strings. - Conditional (Ternary) Operator:
condition ? exprIfTrue : exprIfFalse
to return one of two values based on a condition. - Comma Operator:
,
to evaluate multiple expressions, returning the value of the last expression. - Unary Operators:
typeof
,void
,delete
,+
,-
,++
, and--
to perform operations with a single operand. - Relational Operators: Used for comparing operands but are less commonly used directly; most comparison tasks use the Comparison Operators instead.
2. Explain the difference between =
and ==
in JavaScript.
=
is the assignment operator used to assign a value to a variable, e.g., let x = 5
.
==
is the comparison operator for equality but it doesn't check data types. It converts both operands to the same type before making a comparison, e.g., 3 == '3'
returns true
because the string '3'
is converted to the number 3
prior to comparison.
3. What is strict equality (===
) in JavaScript?
Strict equality (===
) checks whether its two operands are equal in value and type without doing type coercion (automatic conversion between different data types). For example, 3 === '3'
returns false
because 3
is a number, while '3'
is a string.
4. How do logical operators work in JavaScript?
&&
(logical AND): Returnstrue
if both operands are true; otherwise, it returnsfalse
. Example:
true && false; // false
||
(logical OR): Returnstrue
if at least one operand is true; otherwise, it returnsfalse
. Example:
true || false; // true
!
(logical NOT): Negates the operand—returnstrue
if the operand isfalse
; returnsfalse
if the operand istrue
. Example:
!true; // false
5. Can you provide examples of bitwise operators in JavaScript?
Bitwise operations manipulate numbers at the binary level.
&
(AND): Performs a binary AND operation.|
(OR): Performs a binary OR operation.^
(XOR): Performs a binary XOR operation.~
(NOT): Inverts all the bits in a number.<<
(Left Shift): Shifts the bits of the first operand left by the specified number of positions in the second operand.>>
(Right Shift): Shifts the bits of the first operand right by the specified number of positions in the second operand, the bits vacated by shifting get filled with 1's.>>>
(Zero-Fill Right Shift): Shifts the bits of the first operand right by the specified number of positions in the second operand, padding zero-bits on void left spaces from left. Example:
let x = 5; // binary representation is "101"
let y = 3; // binary representation is "011"
console.log(x & y); // output 1, because binary "101 & 011" equals "001"
console.log(x | y); // output 7, because binary "101 | 011" equals "111"
console.log(x ^ y); // output 6, because binary "101 ^ 011" equals "110"
console.log(~x); // output -6, because binary "~101" equals "-110" (-6 in decimal)
console.log(x << 1);// output 10, binary "101 << 1" equals "1010"
console.log(y >> 1);// output 1, binary "011 >> 1" equals "001"
console.log(y >>> 1);// output 1, binary "011 >>> 1" equals "001"
6. What is the conditional (ternary) operator in JavaScript?
The conditional (ternary) operator acts as a short form for an if...else
statement. It has three parts: a condition followed by a question mark (?
), then an expression that will be executed if the condition is truthy, followed by a colon (:
) and another expression that will be executed if the condition is falsy.
Example:
let age = 25;
let category = age >= 18 ? 'Adult' : 'Minor';
console.log(category); // Outputs "Adult"
7. Describe how the comma operator functions in JavaScript. The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand. Example:
let z = (function(a,b,c){return ++a;}, --b + c++, a+c);
console.log(z); // Output depends on the context and initial values of variables a, b, and c. If these were previously defined as 1, 1, and 1 respectively then output would be "3".
8. What are unary operators in JavaScript? Unary operators work on a single operand and perform a variety of operations including deleting object properties, voiding expressions, returning the data type and more. Examples:
typeof
: Returns the type of the operand as a string.void
: Discards the expression's return value and returnsundefined
.delete
: Removes an object property or an element from an array.+
: Unary plus tries converting the operand to a number, if it’s not already one.-
: Unary negation tries converting the operand to a number, if it’s not already one, and then negates it.++
and--
: Increment and decrement operators add/remove one from their operand.
9. When should you use the conditional operator in JavaScript? Use the conditional (ternary) operator when you need to evaluate a simple condition and make decisions based on whether the condition is true or false. This operator is especially useful when you’d like to choose between one of two values depending on some conditions. However, be cautious as using too many ternary operators sequentially can lead to code readability issues. Example:
let discount;
let totalAmount = 200;
discount = totalAmount > 100 ? '20%' : '10%';
console.log(discount); // Outputs "20%"
10. How does the +
operator differ when used with numbers versus strings in JavaScript?
When +
is used with two numeric operands, it performs arithmetic addition.
Example:
let result = 6 + 4;
console.log(result); // Outputs "10"
However, if +
is used between a string and another type of value, JavaScript will convert the non-string value to a string and then concatenate the strings.
Example:
let sentence = "The sum is " + 9 + 11;
console.log(sentence); // Outputs "The sum is 911"
In the latter case, JavaScript treats 9
and 11
as strings rather than numbers due to the presence of a string on the left side, so the result becomes "911"
instead of "20"
. To get the correct numeric result, ensure that the arithmetic operations occur first, then concatenate.
Example:
Login to post a comment.