Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
144 views

JavaScript Operators and Expressions

The document discusses various JavaScript operators and expressions. It describes operators like arithmetic, assignment, relational, logical, and string operators. It also covers increment and decrement operators. Examples are provided to demonstrate how to use each operator type to evaluate expressions and perform operations on operands.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
144 views

JavaScript Operators and Expressions

The document discusses various JavaScript operators and expressions. It describes operators like arithmetic, assignment, relational, logical, and string operators. It also covers increment and decrement operators. Examples are provided to demonstrate how to use each operator type to evaluate expressions and perform operations on operands.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

JavaScript Operators and Expressions

(Salinan dari http://www.brainkart.com/article/JavaScript-Operators-and-Expressions_36761/)


An operator combines the values of its operands in some way and evaluates to a new value.

JavaScript Operators and Expressions


 

An operator combines the values of its operands in some way and evaluates to a
new value. Operators are used for JavaScript’s arithmetic expressions,
comparison expressions, logical expressions, assignment expressions.

An expression is a phrase of JavaScript that a JavaScript interpreter can


evaluate to produce a value. The data types are used directly as literals or within
variables in combination with simple operators, such as addition, subtraction,
and so on, to create an expressions. An expression is a code fragment that can
be evaluated to some data type the language supports. An expression is simply
one or more variables and/or constants joined by operators. An expression is
evaluated and produces a result. The result of all expressions may be either an
integer or floating-point value or Boolean value. There are three types of
expressions as follows,

•         Arithmetic expressions

•         Relational expressions

•         Logical expressions

Arithmetic Operators
 

JavaScript supports all the basic arithmetic operators like addition (+),
subtraction (–), multiplication (*), division (/), and modulus (%, also known as
the remainder operator).

Table: 14.1 – Arithmetic Operators


 

Illustration 14.3 Using Arithmetic Operators

<Html>

<Head>

        <Title>Demo Program – To test Arithmetic Operators in JavaScript


</Title>

</Head>

<Body>

<script language="javascript" type="text/javascript">

        var value1 = 522, value2=10;

        document.write("<br>Data1 : "+value1);

        document.write("<br>Data2 : "+value2);

        var sum = value1+value2;

        var diff = value1-value2;

        var prod = value1*value2;

        var res = value1/value2;

        var rem = value1%value2;


        document.write("<br><br>The Sum of Data1 and Data2 : "+sum);

        document.write("<br>The Difference of Data1 and Data2 : "+diff);

        document.write("<br>The Product of Data1 and Data2 : "+prod);

        document.write("<br>The Result after Division of Data1 and Data2 :


"+res);

        document.write("<br>The Remainder after Division of Data1 and


Data2 :"+rem);

</script>

</Body>

</Html>

Output:

Assignment Operator
 
An assignment operator is the operator used to assign a new value to a variable.
Assignment operator can also be used for logical operations such as bitwise
logical operations or operations on integral operands and Boolean operands.

In JavaScript = is an assignment operator, which is used to assign a value to a


variable. Often this operator is used to set a variable to a literal value, for
example,

var number1=10;

var number2=number1;

var name=”Computer Science”;

var booleanvar=true;

The assignment operator is used to assign a value to a single variable, but it is


possible to perform multiple assignments at once by stringing them together
with the = operator. For example, the statement

var m = n = z = 25; // sets all three variables to a value of 25//

The assignment operator can also be used to set a variable to hold the value of
an expression. For example,

var x = 102 + 5 - 50; // x set to 57 //

JavaScript supports some shorthand arithmetic operators like +=, -=, *=, /= and
%= to evaluate arithmetic calculations.

Table: 14.2 Shorthand Arithmetic operators


 

Illustration 14.4 Using Arithmetic Shorthand Operators

<Html>

<Html>

<Head>

        <Title>Demo Program - To test Arithmetic Shorthand Operators in


JavaScript

</Title>

</Head>

<Body>

        <script language="javascript" type="text/javascript">

        var value1 = 522, value2=10;

        document.write("<br>Data1 : "+value1);

        document.write("<br>Data2 : "+value2);


        var sum = value1; sum+=value2;

        var diff = value1; diff-=value2;

        var prod = value1; prod*=value2;

        var res = value1; res/=value2;

        var rem = value1; rem%=value2;

        document.write("<br><br>The Sum of Data1 and Data2 Using += :


"+sum);

        document.write("<br>The Difference of Data1 and Data2 Using -= :


"+diff);

        document.write("<br>The Product of Data1 and Data2 Using *= :


"+prod);

        document.write("<br>The Result after Division of Data1 and Data2


using /= : "+res);

        document.write("<br>The Remainder after Division of Data1 and


Data2 Using %= : "+rem);

        </script>

</Body>

</Html>

Output:
Assignment:

Develop JavaScript code for the following:

1.   To find Simple Interest for the given Principle, Number of years and Rate of
interest.

2.   To find Compund Interest for the given Principle, Number of years and Rate
of interest.

3.   To find difference between Simple Interest and Compound Interst.

Relational or Comparison Operators:


 

Relational operators are also called as Comparison operators, they compares


two values and the result is true or false. JavaScript provides a rich set of
relational operators including == (equal to), != (not equal to), < (less than), >
(greater than), <= (less than or equal to), and >= (greater than or equal to).
Using a relational operator in an expression causes the expression to evaluate as
true if the condition holds or false if otherwise.
Table: 14.3 Relational or Comparison operators

Illustration 14.5 Using Relational Operators

<Html>

<Head>

        <Title>Demo Program - To test Relational(Comparison) Operators in


JavaScript </Title>

</Head>

<Body>

<script language="javascript" type="text/javascript">

var value1 = 522, value2=10;

document.write("<br>Data1 : "+value1);

document.write("<br>Data2 : "+value2);

document.write("<br><br>Whether Data1 = Data2 : "+(value1==value2));

document.write("<br>Whether Data1 < Data2 : "+(value1<value2));

document.write("<br>Whether Data1 > Data2 : "+(value1>value2));


document.write("<br>Whether Data1 <= Data2 : "+(value1<=value2));

document.write("<br>Whether Data1 >= Data2 : "+(value1>=value2));

document.write("<br>Whether Data1 != Data2 : "+(value1!=value2));

</script>

</Body>

</Html>

Output:

Logical Operators:
 

Logical operators perform logical (boolean) operations. Logical operators


combine or invert boolean values. Once comparisons are made, the logical
operators && (AND), || (OR) and ! (NOT) can be used to create more complex
conditions.

Table: 14.4 Logical or Boolean operators


 

Usage :

Best practice is to use logical operators on boolean operands. However,


operands of any type can be combined. The strict rules are as follows:

•         For && (AND) the result is false if the first operand is false; otherwise, the
result is the Boolean value of the second operand.

•         For || (OR) the result is true if the first operand is true; otherwise, the result
is the Boolean value of the second operand.

•         For ! (NOT) the result is true if the operand is false; otherwise, the result is
true.

Illustration 14.6 Using Logical Operators

<Html>

<Head>

        <Title>Demo Program - To test Logical Operators in JavaScript </Title>

</Head>

<Body>
<script language="javascript" type="text/javascript">

var value1 = 522, value2=10;

document.write("<br>Data1 : "+value1);

document.write("<br>Data2 : "+value2);

var res1=((value1>100) && (value1>601));

var res2=((value1>100) || (value1>601));

var res3=(!(value1!=value2));

document.write("<br><br>Whether Data1>100 AND Data1>601 : "+res1);

document.write("<br><br>Whether Data1>600 OR Data1>601 : "+res2);

document.write("<br>Whether !Data1 != Data2 : "+res3);

</script>

</Body>

</Html>

Output:

 
String Operators:
 

One of the built-in features of JavaScript is the ability to concatenate strings.


The + operator performs addition on numbers but also serves as the
concatenation operator for strings. Because string concatenation has precedence
over numeric addition, + will be interpreted as string concatenation if any of the
operands are strings. + operator which is also called as the string concatenation
operator. For example:

Illustration 14.7 Using + Operator for concatenating String

<Html>

<Head>

        <Title>Demo Program - To Concatenating (+) Operators in JavaScript


</Title>

</Head>

<Body>

        <script language="javascript" type="text/javascript">

        var String1 = "Java";

        var String2 = "Script";

        var String3=String1+String2;

        document.write("<br>String1 : "+String1);

        document.write("<br>String2 : "+String2);

        document.write("<br><br>Concatenated String of String1 and String2 :


"+String3);

        </script>

</Body>

</Html>
Output:

Increment and Decrement Operators:


 

The ++ operator increments its single operand. The operator converts its
operand to a number, adds 1 to that number, and assigns the incremented value
back into the variable. The return value of the ++ operator depends on its
position relative to the operand. When ++ is used before the operand, where it is
known as the pre-increment operator, it increments the operand and evaluates to
the incremented value of that operand. When used after the operand, where it is
known as the post-increment operator, it increments its operand but evaluates to
the un-incremented value of that operand. Consider the difference between
these two lines of code:

var m = 1, n = ++m; // m and n are both 2

var m = 1, n = m++; // m is 2, n is 1

The -- operator decrements its single operand. It converts the value of the
operand to a number, subtracts 1, and assigns the decremented value back to the
operand. Like the ++ operator, the return value of -- depends on its position
relative to the operand. When used before the operand, it decrements and
returns the decremented value. When used after the operand, it decrements the
operand but returns the undecremented value.

var m = 2, n = --m; // m and n are both 1


var m = 2, n = m--; // n is 2, n is 1

Illustration 14.8 Using ++ and -- Operator – both Prefix and Suffix

<Html>

<Head>

        <Title>Demo Program - ++ and -- Operators in JavaScript </Title>

</Head>

<Body>

<script language="javascript" type="text/javascript">

var number1 = 150;

var number2 = number1++;

document.write("<br><h4>Post Increment - number++</h4>");

document.write("Number1 = "+number1+" Number2 = "+number2);

document.write("<br><h4>Pre Increment - ++number</h4>"); var number1 =


150;

var number2 = ++number1;

document.write("Number1 = "+number1+" Number2 = "+number2);

var number1 = 150;

var number2 = number1--;

document.write("<br><h4>Post Decrement - number--</h4>");

document.write("Number1 = "+number1+" Number2 = "+number2);

document.write("<br><h4>Pre Decrement - --number</h4>");

 var number1 = 150;

var number2 = --number1;

document.write("Number1 = "+number1+" Number2 = "+number2);


</script>

</Body>

</Html>

Output:

Unary + and - Operator:


 

 + has no effect on numbers but causes non-numbers to be converted into


numbers

– Negation (changes the sign of the number or converts the expression to a


number and then changes its sign)

 
typeof Operator:
The typeof operator is used to get the data type (returns a string) of its operand.
The operand can be either a literal or a data structure such as a variable, a
function, or an object. The operator returns the data type.

Syntax

typeof operand

or

typeof(operand)

typeof returns: boolean, function, number, string, and undefined. The following
table summarizes possible values returned by the typeof operator.

Illustration 14.9 typeof operator

<Html>

<Head>

        <Title>Demo Program - To test typeof Operator in JavaScript </Title>

</Head>

<Body>
<script language="javascript" type="text/javascript">

var value1 = 522, value2="JavaSript";

value3=true;

document.write("<br>Value1 ="+value1+" and its data Type is :


"+typeof(value1));

document.write ("<br>Value2 ="+value2+" and its data Type is :


"+typeof(value2));

document.write ("<br>Value3 ="+value3+" and its data Type is :


"+typeof(value3));

</script>

</Body>

</Html>

Output:

Conditional Operator (?:)


 

The ?: is the conditional operator in JavaScript, which requires three operands,


hence it is called the ternary operator. The syntax is

var variablename=(condition) ? value1 : value2;


In the syntax condition may be relational expression or logical expression. First
condition will be evaluated, if the condition returns true then the value of the
left side of the colon is assigned to the variable otherwise the value of the right
side of the colon will be assigned the variable. For example,

var result=(10>15) ?100 :150;

In the above example, since the condition returns false the value 150 will be
assigned to result.

Illustration 14.10 Condtional Operator

<Html>

<Head>

        <Title>Demo Program - To test Conditional Operator in JavaScript


</Title>

</Head>

<Body>

        <script language="javascript" type="text/javascript">

        var value1 = 522, value2=150, value3;

        value3=(value1<value2) ? value1: value2;

        document.write("<br>The Value of Data1 = "+value3);

        </script>

</Body>

</Html>

Output:
 

A Comprehensive Look at JavaScript


Comparison Operators
Sumber : https://www.javascripttutorial.net/javascript-comparison-operators/

Summary: in this tutorial, you will learn how to use JavaScript comparison
operators to compare two values.

Introduction to JavaScript comparison operators


To compare two values, you use the comparison operators. The following table
illustrates the JavaScript comparison operators:

Operator Meaning
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equal to
!= not equal to
A comparison operator returns a Boolean value indicating that the comparison is
true or not. See the following example:
let r1 = 20 > 10; // true
let r2 = 20 < 10; // false
let r3 = 10 == 10; // true
The comparison operator takes at least two values (or operands). If one of the two
values has a different type, JavaScript will perform a conversion based on specific
rules before comparing them. We will discuss each rule in detail in the following
sections.

Comparing numbers

If the operands are numbers, JavaScript will perform a numeric comparison. For
example:

let a = 10,
b = 20;
console.log(a >= b); // false
console.log(a == 10); // true
This example is straightforward. the variable a is 10, b is 20.  The a>=b expression
returns and a==10 expression returns  true.

Comparing strings

If the operands are strings, JavaScript compares the character codes numerically
one by one in the string.

let name1 = 'alice',


name2 = 'bob';
let result = name1 < name2;
console.log(result); // true
console.log(name1 == 'alice'); // true
Because JavaScript compares character codes in the strings numerically, you may
receive an unexpected result, for example:

let f1 = 'apple',
f2 = 'Banana';
let result = f2 < f1;
console.log(result); // true
In this example, f2 is less than f1 because the letter B has the character code 66 while
the letter a has the character code 97.
To fix this, you must first convert strings into a common format, either lowercase
or uppercase and then perform comparison as follows:

let result2 = f2.toLowerCase() < f1.toLowerCase();


console.log(result2); // false
Note that the toLowerCase() is a method of the String object that converts the string
itself to lowercase.

Comparing a number with a value of another type

If an operand is a number while the other is not, JavaScript converts the non-
numeric operand to a number and performs comparison numerically.

console.log(10 < '20'); // true


In this example, the string '20'is converted to 20 and compared with the number 10.
Here is an example:
console.log(10 == '10'); // true
In this example, JavaScript converts the string '10' to the number 10 and
compares the result with the number 10 that results in true.

Comparing an object with a non-object

If an operand is an object, JavaScript calls the valueOf() method of that object to get


the value for comparison. If the object doesn’t have the valueOf() method, JavaScript
then calls the toString() method and uses the returned value for comparison. See the
following example:
let apple = {
valueOf: function() {
return 10;
}
};

let orange = {
toString: function() {
return '20';
}
};
console.log(apple > 10); // false
console.log(orange == 20); // true
In this first comparison, the apple object has the valueOf() method that returns 10,
therefore, JavaScript uses 10 for comparison. In the second comparison, JavaScript
first calls the valueOf() method. However, the orange object doesn’t have
the valueOf() method so JavaScript calls the toString() method to get the returned value
of 20.

Comparing a Boolean with another value

If an operand is a Boolean, JavaScript converts it to a number and compares the


converted value with the other operand; true will convert to 1 and false will convert
to 0.
console.log(true > 0); // true
console.log(false < 1); // true
console.log(true > false); // true
console.log(false > true); // false
console.log(true >= true); // true
console.log(true <= true); // true
console.log(false <= false); // true
console.log(false >= false); // true
In addition to the above rules, the equal ( ==) and not-equal(!=) operators also have
the following rules.

Comparing null and undefined

In JavaScript, null equals undefined. It means that the following expression returns true.


console.log(null == undefined); // true

Comparing NaN with other values

If either operand is NaN, then the equal operator(==) returns false.


console.log(NaN == 1); // false
Even

console.log(NaN == NaN); // false


The not-equal (!=) operator returns true when comparing the NaN with another value:
console.log(NaN != 1); // true
And also

console.log(NaN != NaN); // true

Strict equal (===) and not strict equal (!==)


Besides the comparison operators above, JavaScript provides the strict equal ( ===)
and not strict equal  ( !==) operators.
Operator Meaning
=== strict equal
!== not strict equal
The strict equal and not strict equal operators behave like the equal and not equal
operator except that they don’t convert the operand before comparison. See the
following example:

console.log("10" == 10); // true


console.log("10" === 10); // false
In the first comparison, since we use the equality operator, JavaScript converts the
string into the number and performs the comparison.

However, in the second comparison, we use the strict equal operator ( ===),
JavaScript doesn’t convert the string before comparison, therefore the result is false.
In this tutorial, you have learned how to use the JavaScript comparison operators to
compare values.

You might also like