Saturday, May 04, 2024

Discover the Potential of Operators in the JavaScript Programming Language

Before you move on to learning operators in the JavaScript programming language, it is assumed that you are already familiar with variables in JavaScript, see here; and that you have already started a JavaScript project js_tutorial. Operators in the JavaScript programming language, as in other programming languages, are symbols used to perform various operations on values, variables, and expressions. They play a key role in calculating and manipulating data in the JavaScript programming language because they allow programmers to calculate values, control the flow of the program, and create complex logical expressions.

Understanding how operators work and how they are used is essential for developing JavaScript applications. Operators in JavaScript are not significantly different from operators in other programming languages. Most programming languages have similar basic operators, but there are some differences in behavior and syntax. As far as basic operators are concerned, the JavaScript programming language does not lag behind much more developed programming languages at all.

Students learn operators in the JavaScript programming language

Students learn Operators in the JavaScript programming language

JavaScript supports various types of operators, including the following:

  • Arithmetic operators
  • Assignment operators
  • Unary (Increment and Decrement) operators
  • Comparison operators
  • Logical operators
  • Comma operator
  • Ternary (Conditional) operator
  • Nullish Coalescing operator
  • Optional Chaining operator
  • Bitwise shift operators
  • Etc.

When it comes to ternary, nullish coalescing, optional chaining, bitwise shift operators, and so on; we will cover them in other future posts of this tutorial as they come up in practical examples. For now, it would be great to learn and familiarize yourself with the most basic operators that you will frequently use in your projects. First, let’s start with arithmetic operators and introduce other fundamental operators in the JavaScript programming language on a single web page. Meanwhile, we’ll create another web page to showcase a simple calculator. So, your project will have two new lessons. Our calculator creation will definitely demonstrate true mastery in CSS styling, which is so straightforward that we won’t use Bootstrap at all in the fourth lesson.

Arithmetic Operators: Basic Mathematical Operators on Numbers

Arithmetic operators in the JavaScript programming language are symbols or signs used to perform basic mathematical operations on numbers. These operators allow you to carry out various arithmetic calculations and manipulate numeric values. They are used in many aspects of programming, including creating mathematical formulas, managing variable values, data processing, and many other tasks. For example, in web application development, arithmetic operators are often used to calculate values displayed to users or manage numbers in games.

In addition to basic operations, JavaScript also supports more complex mathematical functions and methods through the Math object, which provides a wide range of mathematical functions such as:
sqrt - square root, pow - exponentiation and many others. We’ll explore these functions more in future lessons. Arithmetic operators are therefore a fundamental component for performing computational operations in JavaScript and other programming languages. Now, let’s create an HTML file to continue our tutorial. Open Visual Studio Code or your preferred IDE - Integrated Development Environment, navigate to your js_tutorial project, and create a new file in the lessons directory named lesson3.html. In this file, type the following HTML5 code:

header></header>

<h2 class="bg-primary text-light text-center py-3">Lesson 3. - Using operators in the JavaScript programming language</h2>

<div class="container">

    <script src="../js/operators.js"></script>

</div>   

    <script src="../js/includes.js"></script> 

<footer></footer>

Open the index.html file and add the following item between the <ul> and </ul> tags.

<li><a href="lessons/lesson3.html">

                    Lesson 3. - Using operators in the JavaScript programming language        

                </a></li>

Home page of js_tutorial project

Home page of js_tutorial project

Next, create a new file in the js folder and name it operators.js. Type the following JavaScript code into the file:

// arithmetic operators

document.write("<h3><font color=\"seagreen\">Arithmetic operators</font></h3>");

let x = 7;

let y = 4;

let z = 0;

document.write("<p>X = " + x + "</br>" + "Y = " + y + "</p>"); 

// addition operator 

document.write("<h4>The addition operator</h4>"); 

z = x + y

document.write("<p>X + Y = " + z + "</p>"); 

// subtraction operator

document.write("<h4>The subtraction operator</h4>"); 

z = x - y;

document.write("<p>X - Y = " + z + "</p>");

// multiplication operator

document.write("<h4>The multiplication operator</h4>");

z = x * y;

document.write("<p>X * Y = " + z + "</p>");

// exponentiation operator

document.write("<h4>The exponentiation operator</h4>");

z = x ** y;

document.write("<p>X ** Y = " + z + "</p>");

// division operator

document.write("<h4>The division operator</h4>");

z = x / y;

document.write("<p>X / Y = " + z + "</p>");

// modulus operator

document.write("<h4>The modulus operator</h4>");

z = x % y;

document.write("<p>X % Y = " + z + "</p>");

Click on the third lesson link and you will get the following result:

Arithmetic operators

X = 7
Y = 4

The addition operator

X + Y = 11

The subtraction operator

X - Y = 3

The multiplication operator

X * Y = 28

The exponentiation operator

X ** Y = 2401

The division operator

X / Y = 1.75

The modulus operator

X % Y = 3

Assignment Operators: Understanding the Basics

Assignment operators in the JavaScript programming language are symbols or characters used to assign values to variables or properties of objects. These operators allow programmers to set the values of variables or properties to specific values, which is a basic operation in most programming languages, including the JavaScript programming language. Assignment operators are important because they allow you to manipulate data and manage variable values in your JavaScript code.

They form the core component for building and updating state in your programs. Without these operators, it would be more difficult to set values to variables or update properties of objects, which would significantly complicate application development. Using assignment operators can also improve code readability and reduce the number of lines of code, especially when performing simple arithmetic operations. Go back to the operators.js file and add the following JavaScript code:

// assignment operators

document.write("<h3><font color=\"seagreen\">Assignment operators</font></h3>");

x = 9;

y = 5;

document.write("<p>X = " + x + "</br>" + "Y = " + y + "</p>");

// addition assignment operator

document.write("<h4>The addition assignment operator</h4>");

x = 9;

x += y;

document.write("<p>X += Y -> " + x + "</p>");

// subtraction assignment operator

document.write("<h4>The subtraction assignment operator</h4>");

x = 9;

x -= y;

document.write("<p>X -= Y -> " + x + "</p>");

// multiplication assignment operator

document.write("<h4>The multiplication assignment operator</h4>");

x = 9;

x *= y;

document.write("<p>X *= Y -> " + x + "</p>");

// exponentiation assignment operator

document.write("<h4>The exponentiation assignment operator</h4>");

x = 9;

x **= y;

document.write("<p>X **= Y = " + x + "</p>");

// division assignment operator

document.write("<h4>The division assignment operator</h4>");

x = 9;

x /= y;

document.write("<p>X /= Y -> " + x + "</p>");

// modulus assignment operator

document.write("<h4>The modulus assignment operator</h4>");

x = 9;

x %= y;

document.write("<p>X %= Y -> " + x + "</p>");

When you start or refresh the lesson3.html webpage you will get additional text on the page.

Assignment operators

X = 9
Y = 5

The addition assignment operator

X += Y -> 14

The subtraction assignment operator

X -= Y -> 4

The multiplication assignment operator

X *= Y -> 45

The exponentiation assignment operator

X **= Y = 59049

The division assignment operator

X /= Y -> 1.8

The modulus assignment operator

X %= Y -> 4

Increment and decrement operators

The increment ++ and decrement -- operators in the JavaScript programming language are used to increase or decrease the value of a variable by 1. These operators are important because they often make writing code easier and more efficient in situations where you need to work with numbers and variables that need to be incremented or incremented. reduce by certain values. Increment and decrement operators are often used in loops such as for loops and in situations where you need to keep track of counters, iterations, and indices.

These operators can also make code more readable and reduce the need for redundant lines of code. It is important to note that the increment and decrement operators should be used carefully, because their careless use can lead to misunderstandings and errors in the code. They should be used where it makes sense and where they are needed for specific operations of incrementing or decrementing variable values. Go back to the operators.js file and add the following JavaScript code:

// increment and decrement operators

document.write("<h3><font color=\"seagreen\">Increment and decrement operators</font></h3>");

// increment operator

document.write("<h4>The increment operator</h4>");

let a = 8;

document.write("<p>A = 8</p>");

a++// increments the variable by 1

++a;

document.write("<p>A++ i ++A = " + a + "</p>");

// decrement operator

document.write("<h4>The decrement operator</h4>");

a--// decrements the variable by 1

--a;

document.write("<p>A-- i --A = " + a + "</p>");

When you start or refresh the lesson3.html webpage you will get additional text on the page.

Increment and decrement operators

The increment operator

A = 8

A++ i ++A = 10

The decrement operator

A-- i --A = 8

Comparison Operators: Making Sense of Values

Comparison operators in the JavaScript programming language are symbols or signs used to compare two values to determine their relationship to each other. These operators are often used for conditional code execution, that is, for making decisions according to the result of a comparison. Comparison operators return a boolean value true or false as a result of the comparison. Comparison operators are important because they allow programmers to conditionally control the execution of code based on certain conditions.

They are also important in manipulating arrays and sorting data, as they allow comparison of array elements. In addition, a proper understanding of comparison operators is crucial to avoid errors in your code, especially in cases where data types are important. Using the wrong comparison operators can lead to unexpected results. Therefore, it is important to carefully consider which operator to use depending on the specific requirements and types of data you are working with. Go back to the operators.js file and add the following JavaScript code:

// comparison operators

document.write("<h3><font color=\"seagreen\">Comparison operators</font></h3>");

a = 12;

b = 23;

document.write("<p>a = " + a + "</br>" + "b = " + b + "</p>");

document.write("<p> equal to --> a == b --> " + (a == b+ "</p>");

document.write("<p> not equal --> a != b --> " + (a != b+ "</p>");

document.write("<p> equal value and equal type --> a === b --> " + (a === b+ "</p>");

document.write("<p> not equal value or not equal type --> a !== b --> " + (a !== b+ "</p>");  

document.write("<p> greater than --> a > b --> " + (a > b+ "</p>");

document.write("<p> greater than or equal to --> a >= b --> " + (a >= b+ "</p>");

document.write("<p> less than --> a < b --> " + (a < b+ "</p>");

document.write("<p> less than or equal to --> a <= b --> " + (a <= b+ "</p>");

// we will learn this in some of the future tutorial

document.write("<br/>");

document.write("<p>in - is contained within an expression or object</p>");

document.write("<p>instanceof - an instance of an object</p>");

When you start or refresh the lesson3.html webpage you will get additional text on the page.

Comparison operators

a = 12
b = 23

equal to --> a == b --> false

not equal --> a != b --> true

equal value and equal type --> a === b --> false

not equal value or not equal type --> a !== b --> true

greater than --> a > b --> false

greater than or equal to --> a >= b --> false

less than --> a < b --> true

less than or equal to --> a <= b --> true


in - is contained within an expression or object

instanceof - an instance of an object

Logical Operators: The Building Blocks of JavaScript Conditions

Logical operators in the JavaScript programming language are symbols or characters used to perform logical operations on the logical values true or false. These operators are important because they allow programmers to control the flow of program execution based on various logical conditions and expressions. Logical operators are important because they allow programmers to create complex logical expressions and conditions in their programs. These operators are often used in if statements, while loops, for loops, and other control structures to make decisions and manage program execution based on various conditions. Go back to the operators.js file and add the following JavaScript code:

// logical operators

document.write("<h3><font color=\"seagreen\">Logical operators</font></h3>");

a = 47;

b = 81;

document.write("<p>a = " + a + "</br>" + "b = " + b + "</p>");

document.write("<p> and --> (a < 100 && b > 1) --> " + (a < 100 && b > 1+ "</p>");

document.write("<p> or --> (a == 100 or b == 100) --> " + (a == 100 || b == 100+ "</p>");

document.write("<p> not --> !(a === b) --> " + !(a === b+ "</p>");

When you start or refresh the lesson3.html webpage you will get additional text on the page.

Logical operators

a = 47
b = 81

and --> (a < 100 && b > 1) --> true

or --> (a == 100 or b == 100) --> false

not --> !(a === b) --> true

Comma Operator: Sequencing Expressions

The comma operator, in the JavaScript programming language, is an operator used to group and execute multiple statements within a single statement. This operator allows the execution of a sequence of expressions from left to right and returns the value of the last expression in the sequence. Although the comma operator can be useful in certain situations, it should be used with caution, as it can make code more difficult to read and reduce its readability. In most cases, it is clearer to use separate lines of code for each operation or expression, rather than grouping them together using the comma operator. Using the comma operator is usually recommended only when its use is clear and contributes to code readability. Go back to the operators.js file and add the following JavaScript code:

// comma operators

document.write("<h3><font color=\"seagreen\">Comma operators</font></h3>");

let i = 10j = 20k = 30;

document.write("<p>i = " + i + " j = " + j + " k = " + k + "</p>");

When you start or refresh the lesson3.html webpage you will get additional text on the page.

Comma operators

i = 10 j = 20 k = 30

Other operators

As we have already mentioned, we will learn and use other operators when we meet the conditions to apply them in practice. However, for now we can list some of them in our third lesson. Go back to the operators.js file and add the following JavaScript code:

// other operators

document.write("<h3><font color=\"seagreen\">Other operators</font></h3>");

document.write("<p> The Conditional (Ternary) Operator --> ? </p>");

document.write("<p> The Nullish Coalescing Operator --> ?? </p>");

document.write("<p> The Optional Chaining Operator --> ?. </p>");

document.write("<p> The Bitwise Operator --> & | ^ ~ << >> >>> </p>");

document.write("<p> etc. </p><br/><br/><br/>");

When you start or refresh the lesson3.html webpage you will get additional text on the page.

Other operators

The Conditional (Ternary) Operator --> ?

The Nullish Coalescing Operator --> ??

The Optional Chaining Operator --> ?.

The Bitwise Operator --> & | ^ ~ << >> >>>

etc.

The result of Lesson 3. - Using operators in the JavaScript programming language

The result of Lesson 3. - Using operators in the JavaScript programming language  

You can also watch this entire example in the following video.


JavaScript - 3. Operators

Building a Basic Calculator: JavaScript Operations in Action

Creating a simple calculator or digitron in JavaScript is so easy you won't believe it. Modify index.html to look like this:

<header></header>

     <h2 class="bg-primary text-light text-center py-3">Contents</h2>

    <div class="container">

        <div>

            <h2><font color="seagreen">Lessons</font></h2>

            <ul>

                <li><a href="lessons/lesson1.html">

                    Lesson 1. Hello World        

                </a></li>

                <li><a href="lessons/lesson2.html">

                    Lesson 2. Variables and data types        

                </a></li>

                <li><a href="lessons/lesson3.html">

                    Lesson 3. - Using operators in the JavaScript programming language        

                </a></li>

                <li><a href="lessons/lesson4.html">

                    Lesson 4. - Calculator      

                </a></li>

            </ul>

        </div>

    </div>

     <script src="js/includes.js"></script>

<footer></footer>

Create a new directory in the js_tutorial project and name it css. Create a new file in it and name it styles1.css. Type the following CSS settings for our lesson4.html page:

* {

    margin0;

    padding0;

    font-family'Courier New'Couriermonospace;

    box-sizingborder-box;

}

.container {

    width100%;

    height100vh;

    backgroundnavajowhite;

    displayflex;

    align-itemscenter;

    justify-contentcenter;

}

.calculator {

    backgroundorange;

    padding20px;

    border-radius10px;

}

.calculator form input {

    border0;

    outline0;

    width60px;

    height60px;

    border-radius10px;

    box-shadow-8px -8px 15px rgba(2552552550.1), 5px 5px 15px rgba(0000.2);

    backgroundtransparent;

    font-weightbold;

    font-size20px;

    colorbrown;

    cursorpointer;

    margin10px;

}

form .display {

    displayflex;

    justify-contentflex-end;

    margin20px 0;

}

form .display input {

    text-alignright;

    flex1;

    font-size45px;

    box-shadownone;

}

form input.equal {

    width145px;

}

form input.operator {

    coloryellow;

}

Create the lesson4.html page and code the following HTML code.

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Calculator</title>

    <link rel="stylesheet" href="../css/styles1.css">

</head>

<body>

    <div class="container">

        <div class="calculator">

            <form>

                <div class="display">

                    <input type="text" name="display">

                </div>

                <div>

                    <input type="button" value="AC" onclick="display.value = ''" class="operator">

                    <input type="button" value="DE" onclick="display.value = display.value.toString().slice(0-1)" class="operator">

                    <input type="button" value="." onclick="display.value += '.'" class="operator">

                    <input type="button" value="/" onclick="display.value += '/'" class="operator">

                </div>

                <div>

                    <input type="button" value="7" onclick="display.value += '7'">

                    <input type="button" value="8" onclick="display.value += '8'">

                    <input type="button" value="9" onclick="display.value += '9'">

                    <input type="button" value="*" onclick="display.value += '*'" class="operator">

                </div>

                <div>

                    <input type="button" value="4" onclick="display.value += '4'">

                    <input type="button" value="5" onclick="display.value += '5'">

                    <input type="button" value="6" onclick="display.value += '6'">

                    <input type="button" value="-" onclick="display.value += '-'" class="operator">

                </div>

                <div>

                    <input type="button" value="1" onclick="display.value += '1'">

                    <input type="button" value="2" onclick="display.value += '2'">

                    <input type="button" value="3" onclick="display.value += '3'">

                    <input type="button" value="+" onclick="display.value += '+'" class="operator">

                </div>

                <div>

                    <input type="button" value="00" onclick="display.value += '00'">

                    <input type="button" value="0" onclick="display.value += '0'">

                    <input type="button" value="=" onclick="display.value = eval(display.value)" class="equal operator">

                </div>

            </form>

         </div>

    </div>

</body>

</html>

When you start or refresh the website lesson4.html you will get the result as in the picture.

JavaScript Calculator web page

JavaScript Calculator web page

You can also watch this entire example in the following video.


JavaScript - 4. How to make a calculator ?



 


 

 

 

 

 

No comments:

Post a Comment