Operators in JavaScript: Types and Usage Explained
☰Fullscreen
Table of Content:
Following operators available in JavaScript:
- Assignment operators
- Arithmetic operators
- Comparison operators
- Logical operators
- String operators
- Conditional operators
Assignment Operators
- Like most programming languages,
=is the assignment operator - Variables can be declared either by key
varand value OR simply by assigning values directly. Ex –var x = 42; ORx = 42 ; - Explicit type declaration is not necessary.
- Same variable can be assigned values of different data types. To know the type of a variable, use
typeofoperator. Ex –
var x = "hello";
var x = true;
console.log(typeof x); //returns Boolean
Comparison Operators
- JavaScript has operators like
<, >, !=, >=, <=to compare 2 operands. - What is unique about JavaScript is the
==and===operators? ==compares the operands and returnstruewithout considering their data type. Ex:var a = 10, b= “10”;if(a==b)results intruedue to the same value they carry, but ignores data types differentiation.- However,
if(a===b)results infalseas they are of different data types.
Standard Arithmetic Operators
- Addition
+Ex:[5 + 8] - Subtraction
-Ex:[49 – 38] - Division
/Ex:[ 49 / 7] - Multiplication
*Ex:[28 * 2]
More on Arithmetic Operators
- Modulus
%to return the remainder of a division – Ex:50 % 7is 1 - Increment
++to increment the operand itself by 1 – Ex: If x=4,x++evaluates to5 - Decrement
--to decrement the operand itself by 1 – Ex: if x= 10,x—-evaluates to9
Logical Operators
AND &&, OR ||, NOT ! are the logical operators often used during conditional statements to test logic between variables.
Expr1 && Expr2returns true if both are true, else returns false.Expr1 || Expr2returns true if either is true.!Expr1operates on single operand to convert true to false and vice versa.
String Operator
Operator + is used to concatenate strings. x = "Hello"; y = " World "; x + y; /* Returns “Hello World” */
While concatenating, JavaScript treats all data types as strings even if values are of different data types.
x = "Hello"; y = 100; z = 333; x + y + z; /* Returns “Hello100333” */