2.5 Basic Operators in JavaScript

22 min read
104

In this, “Basic Operators,” we’ll delve into fundamental JavaScript concepts. Building on what we learned in the previous lesson, “2.4 Variable Declarations: let, const, and var,” we now shift our focus to “Basic Operators.”

But first, let’s understand what an operator is. Operators in JavaScript enable us to manipulate values, combine them, and perform various operations.

Basic Operators

Let’s begin by establishing a clear definition of what constitutes a basic operator.

Exactly, operators in programming languages like JavaScript enable us to manipulate values, transform them, and perform various operations, making it possible to work with data effectively. They allow us to perform tasks like mathematical calculations, comparisons, and string manipulations, among others. These operators are fundamental tools for working with values in a programming context.

JavaScript boasts various categories of operators, including: Mathematical operators, Comparison operators, Logical operators, Assignment operators, Increment and decrement operators, String concatenation operators, Type conversion operators, and many more.

Let’s delve into various types of operators, beginning with mathematical or arithmetic operators. These operators are essential for performing mathematical calculations and operations on values in JavaScript. Let’s explore them in more detail.

ALSO READ:  2.8 Working with Strings and Template Literals

MATHEMATICAL OPERATORS

You're likely already familiar with the addition (+) and subtraction (-) operators. However, JavaScript supports a range of arithmetic operations, such as multiplication and division.

Minus or Subtraction (-) operator

Let's use the minus operator (-) to calculate a person's age based on their birth year. To do so, first we declare the variable myBirthYear, which holds the person's birth year. We can then calculate the age by subtracting the birth year from the current year. Here's how you can do it:

  1. Declaring variable: <code>myBirthYear
const myBirthYear = 1989; // This variable holds the person's birth year.
  1. We can perform year subtractions by using the '-' operator sequentially, and then store the result in a separate variable named currentYear and myCurrentAge.
const currentYear = 2037; // This variable holds the current year.

// Calculate the person's current age
const myCurrentAge = currentYear - myBirthYear;
  1. Now, let's take a quick look at the result in the console:
console.log(myCurrentAge); // 48

Similarly, let's explore another scenario: let's determine Aaradhya's age by using her birth year, who was born in 2018:

const aaradhyaBirthYear = 2018; // Aaradhya's birth year
const currentYear = 2037; // The current year

// Calculate Aaradhya's current age
const aaradhyaAge = currentYear - aaradhyaBirthYear;

We can output her age to the console:

console.log(aaradhyaAge); // Output: 19

We can simultaneously record multiple values as well. To achieve this, we simply input the first value, followed by a comma, and then the second value. Additionally, we can expand on this by including additional commas for further values. For instance, in this scenario, we could log another piece of information.

console.log(myCurrentAge, aaradhyaAge); // Output: 48 19

This is how we utilize the subtraction (-) operator to address a straightforward problem, and in this case, simply to calculate an age.

Multiplication (*) and Division (/) Operators

You can perform various mathematical operations on variables in JavaScript. In this case, you want to multiply myCurrentAge by 2 and divide it by 2. Here's how you can do it and print both results to the console:

const myBirthYear = 1989; // Person's birth year
const currentYear = 2037; // Current year

// Calculate the person's current age
const myCurrentAge = currentYear - myBirthYear;

// Perform mathematical operations and print the results
console.log(myCurrentAge * 2, myCurrentAge / 2); // Output: // 96 24

In this code, myCurrentAge * 2 multiplies the current age by 2, and myCurrentAge / 2 divides the current age by 2. Both results are then printed to the console.

Take note of the distinction between these two computations. We have one calculation, followed by another, or essentially, another operation. This is possible because, as mentioned earlier, we can log multiple values simultaneously within a single console.log(). JavaScript allows you to include multiple expressions or values separated by commas within a single console.log() statement. In this case, we are generating two values: the first is 'myCurrentAge * 2', and the second is 'myCurrentAge / 2'.

Exponentiation operator

Now, let's incorporate the exponentiation operator (**). For instance, consider 2 to the power of 3:

const myBirthYear = 1989; // Person's birth year
const currentYear = 2037; // Current year

// Calculate the person's current age
const myCurrentAge = currentYear - myBirthYear;

// Perform mathematical operations and print the results
console.log(myCurrentAge * 2, myCurrentAge / 2, 2 ** 3);

In this code, 2 ** 3 calculates 2 to the power of 3, which equals 2 × 2 × 2 = 8. All three results are then printed to the console in a single console.log() statement.

Plus or addition (+) operator

Moving on, there's another practical application of the plus or addition (+) operator that we haven't explored yet. This operator can be employed to combine strings, essentially joining them together, a process known as string concatenation.

Let's create two variables for demonstration:

Let me explained the use of the plus operator (+) for string concatenation perfectly! In JavaScript, we can use the plus operator to join or concatenate strings together. When we concatenate strings, we can also include other characters like spaces or punctuation to format the resulting string as desired.

const firstName = "Amit";
const lastName = "Kumar";

Now, we can concatenate these two strings using the plus operator:

const fullName = firstName + lastName;

If we wish to display our full name in the console:

console.log(fullName); // Outputs: AmitKumar

At this point, we have a single large string containing both names, exactly as we declared earlier.

But what if we want a space between them? Well, that's not too complicated. All we need to do is create another string containing just a space and then concatenate it with the firstName and lastName variables.

So, we have firstName, which is simply "Amit" (a string). Remember, the JavaScript engine will substitute the "Amit" string with the firstName variable. Next, we create an empty string, or more precisely, a string with a space, and then append the "Kumar" string, which the JavaScript engine will replace with the lastName. This results in "Amit" plus a space plus "Kumar", like this:

const newFullName = firstName + " " + lastName;

Let's check the console:

console.log(newFullName); // Outputs: Amit Kumar

Indeed, this is precisely the desired outcome.

Presently, there is an improved method for combining strings known as template strings, but for now, let's concentrate on operators. The plus operator is incredibly valuable and frequently used.

typeof operator

Another category of operator is the typeof operator, which is used to determine the data type of a value or variable in JavaScript. It's a valuable operator for checking the type of a variable, whether it's a number, string, boolean, object, or another data type. And remember? The typeof operator, which we've previously covered in the "Variable Declarations: let, const, and var" tutorial. Therefore, there's no need for repetition. Recall that the typeof operator provides us with the data type of a value. You're already familiar with how it operates.

Now, let's move on to the next category, which consists of assignment operators. The most straightforward assignment operator is represented by the equal sign (=).

ASSIGNMENT OPERATORS

The equal sign (=) is the most fundamental assignment operator in JavaScript, and it's used to assign a value to a variable.

For instance, consider the following code:

let x = 9 + 5;

In this case, the equal sign (=) itself serves as an operator. Therefore, in this example, we actually have two operators in play: the addition operator (+) and the assignment operator (=).

  1. The plus operator (+): This operator performs the addition operation, which results in 9 + 5, equaling 14.
  2. The equal sign (=): This operator assigns the result of the addition operation (14) to the variable x.

In this specific scenario, "x" will be assigned the value 14, because the addition operator is executed before the assignment operator. This behavior is based on specific rules regarding operator precedence, which we will delve into in the next tutorial "Operator Precedence in JavaScript." The order of operations (operator precedence) plays a crucial role in determining the sequence of execution in more complex expressions.

Let's verify this in the console:

console.log(x); // 14

As you can see, it indeed works as expected. The addition of 9 and 5 is performed first, resulting in 14, which is then assigned to the variable "x." Thus, the assignment operator (=) functions as another operator in this context.

So, that is self another operator, but there are more assignment operators available.

Compound assignment operators

Compound assignment operators are convenient for performing repetitive operations on variables while maintaining readability and conciseness in your code.

Let's learn the concept of compound assignment operators perfectly!

+= operator

The += operator is an example of a compound assignment operator, and it combines an arithmetic operation with the assignment operation. This operator is used to increment the value of a variable by a specified amount, making the code more concise.

Let me demonstrate one for you, which is as follows:

x += 9; // x = x + 9 = 14 + 9 = 23

So, at this point, after the line "let x = 9 + 5;", we have established that x is 14, correct? Next, we encounter "x += 9;", which might seem a bit unusual with the "x plus equal" notation. So, what does "plus equal" actually signify? Well, it means that "x equals x plus 9," as indicated in the code comment. Instead of writing out "x = x + 9" in full, we can simplify it to "x += 9." Consequently, x should now be 23, since the previous value of x from the prior step was 14, resulting in 14 + 9 = 23. In essence, we are reassigning the value of x, which is why we use "let" in this context.

Now, let's observe this in action in the console:

console.log(x); // 23

As you can see, it indeed outputs 23.

Let's explore additional operators because, as you can envision, there are more operators similar to this one.

*= operator

The *= operator is a compound assignment operator in JavaScript. It is used for multiplication and assignment combined into a single operation.

As an illustration, consider the operation where 'x' is multiplied by 4 and assigned to 'x':

x *= 4; // This is equivalent to x = x * 4 = 23 * 4 = 92
console.log(x); // 92

You can think of x *= 4 as a shorthand for x = x * 4. In this example, the value of x is initially 23. When you use x *= 4, it multiplies the current value of x (which is 23) by 4. So, x becomes 92 after this operation.

You can use the division assignment or /= operator as well.

/= operator

The /= operator is a compound assignment operator in JavaScript. It combines division and assignment into a single operation.

x /= 4; // This is equivalent to x  = x / 4 = 92 / 4 = 23
console.log(x); // 23

You can think of x /= 4 as a shorthand for x = x / 4. Initially, the value of x is 92. When you use x /= 4, it divides the current value of x (which is 92) by 4. So, x becomes 23 after this operation.

So, the /= operator is just one of several compound assignment operators in JavaScript, and it helps make your code more concise when performing arithmetic operations on variables.

Let's explore another instance of the x++ operator, which essentially increments the value of x by 1.

++ operator

The ++ operator is known as the "increment" operator in JavaScript. It's used to increment the value of a variable by 1. There are two forms of the increment operator: x++ (post-increment) and ++x (pre-increment).

Here's how both forms work:

  1. Post-Increment (x++):
    • It increments the value of x by 1.
    • The result of the expression is the current value of x before the increment.
let x = 23;
x++; // x = x + 1 = 23 + 1 = 24
console.log(x); // 24
  1. Pre-Increment (++x):
  • It increments the value of x by 1.
  • This increments the value of x by 1 before any other operations are performed. So, after this code, the value of x will become 24.
let x = 23;
++x;
console.log(x); // 24

The ++x; operation increments the value of x by 1, which is equivalent to x = x + 1;, and after this operation, x becomes 24, just as if you had used x++;.

So, in both cases, the value of x is incremented by 1, but the result of the expression depends on whether you use the post-increment (x++) or pre-increment (++x) form.

The ++ operator is commonly used in loops, conditionals, and other scenarios where you need to increment or decrement variables.

-- operator

The -- operator is known as the "decrement" operator in JavaScript. It's used to decrease the value of a variable by 1. Like the increment operator ++, there are two forms of the decrement operator: x-- (post-decrement) and --x (pre-decrement).

Here's how both forms work:

  1. Post-Decrement (x--):
    • It decreases the value of x by 1.
    • The result of the expression is the current value of x before the decrement.
let x = 23;
x--;
console.log(x); // 22
  1. Pre-Decrement (--x):
    • It decreases the value of x by 1.
    • The result of the expression is the updated value of x after the decrement.
let x = 23;
--x;
console.log(x); // 22

The code --x; is equivalent to x = x - 1;.

In both of these statements decrement the value of the variable x by 1, but the result of the expression depends on whether you use the post-decrement (x--) or pre-decrement (--x) form.

COMPARISON OPERATOR

Let's discuss comparison operators; they're quite useful. Comparison operators are used to generate Boolean values.

To illustrate how they work, consider the following example, where we want to determine if my current age is greater than Aaradhya's age:

const myBirthYear = 1989; // My birth year
const aaradhyaBirthYear = 2018; // Aaradhya's birth year
const currentYear = 2037; // Current year

// Calculate my current age
const myCurrentAge = currentYear - myBirthYear;

// Calculate Aaradhya's current age
const aaradhyaCurrentAge = currentYear - aaradhyaBirthYear;

const isTrue = myCurrentAge > aaradhyaCurrentAge;

Now, let's consider the logical outcome. My current age can either be greater or not greater than Aaradhya's age. If it's greater, the result is true; otherwise, it's false.

To see the result, check the console:

console.log(isTrue); // true

The result is true, indicating that myCurrentAge is indeed greater than Aaradhya's age, as my current age is 48 and Aaradhya's age is 19.

In essence, you're essentially asking the operator, "Is my current age greater than Aaradhya's age?" The operator replies with "yes" (true) or "no" (false).

These comparison operators, such as >, >=, <, and <=, are valuable for making decisions in your code based on conditions like this.

Now, let's explore a practical application of the "greater than or equal to (>=)" comparison operator.

Imagine we want to determine whether Aaradhya has reached the legal age of 18. This means she must be either 18 or older. To represent this condition, we use the "greater than or equal to" operator, denoted as >=, with the number 18. This operator ensures that 18 is included as a valid age.

console.log(ageOfAaradhya >= 18); // true

In this case, the result is true because Aaradhya's age is 19, which satisfies the condition.

Now, let's consider another scenario. Suppose the current year is 2037, and Aaradhya was born in 2019, making her 18 years old.

const currentYear = 2037;
let aaradhyasBirthYear = 2019;
let nowAgeAaradhya = currentYear - aaradhyasBirthYear;

console.log(nowAgeAaradhya >= 18); // true

Here, we calculate her age and check if it's greater than or equal to 18, which is still true because she is exactly 18 years old. The operator (>=) ensures that 18 is considered part of the valid range.

Now, let's explore a different scenario. If Aaradhya was born in 2020, she would be 17 years old, which means the condition should be false.

aaradhyasBirthYear = 2020;
nowAgeAaradhya = currentYear - aaradhyasBirthYear;

console.log(nowAgeAaradhya >= 18); // false

Indeed, in this case, the result is false because Aaradhya's age (17) falls below the required minimum of 18 years. The (>=) operator helps us compare and make decisions based on these age conditions.

Please keep in mind that in practical development, it's customary to store the results, such as in the case of our comparison operator example, within variables rather than consistently logging the outcomes to the console. However, for the purposes of this demonstration, I'm illustrating how these operations work. Since we are still in the learning phase, we rely on the console to visualize the results.

Nonetheless, you can save these results in variables later in your code, like this:

const isFullAge = nowAgeAaradhya >= 18;

This variable, isFullAge, would hold the Boolean value.

Now, let's observe the result:

console.log(isFullAge); // false

Of course, in this case, it's false, representing a Boolean value.

To wrap up, let's consider a scenario where we want to perform these comparisons without using intermediate age variables. We can accomplish this in a single step, like so:

console.log(myCurrentAge > ageOfAaradhya);

To clarify, imagine that we have a substantial amount of code, and we wish to avoid calculating these ages separately. Instead, we can calculate currentYear - 1989 and then check if it's greater than currentYear - 2018.

console.log(currentYear - 1989 > currentYear - 2018); // true

In this line of code, (currentYear - 1989) is essentially equivalent to myCurrentAge, which equals (currentYear - myBirthYear). We are now performing these operations in a single step. Therefore, our previous code, where myCurrentAge represented (currentYear - 1989), is analogous to this code. Similarly, our previous code, where ageOfAaradhya represented (currentYear - 2018), is equivalent to this code.

In essence, the entire line of code, console.log(currentYear - 1989 > currentYear - 2018);, achieves the same result as defining myCurrentAge as currentYear - myBirthYear and ageOfAaradhya as currentYear - 2018.

Now, the key question at hand is how JavaScript determines whether it should prioritize mathematical calculations or comparisons.

One might initially assume that JavaScript would first compute (currentYear - 1989), which equals 48, and then immediately compare that result to the value of currentYear. This would be the case if operations were simply executed from left to right. However, as we'll discover, that's not how it operates.

In practice, we'll find that JavaScript handles this scenario seamlessly. It somehow discerns that it should first perform the "currentYear - 1989" calculation, followed by the "currentYear - 2018" calculation. Then, once it has these two numerical values, it proceeds to compare them using the ">" operator in the middle.

So, how does JavaScript achieve this? Well, that's precisely what we'll explore in the upcoming tutorial on "Operator Precedence in JavaScript."

Avatar for Amit

Amit (16)

Hello! I'm Amit Kumar, a passionate teacher specializing in web development and digital marketing. With several years of experience in the industry, I am dedicated to sharing my knowledge and expertise to empower aspiring learners like you.

Teaching Philosophy:

I believe in creating a dynamic and engaging learning environment where students can thrive. My teaching approach focuses on hands-on experience, practical applications, and real-world examples. I strive to make complex concepts understandable and enjoyable, ensuring that you not only grasp the fundamentals but also develop the skills necessary to excel in web development and digital marketing.

Web Development Expertise:

As a web development instructor, I am well-versed in HTML, CSS, JavaScript, and various frameworks such as React and Angular. I will guide you through the process of building responsive and user-friendly websites, exploring topics like front-end development, back-end integration, database management, and more. Together, we will delve into the latest trends and best practices in web development, equipping you with the tools to create stunning online experiences.

Digital Marketing Mastery:

In the rapidly evolving digital landscape, digital marketing is crucial for businesses to thrive. Through my digital marketing courses, I will help you navigate the intricacies of search engine optimization (SEO), social media marketing, content strategy, email marketing, and analytics. Gain insights into effective marketing techniques, harness the power of data-driven decision-making, and learn how to craft compelling campaigns that drive results.

Passion for Teaching:

Teaching is not just a profession for me; it's my passion. I find great joy in witnessing my students grow and succeed. I am committed to fostering a supportive learning community where questions are encouraged, ideas are shared, and challenges are overcome together. I am here to guide you every step of the way and provide the necessary resources for your personal and professional development.

Join me on this exciting journey of learning and discovery. Let's unlock your potential in web development and digital marketing together. Enroll in my courses today and embark on a transformative educational experience that will propel your career forward.
Start Learning Today!

5 1 vote
Article Rating
Subscribe
Notify of

guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Scroll to Top