A Comprehensive Guide to Mastering Basic Javascript Operators

A Comprehensive Guide to Mastering Basic Javascript Operators

Today marks two weeks since I began learning JavaScript, and I am thrilled to embark on an article series that delves deep into an intriguing concept weekly.

At its core, JavaScript revolves around communication—between the code you write and the web pages, programs, and applications it brings to life. Just like any engaging conversation, specific rules, patterns, and signals facilitate smooth interactions.

This is where operators come into play. They can be likened to the punctuation marks, conjunctions, and prepositions of JavaScript—a set of small connecting words that establish links and provide instructions. Operators such as +, -, ==, &&, and others serve as essential elements.

Without operators, our code conversations would be ambiguous and confusing. We might say "this and that" instead of "this + that" or express "this is the same as that" rather than "this == that."

In this article, we will explore the basic operators, ranging from Arithmetic to Logical operators. By the end of this article, you'll understand each operator's purpose, also with an understanding of how they enable JavaScript to communicate clearly and effectively.

Arithmetic Operators

In JavaScript, arithmetic operators allow you to perform mathematical calculations and manipulate numbers. They enable you to add, subtract, multiply, divide, and perform other mathematical operations. Understanding how to use these operators effectively is crucial for mastering JavaScript. In this section, we'll explore each arithmetic operator in detail and provide practical code examples to illustrate their usage.

  1. Addition Operator (+)

The addition operator (+) is used to add two numbers or concatenate strings. When used with numerical values, it performs simple addition. Let's take a look at some examples:

let num1 = 5;
let num2 = 10;
let result = num1 + num2;
console.log(result); // Output: 15

let str1 = "Hello";
let str2 = " world!";
let message = str1 + str2;
console.log(message); // Output: Hello world!
  1. Subtraction Operator (-)

The subtraction operator (-) is used to subtract one number from another. It can also be used to negate a numerical value. Here are a couple of examples:

let num1 = 10;
let num2 = 5;
let result = num1 - num2;
console.log(result); // Output: 5

let num = 7;
let negatedNum = -num;
console.log(negatedNum); // Output: -7
  1. Multiplication Operator (*)

The multiplication operator (*) is used to multiply two numbers. It takes two numbers and returns their product. Here's an example:

let num1 = 3;
let num2 = 4;
let result = num1 * num2;
console.log(result); // Output: 12
  1. Division Operator (/)

The division operator (/) is used to divide one number by another. Let's see an example:

let num1 = 10;
let num2 = 2;
let result = num1 / num2;
console.log(result); // Output: 5
  1. Modulo Operator (%)

The modulo operator (%) returns the remainder of a division operation. It can be used to check divisibility or to perform cyclic operations. Here's an example:

let num1 = 10;
let num2 = 3;
let remainder = num1 % num2;
console.log(remainder); // Output: 1
  1. Exponentiation Operator (**)

The exponentiation operator (**) raises the first operand to the power of the second operand. It is a relatively new addition to JavaScript. Here's an example:

let base = 4;
let exponent = 3;
let result = base ** exponent;
console.log(result); // Output: 64

Order of Operations

JavaScript follows the standard mathematical rules for the order of operations (BODMAS). Parentheses can be used to override the default precedence. For example:

let result = 2 + 3 * 4;
console.log(result); // Output: 14

let resultWithParentheses = (2 + 3) * 4;
console.log(resultWithParentheses); // Output: 20

Assignment Operators

Assignment operators in Javascript enable you to write code concisely and efficiently. Here, I'll be showing you different types of Assignment operators and how they can be used effectively:

1. The Assignment Operator (=)

The assignment operator, denoted by the equals sign (=), is the most basic and commonly used assignment operator in JavaScript. It assigns the value on the right-hand side to the variable on the left-hand side. Let's take a look at an example:

let num = 10;

2. Addition Assignment Operator (+=)

The addition assignment operator (+=) adds the value on the right-hand side to the current value of the variable and assigns the result back to the variable. It is a shorthand way of writing 'variable = variable + value'. Here's an example:

let num = 5;
num += 3;
console.log(num); // Output: 8

In this example, the value of 'num' is initially 5. The addition assignment operator (+=) adds 3 to the current value of 'num' and assigns the result (8) back to 'num'.

  1. Subtraction Assignment Operator (-=)

The subtraction assignment operator (-=) subtracts the value on the right-hand side from the current value of the variable and assigns the result back to the variable. It is a shorthand way of writing 'variable = variable - value'. Let's see an example:

let num = 10; 
num -= 4; 
console.log(num); // Output: 6

In this example, the value of 'num' is initially 10. The subtraction assignment operator (-=) subtracts 4 from the current value of 'num' and assigns the result (6) back to 'num'.

  1. Multiplication Assignment Operator (*=)

The multiplication assignment operator (*=) multiplies the value on the right-hand side with the current value of the variable and assigns the result back to the variable. It is a shorthand way of writing 'variable = variable * value'. Consider the following example:

let num = 3; 
num *= 5; 
console.log(num); // Output: 15

In this example, the value of 'num' is initially 3. The multiplication assignment operator (=) multiplies the current value of 'num' by 5 and assigns the result (15) back to 'num'.

  1. Division Assignment Operator (/=)

The division assignment operator (/=) divides the current value of the variable by the value on the right-hand side and assigns the result back to the variable. It is a shorthand way of writing 'variable = variable / value'. Let's examine an example:

let num = 20; 
num /= 4; 
console.log(num); // Output: 5

In this example, the value of 'num' is initially 20. The division assignment operator (/=) divides the current value of 'num' by 4 and assigns the result (5) back to 'num'.

  1. Remainder Assignment Operator (%=)

The remainder assignment operator (%=) divides the current value of the variable by the value on the right-hand side and assigns the remainder back to the variable. It is a shorthand way of writing 'variable = variable % value'. Consider the following example:

let num = 17; 
num %= 5; 
console.log(num); // Output: 2

In this example, the value of 'num' is initially 17. The remainder assignment operator (%=) divides the current value of 'num' by 5 and assigns the remainder (2) back to 'num'.

  1. Exponentiation Assignment Operator (**=)

The exponentiation assignment operator (=) raises the current value of the variable to the power of the value on the right-hand side and assigns the result back to the variable. It is a shorthand way of writing 'variable = variable ** value'. Let's see an example:

let num = 2;
num **= 3;
console.log(num); // Output: 8

In this example, the value of 'num' is initially 2. The exponentiation assignment operator (=) raises 'num' to the power of 3 and assigns the result (8) back to 'num'.

Next up are the comparison operators

Comparison Operators

Comparison operators are an integral part of any programming language, and JavaScript is no exception. These operators allow us to compare values and perform logical operations based on the results. In this section, I'll be explaining to you JavaScript's comparison operators, exploring their functionality, and illustrating their usage. Additionally, I'll shed light on the crucial distinction between equality and identity operators:

The Equality Operator (==)

The equality operator, denoted by two equal signs (==), compares two values for equality, disregarding their data types. It performs type coercion if necessary, meaning that if the operands have different data types, JavaScript tries to convert them to a common type before making the comparison. Here's an example:

let num = 5;
let strNum = "5";
console.log(num == strNum); // true

In the above code snippet, even though num is a number and strNum is a string, the equality operator coerces the string to a number and evaluates them as equal.

The Inequality Operator (!=)

The inequality operator (!=) checks if two values are not equal to each other. Similar to the equality operator, it performs type coercion when necessary. Here's an example:

let num = 5;
let strNum = "5";
console.log(num != strNum); // false

In the above example, the inequality operator coerces the string to a number and evaluates them as equal, resulting in a false value.

The Strict Equality Operator (===)

The strict equality operator (===) compares both value and data type. It returns true only if the operands are of the same type and have the same value. Unlike the equality operator, it does not perform type coercion. Consider the following example:

let num = 5;
let strNum = "5";
console.log(num === strNum); // false

The Strict Inequality Operator (!==)

The strict inequality operator (!==) checks if two values are not equal in both value and data type. It returns true if the operands are either of different types or have different values. Here's an example:

let num = 5;
let strNum = "5";
console.log(num !== strNum); // true

The Greater Than Operator (>)

The greater than operator (>) compares two values and returns true if the left operand is greater than the right operand. Here's an example:

let num1 = 10; 
let num2 = 5; 
console.log(num1 > num2); // true

In this example, the greater than operator compares num1 and num2 and determines that num1 is indeed greater.

The Less Than Operator (<)

The less than operator (<) compares two values and returns true if the left operand is less than the right operand. Consider the following example:

let num1 = 10; 
let num2 = 5; 
console.log(num1 < num2); // false

The Greater Than or Equal To Operator (>=)

The greater than or equal to operator (>=) checks if the left operand is greater than or equal to the right operand. It returns true if the comparison holds. Here's an example:

let num1 = 10; 
let num2 = 5; 
console.log(num1 >= num2); // true

In this example, the greater than or equal to operator evaluates to true since num1 is greater than num2.

The Less Than or Equal To Operator (<=)

The less than or equal to operator (<=) compares two values and returns true if the left operand is less than or equal to the right operand. Consider the following example:

let num1 = 10; 
let num2 = 5; 
console.log(num1 <= num2); // false

Equality vs. Identity Operators

It's crucial to understand the distinction between the equality (==) and identity (===) operators. While the equality operator performs type coercion to compare values, the identity operator compares both the value and the data type without coercion.

For example, consider the following code:

let num = 5; 
let strNum = "5"; 
console.log(num == strNum); // true 
console.log(num === strNum); // false

In the above code snippet, the equality operator coerces the string "5" to a number and evaluates them as equal, resulting in true. However, the identity operator compares both the value and the data type and determines that num (a number) and strNum (a string) are not identical, resulting in false.

In general, it is recommended to use the strict equality (===) and strict inequality (!==) operators to avoid unexpected behaviors caused by type coercion.

Logical Operators

Logical operators allow you to make decisions based on multiple conditions and control the flow of your code. Understanding how to use logical operators effectively is crucial in writing robust and efficient JavaScript code.

JavaScript provides three logical operators: AND (&&), OR (||), and NOT (!). These operators are often used to combine or modify the results of comparison operators, such as equality (==) or inequality (!=), to create more complex conditions.

The AND Operator (&&)

The AND operator returns true if both operands are true; otherwise, it returns false. It is denoted by two ampersands (&&). Let's look at an example:

console.log(true && true) //Output: true
console.log(true && false) //Output: false
console.log(false && true) //Output:false
console.log(false && false) //Output: false

The OR Operator (||)

The OR operator returns true if at least one of the operands is true; otherwise, it returns false. It is denoted by two vertical bars (||). Consider the following example:

console.log(true || true) //Output: true
console.log(true || false) //Output: true
console.log(false || true) //Output: true
console.log(false || false) //Output: false

The NOT Operator (!)

The ! operator returns the opposite boolean value of its operand. This means that if the operand evaluates to true, the expression will return false. And vice versa.

Example:

console.log(!true) //Output: false
console.log(!false) //Output: true

Conclusion

Well, we've come to the end of our journey learning the basics of JavaScript operators. I hope this guide helped break down the main types of operators - arithmetic, comparison, logical, and assignment - in a way that was easy to understand.

Operations like addition, subtraction, multiplication, and division are extremely useful for performing simple math in your code. Comparison operators let you check relationships between values to direct your program's flow.

Mastering the basics like we covered today is so important. It's like learning your multiplication tables when you first start studying math. Having a solid grasp of operators will serve as a strong foundation as you move on to more advanced JavaScript operators and topics.

There are other JavaScript operators like the Bitwise operators, ternary operators, and more. You can learn ore about these from freecodecamp. Catch you in the next one!