JavaScript operator

 JavaScript Operators




Operators

A few data types and some ways to convert them, it is time for the next major building block: operators. These come in handy whenever we want to work with the variables, modify them, perform calculations on them, and compare them. They are called operators because we use them to operate on our variables.


    Arithmetic operators

    Arithmetic operators can be used to perform operations with numbers. Most of these operations will feel very natural to you because they are the basic mathematics you will have come across earlier in life already.


    1.Addition

    Addition in JavaScript is very simple, we have seen it already. We use + operator for this 

    operation:

    let nr1 = 12;

    let nr2 = 14;

    let result1 = nr1 + nr2;


    However, this operator can also come in very handy for concatenating strings.

     Note 

    the added space after "Hello" to ensure the end result contains space characters:

    let str1 = "Hello ";

    let str2 = "addition";

    let result2 = str1 + str2;


    The output of printing result1 and result2 will be as follows:


    Hello addition


    As you can see, adding numbers and strings lead to different results. If we add twodifferent strings, it will concatenate them into a single string.


    2.Subtraction


    Subtraction works as we would expect it as well. We use - for this operation. 


    let nr1 = 20;

    let nr2 = 4;

    let str1 = "Hi";

    let nr3 = 3;

    let result1 = nr1 - nr2;

    let result2 = str1 - nr3;

    console.log(result1, result2);


    The output is as follows:

    16 NaN

    The first result is 16. And the second result is more interesting. It gives NaN, not an error, but just simply the conclusion that a word and a number subtracted is not a number. Thanks for not crashing, JavaScript!


    3. Multiplication


    We can multiply two numeric values with the * character. Unlike some other languages, we cannot successfully multiply a number and a string in JavaScript.

    The result of multiplying a numeric and a non-numeric value is NaN:

    let nr1 = 15;

    let nr2 = 10;

    let str1 = "Hi";

    let nr3 = 3;

    let result1 = nr1 * nr2;

    let result2 = str1 * nr3;

    console.log(result1, result2);

    Output:

    150 NaN


    4.Division

    Another straightforward operator is division. We can divide two numbers with the /

    character:

    let nr1 = 30;

    let nr2 = 5;

    let result1 = nr1 / nr2;

    console.log(result1);


    The output is as follows:

    6


    Exponentiation

    Exponentiation means raising a certain base number to the power of the exponent,

    for example, xy

    . This can be read as x to the power of y. It means that we will

    multiply x by itself y number of times. Here is an example of how to do this in

    JavaScript—we use ** for this operator:

    let nr1 = 2;

    let nr2 = 3;

    let result1 = nr1 ** nr2;

    console.log(result1);


    We get the following output:

    8

    The result of this operation is 2 to the power of 3 (2 * 2 * 2), which is 8. We're going to avoid going into a mathematics lesson here, but we can also find the root of anumber by using fractional exponents: for example, the square root of a value is

    the same as raising it to the power of 0.5.


    Modulus

    This is one that often requires a little explanation. Modulus is the operation in which you determine how much is left after dividing a number by another number in its

    entirety. The amount of times the number can fit in the other number does not matter for this operation is the % character. 

    Here are some examples:

    let nr1 = 10;

    let nr2 = 3;

    let result1 = nr1 % nr2;

    console.log(`${nr1} % ${nr2} = ${result1}`);

    let nr3 = 8;

    let nr4 = 2;

    let result2 = nr3 % nr4;

    console.log(`${nr3} % ${nr4} = ${result2}`);

    let nr5 = 15;

    let nr6 = 4;

    let result3 = nr5 % nr6;

    console.log(`${nr5} % ${nr6} = ${result3}`);

    And the output:

    10 % 3 = 1

    8 % 2 = 0

    15 % 4 = 3

    The first one is 10 % 3, where 3 fits 3 times into 10, and then 1 is left. The second one

    is 8 % 2. This results in 0, because 2 can fit 4 times into 8 without having anything

    left. The last one is 15 % 4, where 4 fits 3 times into 15. And then we have 3 left as

    a result.


    operands


    Operands are subject to the operator. So, if we say x + y, x and y are

    .

    1.unary operators. 

    If we see x++, we can read this as x = x + 1. The same is true for the

    decrement operators: x-- can be read as x = x – 1:

    let nr1 = 4;

    nr1++;

    console.log(nr1);

    let nr2 = 4;

    nr2--;

    console.log(nr2);

    The output is as follows:

    5

    3



    2.Prefix and postfix operators

    We can have the increment operator after the operand (x++), in which case we call this the postfix unary operator. We can also have it before (++x), which is the prefix unary operator. This does something different though—the next few lines might be complicated, so do not worry if you need to read it a few times and have a good look

    It has been updated for the second log statement:


    let nr = 2;

    console.log(nr++);

    console.log(nr);


    The output is as follows:

    2

    3


    The prefix gets executed before sending the variable through, and often this is the one  you will need. Have a look at the following example:


    let nr = 2;

    console.log(++nr);

    We get the following output:

    3

    Alright, if you can figure out what the next code snippets logs to the console, you 

    should really have a handle on it:

    let nr1 = 4;

    let nr2 = 5;

    let nr3 = 2;

    console.log(nr1++ + ++nr2 * nr3++);

    It outputs 16. 


    It will do the multiplication first, according to the basic mathematical 

    order of operations. For multiplying, it uses 6 (prefix, so 5 is incremented before 

    multiplying) and 2 (postfix, so 2 is only incremented after execution, meaning it 

    won't affect our current calculation). This comes down to 12. And then nr1 is a 

    postfix operator, so this one will execute after the addition. Therefore, it will add 12 

    to 4 and become 16.

    Combining the operators

    These operators can be combined, and it works just as it does in math. They get 

    executed in a certain order, and not necessarily from left to right. This is due to a 

    phenomenon called operator precedence.


    There is one more thing to take into account here, and that is grouping. You can

    group using ( and ). The operations between the parentheses have the highest

    precedence. After that, the order of the operations takes place based on the type of

    operation (highest precedence first) and if they are of equal precedence, they take

    place from left to right:

    Name Symbol Example

    1.Grouping (...) (x + y)

    2.Exponentiation ** x ** y

    3.Prefix increment and decrement --, ++ --x, ++y

    4.Multiplication, division, modulus *, /, % x * y, x / y, x % y

    5.Addition and subtraction +, - x + y, x - y


    Write some code to calculate the hypotenuse of a triangle using the Pythagorean

    theorem when given the values of the other two sides. The theorem specifies that the

    relation between the sides of a right-angled triangle is a2

     + b2

     = c2

    .

    You can use prompt() to get the value for a and b. Write code to get the value from

    the user for a and b. Then square the values of both a and b before adding them

    together and finding the square root. Print your answer to the console.

    Assignment operators

    We have seen one assignment operator already when we were assigning values to

    variables. The character for this basic assignment operation is =. There are a few

    others available. Every binary arithmetic operator has a corresponding assignment

    operator to write a shorter piece of code. For example, x += 5 means x = x + 5, and

    x **= 3 means x = x ** 3 (x to the power of 3).

    The Pythagorean theorem only applies to right-angled triangles.

    The sides connected to the 90-degree angle are called the adjacent

    and opposite sides, represented by a and b in the formula. The

    longest side, not connected to the 90-degree angle, is called the

    hypotenuse, represented by c.



    In this first example we declare a variable x, and set it to 2 as an initial value:

    let x = 2;

    x += 2;

    After this assignment operation, the value of x becomes 4, because x += 2 is the same

    as x = x + 2:

    In the next assignment operation, we will subtract 2:

    x -= 2;

    So, after this operation the value of x becomes 2 again (x = x – 2). In the next

    operation, we are going to multiply the value by 6:

    x *= 6;

    When this line has been executed, the value of x is no longer 2, but becomes

    12 (x = x * 6). In the next line, we are going to use an assignment operator to perform

    a division:

    x /= 3;


    After dividing x by 3, the new value becomes 4. The next assignment operator we

    will use is exponentiation:

    x **= 2;

    The value of x becomes 16, because the old value was 4, and 4 to the power of 2

    equals 16 (4 * 4). The last assignment operator we will talk about is the modulus

    assignment operator:

    x %= 3;

    After this assignment operation, the value of x is 1, because 3 can fit 5 times into 16

    and then leaves 1.


    Create variables for three numbers: a, b, and c. Update these variables with the

    following actions using the assignment operators:

    • Add b to a

    • Divide a by c

    • Replace the value of c with the modulus of c and b

    • Print all three numbers to the console


    Comparison operators

    Comparison operators are different from the operators we have seen so far. The

    outcome of the comparison operators is always a Boolean, true, or false.

    1.Equal

    There are a few equality operators that determine whether two values are equal.

    They come in two flavors: equal value only, or equal value and data type. The first

    one returns true when the values are equal, even though the type is different, while

    the second returns true only when the value and the type are the same:

    let x = 5;

    let y = "5";

    console.log(x == y);

    The double equals operator, two equal signs, means that it will only check for equal

    value and not for data type. Both have the value 5, so it will log true to the console.

    This type of equality is sometimes called loose equality.

    The triple equals operator, written as three equal signs, means that it will evaluate

    both the value and the data type to determine whether both sides are equal or not.

    They both need to be equal in order for this statement to be true, but they are not

    and therefore the following statement outputs false:

    console.log(x === y);

    This is sometimes also called strict equality. This triple equals operator is the one

    you should most commonly be using when you need to check for equality, as only

    with this one can you be sure that both variables are really equal.

    2.Not equal

    Not equal is very similar to equal, except it does the opposite—it returns true when

    two variables are not equal, and false when they are equal. We use the exclamation

    mark for not equal:

    let x = 5;

    let y = "5";

    console.log(x != y);


    This will log false to the console. If you are wondering what is going on here, take 

    a look again at the double and triple equals operators, because it is the same here. 

    However, when there is only one equals sign in a not-equal operator, it is comparing 

    loosely for non-equality. Therefore, it concludes that they are equal and therefore not 

    equal should result in false. The one with two equals signs is checking for strict non-

    3.equality:

    console.log(x !== y);

    This will conclude that since x and y have different data types, they are not the 

    same, and will log true to the console.

    Greater than and smaller than

    The greater than operator returns true if the left-hand side is greater than the right-

    hand side of the operation. We use the > character for this. We also have a greater 

    than or equal to operator, >=, which returns true if the left-hand side is greater than 

    or equal to the right-hand side. 

    let x = 5;

    let y = 6;

    console.log(y > x); 

    This one will log true, because y is greater than x.

    console.log(x > y);

    Since x is not greater than y, this one will log false.

    console.log(y > y);

    y is not greater than y, so this one will log false.

    console.log(y >= y);

    This last one is looking at whether y is greater than or equal to y, and since it is equal 

    to itself, it will log true.

    It might not surprise you that we also have smaller than (<) and smaller than or equal 

    to operators (<=). Let's have a look at the smaller than operator, as it is very similar to 

    the previous ones.

    console.log(y < x);

    This first one will be false, since y is not smaller than x.

    console.log(x < y);

    So, this second one will log true, because x is smaller than y.

    console.log(y < y);

    y is not smaller than y, so this one will log false.

    console.log(y <= y);

    This last one looks at whether y is smaller than or equal to y. It is equal to y, so it will

    log true.


    Logical operators

    Whenever you want to check two conditions in one, or you need to negate a

    condition, the logical operators come in handy. You can use and, or, and not.

    1.And

    The first one we will have a look at is and. If you want to check whether x is greater

    than y and y is greater than z, you would need to be able to combine two expressions.

    This can be done with the && operator. It will only return true if both expressions are

    true:

    let x = 1;

    let y = 2;

    let z = 3;

    With these variables in mind, we are going to have a look at the logical operators:

    console.log(x < y && y < z);

    This will log true, you can read it like this: if x is smaller than y and y is smaller

    than z, it will log true. That is the case, so it will log true. The next example will log

    false:

    console.log(x > y && y < z);

    Since x is not greater than y, one part of the expression is not true, and therefore

    it will result in false.


    2.Or

    If you want to get true if either one of the expressions is true, you use or. The

    operator for this is ||. These pipes are used to see if either one of these two is true,

    in which case the whole expression evaluates to true. Let's have a look at the or

    operator in action:

    console.log(x > y || y < z);

    This will result in true, whereas it was false with &&. This is because only one of

    the two sides needs to be true in order for the whole expression to evaluate to true.

    This is the case because y is smaller than z.

    When both sides are false, it will log false, which is the case in the next example:

    console.log(x > y || y > z);


    3.Not

    In some cases you will have to negate a Boolean. This will make it the opposite value.

    It can be done with the exclamation mark, which reads as not:

    let x = false;

    console.log(!x);

    This will log true, since it will simply flip the value of the Boolean. You can also

    negate an expression that evaluates to a Boolean, but you would have to make sure

    that the expression gets evaluated first by grouping it.

    let x = 1;

    let y = 2;

    console.log(!(x < y));

    x is smaller than y, so the expression evaluates to true. But, it gets negated due to the

    exclamation mark and prints false to the console.


    Miles-to-kilometers converter

    Create a variable that contains a value in miles, convert it to kilometers, and log the

    value in kilometers in the following format:

    The distance of 130 kms is equal to 209.2142 miles


    For reference, 1 mile equals 1.60934 kilometers.


    BMI calculator


    Set values for height in inches and weight in pounds, then convert the values to

    centimeters and kilos, outputting the results to the console:

    • 1 inch is equal to 2.54 cm

    • 2.2046 pounds is equal to 1 kilo

    Output the results. Then, calculate and log the BMI: this is equal to weight (in kilos)

    divided by squared height (in meters). Output the results to the console.




    Post a Comment

    0 Comments