×

Javascript Operators

The concept of operators is the basis of nearly all programming languages used in today's computing systems. Operators facilitate the execution of certain functions. For instance, the (+) symbol is used daily in daily life to add; however, one should understand that this (+) symbol is a character with a definite intention, i.e., to add two numeric values. This tutorial will discuss the various types of operators used in JavaScript.

What is an Operator?

In simple terms, an operator can be stated as something that does something to something else, just like a human controls machinery in order to achieve a certain intended purpose. In this case, the human being is the operator. In computer programming, an operator is a character that instructs the computer to perform a certain intended action. For instance, the (+) symbol is used to add two numeric values. In every programming language, this (+) symbol is an operator that executes the task of adding two values.

Operands are numeric values on which operations are performed. In the example provided, the two numeric values are the operands which are subjected to the operation.

Types of Operators in JavaScript

JavaScript divides its operators into eight categories. These categories include:

  1. Arithmetic Operators
  2. Assignment Operators
  3. String Operators
  4. Comparison Operators
  5. Logical Operators
  6. Conditional Operators
  7. Bitwise Operators
  8. Type-of Operator

This tutorial will provide a complete description of each of these types of operators in JavaScript.

What Are Arithmetic Operators in JavaScript?

As the name indicates, arithmetic operators are used to perform mathematical operations, e.g., addition, subtraction, multiplication, division, and some other operations.

For instance, to perform addition between two numeric values, the (+) operator is used in JavaScript.

Note: It should be known that the (+) operator in JavaScript is also responsible for combining two strings together, and that will be addressed in further sections.

 JavaScript boasts a set of unique arithmetic operators. The list of all arithmetic operators used in JavaScript is below.

Assuming variable x is assigned the value 10 and variable y is assigned the value 20, then –

OperatorDescriptionExample
+ (Addition)Adds two operands.x + y will give 30.
- (Subtraction)Subtracts the second operand from the first.x - y will give -10.
* (Multiplication)Multiplies both operands.x * y will give 200.
/ (Division)Divides the numerator by the denominator.y / x will give 2.
% (Modulus)Outputs the remainder of an integer division.y % x will give 0
++ (Increment)Increases an integer value by one.x++ will give 11.
-- (Decrement)Decreases an integer value by one.x-- will give 9.

Code

const sum = 5 + 3; // Addition

const diff = 10 - 2; // Subtraction

const p = 4 * 2; // Multiplication

const q = 8 / 2; // Division

console.log(sum, diff, p, q);

Output

JavaScript Operators

What Are Assignment Operators in JavaScript?

Assignment operators are responsible for assigning a value to various variables in JavaScript. For instance, if someone wants to assign the value 15 to a variable represented by X, that can be achieved using the assignment operator.

Consider the following illustration:

var x = 10;

document.write(x);

In this example, the variable x is assigned the value of 10. Whenever there is a sign of trying to display the value stored inside variable x inside the browser, the value to be displayed will be 10.

Any value placed to the right of the (=) symbol will be placed in the variable placed to its left. The list of various assignment operators in JavaScript is:

OperatorDescriptionExample
#NAME?Assigns values from the right side operand to the left side operandz = x + y will assign the value of x + y into z
+= (Add and Assignment)It adds the right operand to the left operand and assigns the result to the left operand.z += x is equivalent to z = z + x
−= (Subtract and Assignment)It subtracts the right operand from the left operand and assigns the result to the left operand.z -= x is equivalent to z = z - x
*=(Multiply and Assignment)It multiplies the right operand with the left operand and assigns the result to the left operand.z *= x is equivalent to z = z * x
/= (Divide and Assignment)It divides the left operand with the right operand and assigns the result to the left operand.z /= x is equivalent to z = z / x
%= (Modules and Assignment)It takes modulus using two operands and assigns the result to the left operand.z %= x is equivalent to z = z % x

Code

let n = 10;

n += 5;

n *= 2;

console.log(n);

Output

JavaScript Operators

What Are String Operators in JavaScript?

String operators in JavaScript are the tools used to manipulate strings. The (+) operator is used to concatenate two different strings. The (+=) operator can be used to append more content to an existing string.

Example: Let X=”Hello”, Y=”World”

OperatorDescriptionExample
+ConcatenationX+Y=Hello World
 +=Same as assignment operatorX+="Earth"=HelloEarth

Code

const s = "Hello" + " " + "World";

console.log(s);

Output

JavaScript Operators

What Are Comparison Operators in JavaScript?

Comparison operators are used to evaluate expressions to determine their truth value. As their name suggests, comparison operators are used to compare two values or variables in different ways.

JavaScript has a few comparison operators. Here are those operators one after another-

Consider variable x takes the value of 10 and variable y takes the value of 20, then –

OperatorDescriptionExample
== (Equal)Checks if the value of two operands is equal or not. If yes, then the condition becomes true.(x == y) is not true.
!= (Not Equal)Checks if the value of two operands is equal or not. If the values are not equal, then the condition becomes true.(x != y) is true.
=== (Strict equality)It checks whether the value and data type of the variable is equal or not. If yes, then the condition becomes true.(x === y) is not true.
!== (Strict inequality)It checks whether the value and data type of the variable is equal or not. If the values are not equal, then the condition becomes true.(x !== y) is true.
> (Greater than)Checks if the value of the left operand is greater than the value of the right operand. If yes, then the condition becomes true.(x > y) is not true.
< (Less than)Checks if the value of the left operand is less than the value of the right operand. If yes, then the condition becomes true.(x < y) is true.
>= (Greater than or Equal to)Checks if the value of the left operand is greater than or equal to the value of the right operand. If yes, then the condition becomes true.(x >= y) is not true.
<= (Less than or Equal to)Checks if the value of the left operand is less than or equal to the value of the right operand. If yes, then the condition becomes true.(x <= y) is true.

Code

var x = 5;  // Declaring variable x

//comparing c with different values

console.log(x==8);      // Return False (x<8)

console.log(x===5);     // Return True

console.log(x!=8);      // Return True (x!=8)

console.log(x!==5);      // Returns False

console.log(x>8);       // Returns false (x<8)

console.log(x<8);       // Returns true because x = 5

console.log(x>=5);      // Returns True (x = 5)

console.log(x<=8);      // Returns True (x < 8)

Output

JavaScript Operators

The operators (x===5) and (x!==5) will return both the value and the data type. It will return true only when the data type and the value are the same.

What Are Logical Operators in JavaScript?

Logical operators in JavaScript are used for determining the logical relationship between two variables or values. These return boolean values and check the veracity of one or more conditions.

Three types of logical operators exist in JavaScript:

1. Logical And

2. Logical Or

3. Logical Not

For example, x is 10 and y is 0.

OperatorDescriptionExample
&& (Logical AND)If both the operands are non-zero, then the condition becomes true.(x && y) is false
|| (Logical OR)If any of the two operands are non-zero, then the condition becomes true.(x || y) is true.
! (Logical NOT)Reverses the logical state of its operand. If a condition is true, then the Logical NOT operator will make it false.!x is false.

Code

const a = true, b = false;

console.log(a && b); // Logical AND

console.log(a || b); // Logical OR

Output

JavaScript Operators

The not operator checks whether the value held by variable x is not the same as the one in variable y. It returns true if they are unequal.

Code

var x = 5;  // Declaring variable x

var y = 8;

console.log(!(x==y));  // Return True because x is not equal to y. 

Output

JavaScript Operators

What Are Conditional Operators in JavaScript?

Conditional operators of JavaScript are used to assign a value to a variable based on a condition taken as input. Every condition has either true or false as the result.

The syntax of the conditional operator is very simple. It has a variable name followed by a condition. According to the outcome of this condition, two possible values are provided: value 1 and value 2.

Syntax

Variable name = (condition)? Value1 : Value2

Code

const age = 18;

const status = age >= 18 ? "Adult" : "Minor";

console.log(status);

Output

JavaScript Operators

What Are Bitwise Operators in JavaScript?

Though bitwise operators lack widespread practical applications in everyday day-to-day situations, they are of inherent value. Their application, however, is uncommon. In computing, numerical data is represented in binary, and bitwise operators work with 32-bit integers.

Before any operation is performed, each operand is initially converted to a binary representation and then returned as a JavaScript number. The four basic bitwise operators in JavaScript are:

  1. Bitwise AND
  2. Bitwise OR
  3. Bitwise NOT
  4. Bitwise XOR

Assuming variable x is 2 and variable y is 3, it then follows that –

OperatorDescriptionExample
& (Bitwise AND)It performs a Boolean AND operation on each bit of its integer arguments.(x & y) is 2.
| (Bitwise OR)It performs a Boolean OR operation on each bit of its integer arguments.(x | y) is 3.
^ (Bitwise XOR)It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both.(x ^ y) is 1.
~ (Bitwise Not)It is a unary operator and operates by reversing all the bits in the operand.(~y) is -4.

Code

var x = 5;

var y = 1;

console.log((x & y));  // works the same as logic gates

console.log((x | y));  // works the same as logic gates

console.log((~x));    // Returns (-6) and works the same as (-x-1)

console.log((x ^ y)); // Returns 4 and works the same as XOR gate.

Output

JavaScript Operators

The XOR gate has a true output only where one of the two input values is true. If the two input values are both true, then the output resulting will be false.

Type-of Operator in JavaScript

The typeof() operator in JavaScript is applied to determining the precise type of value contained in a variable, which may be a number, string, or boolean. In addition, it can distinguish between null and undefined values. There are five primitive data types in JavaScript, and the typeof() operator gives information regarding the precise data type a variable is holding at the moment.

Code

var x = 5;                   // Numeric value

var y = "hello";            // String value

var flag = false;           // Boolean Value

var p;                      // No value

console.log(typeof(x));               // Return number   

console.log(typeof(y));               // Return String

console.log(typeof(flag));            // Return Boolean  

console.log(typeof(p));               // Return undefined

Output

JavaScript Operators

Conclusion

JavaScript operators are essential for developers who seek to create efficient and dynamic code. These operators, which include arithmetic, comparison, logical, and bitwise operations, enable developers to manipulate data effectively and control program flow. With knowledge of the functionalities outlined in this discussion, one is capable of unleashing the full potential of JavaScript in projects.


Related Topics

JavaScript Function

An important part of JavaScript is the ability to create new functions within <script>.....</script> tag. To declare a function in JavaScript using function keyword. We call JavaScript function multiple times to reuse the...

3 minutes read.

JavaScript dropdown onchange

What is onchange event? It is an event in JavaScript used to make the web pages dynamic. The onchange event gets triggered whenever the value of an event changes. It usually...

3 minutes read.

Javascript Document Object

Document object represents the whole HTML documents. When HTML document is loaded in browser it becomes the document object. It is the root elements that represent the HTML documents. With the help of...

2 minutes read.

JavaScript Image resize before upload

Image resizing can be a quite tedious task, so it is usually done on the server-side. The resized image file is then delivered to the client side. However, sometimes the...

3 minutes read.

JavaScript Time Picker Demo

Time Pickers in JavaScript are lightweight and mobile-friendly controls that let the users enter or select date and time values. These values can be from a pop-up calendar or a...

5 minutes read.

Javascript Forms Validation

Form validation works at server, after client had entered all the necessary details and then pressed submit button. JavaScript provides the facility to validate the form on the client side...

9 minutes read.

Array to String in JavaScript

As a web developer, you often have to deal with multiple data types in a single application. How to convert an array to a string in JavaScript is essential for...

19 minutes read.

Javascript Variable

Variables are used to store values (name="Ram") or expressions (Sum=x+y). Before using of variable first we need to declare it. We use keyword var to declare a variable like this: var name; There are two types of variables: Local Variable ...

1 minute read.

Javascript getElementByID

The document.getElementById() method returns the element of specified id. In below example we receive input field by using document.getElementById() method, here document.getElementById() receive input value on the basis of input field...

1 minute read.

Javascript Email Validation

We can validate the email with the help of JavaScript. Here we check the condition related to any email id, like email it must have "@" and "." sign and...

2 minutes read.

Javascript comment

Introduction In programming languages, comments are a method to include meaningful annotations within the code that the compiler or interpreter will ignore at run time. That is to say, though comments...

7 minutes read.

Minify JavaScript

What do you mean by the term ‘Minification’? The technique of minification reduces the amount of code and markup in your websites and scripting files. It's one of the most used...

4 minutes read.

Callback and Callback Hell in JavaScript

The widely used client-side programming language JavaScript is simple, light, and interpretive. JavaScript is used by the majority of client-side web applications. It is also possible to use JavaScript on...

3 minutes read.

D3.js Tutorial

Introduction of D3.js D3.js is referred to as a JavaScript library that is used to manipulate the documents according to the data. The intensity of D3 is based on web standards...

5 minutes read.

Javascript Dialog Box

A JavaScript dialog box is predefined function which is used to perform different task. Some functions are used in JavaScript Dialog box. FunctionDescriptionalert()To give alert message to userprompt()To input value from...

2 minutes read.

JavaScript Console log Multiple variables

What does console.log() do in JavaScript? The console.log() is a function in JavaScript language. It is used to: Print any message in the console which is visible to the userPrint the values...

3 minutes read.

JavaScript setTimeout()

The setTimeout() method creates a timer that, when it expires, runs a function or provides a piece of code. setTimeout() is an asynchronous function, which means that it will not interrupt...

3 minutes read.

JavaScript moment date difference

Often date differences are required on the web platforms for various reasons. They can be: To find the duration, of course, someone is pursuingTo find the age of a user from...

7 minutes read.

Functional Programming in JavaScript

Most developers work with object-oriented programming while developing their applications, but sometimes they need to change their approach to solve some specific tasks. Although mostly we tend to go for...

6 minutes read.

Javascript Cookies

Cookie is a piece of data which is sent from a website and stored locally by the user's browser. Cookie is needed because HTTP is stateless protocol. Today most of...

1 minute read.