×

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 loops

Loops in JavaScript: Loops are used to execute a specific piece or block of code repeatedly until the given condition is satisfied. What is a Loop? Almost all loops contain a certain...

7 minutes read.

What is Ternary Operator in JavaScript?

In some cases, a ternary operator can be used instead of an if-else expression. A ternary operator examines a condition and then runs a block of code in response to...

4 minutes read.

Javascript Tutorial

JavaScript is a light-weight, dynamic scripting language that is mainly employed to create interactive front-end web applications. It was originally developed in 1995 by Brendan Eich at Netscape Communications Corporation...

5 minutes read.

Javascript Redirect Button

What is a redirect button? When a button acts as a hyperlink, it is known as a redirect button. On clicking the button, it transfers the user to another page. How to...

3 minutes read.

Javascript Number

The Number object is a wrapper object which allows you to work with numerical values. The number object is created using the Number() constructor.It may be integer or floating-point. Syntax var n=new Number(value); Examples <!DOCTYPE html>   <html>   <body>   <script>   var x=100;//integer value   var y=100.7;//floating point value   var z=12e5;//exponent value, output: 1200000   var n=new Number(20);//integer value by number object     document.write(x+" "+y+" "+z+" "+n);   </script>   </body>   </html> Try Now Output 100 100.7 1200000 20 Description The primary...

1 minute read.

Javascript Data Types

An Overview of JavaScript Data Types In computing, there are a number of data types, including numbers, strings, and booleans, to name a few. The role of these data types in...

5 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 input maxlength

Various attributes often accompany the input tag in HTML to change the properties of the input field. Maxlength() is one such attribute. The maxLength attribute defines the maximum number of characters...

2 minutes read.

Javascript Example

What is JavaScript? JavaScript is a highly versatile programming language. It provides the capability to add interactivity to static web pages, which are designed with HTML and CSS. It also provides...

5 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 radio button checked value

What are radio buttons? A radio button is defined as an icon that is used to take input from the user. The user can choose only one option(value) from the group...

5 minutes read.

Javascript Window Object

The window object represents a window in browser. An object of window is created automatically by the browser. Window is the object of browser, it is not the object of JavaScript. The...

3 minutes read.

Javascript Password Validation

Here we see that how to validate any password field. Like password field can be blank and length of password is minimum 8 characters. Example <!DOCTYPE html>   <html>   <head>   <script>   functionpass_validation()   {     var password=document.myform.password.value;     if (password==null || password=="")   {     alert("password can't be blank");     return false;     }   else if(password.length<8)   {     alert("Password must be at least 8 characters long.");     return false;       }     }     </script>   </head>   <body>   <form name="myform" method="post" action="register.php" onsubmit="return pass_validation()" >   Password: <input type="password" name="password">   <input type="submit" value="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute 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.

Javascript Print

JavaScript help's the functionality using the print function of window object. In JavaScript print function window.print() print the current web page when it executed. We can call function directly using onclick...

1 minute 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 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.

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 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.

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.