0% found this document useful (0 votes)
53 views19 pages

Comparison Operators: Operator Description

Uploaded by

Rishabh Jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views19 pages

Comparison Operators: Operator Description

Uploaded by

Rishabh Jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Types of JavaScript Operators

There are different types of JavaScript operators:

 Arithmetic Operators
 Assignment Operators
 Comparison Operators
 String Operators
 Logical Operators
 Bitwise Operators
 Ternary Operators
 Type Operators

Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement

JavaScript Assignment Operators

Assignment operators assign values to JavaScript variables.

Operator Example Same As


= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y

Comparison Operators
Comparison operators are used in logical statements to determine equality or difference
between variables or values.

Given that x = 5, the table below explains the comparison operators:


Operator Description Comparing Returns

== equal to x == 8 FALSE
x == 5 TRUE

x == "5" TRUE

=== equal value and equal type x === 5 TRUE

x === "5" FALSE

!= not equal x != 8 TRUE

!== not equal value or not equal type x !== 5 FALSE

x !== "5" TRUE

x !== 8 TRUE

> greater than x>8 FALSE

< less than x<8 TRUE

>= greater than or equal to x >= 8 FALSE

<= less than or equal to x <= 8 TRUE

JavaScript Logical Operators


Logical operators are used to determine the logic between variables or values.

Given that x = 6 and y = 3, the table below explains the logical operators:

Operator Description Example


&& and (x < 10 && y > 1) is true
|| or (x == 5 || y == 5) is false
! not !(x == y) is true
JavaScript Bitwise Operators
Bit operators work on 32 bits numbers.

Any numeric operand in the operation is converted into a 32 bit number. The result is
converted back to a JavaScript number.

Operator Description Example Same as Result Decimal


& AND 5&1 0101 & 0001 0001 1
| OR 5|1 0101 | 0001 0101 5
~ NOT ~5 ~0101 1010 10
^ XOR 5^1 0101 ^ 0001 0100 4
<< left shift 5 << 1 0101 << 1 1010 10
>> right shift 5 >> 1 0101 >> 1 0010 2
>>> unsigned 5 >>> 1 0101 >>> 1 0010 2
right shift
The examples above uses 4 bits unsigned examples. But JavaScript uses 32-bit signed
numbers.

Because of this, in JavaScript, ~ 5 will not return 10. It will return -6.

~00000000000000000000000000000101 will return


11111111111111111111111111111010

Conditional (Ternary) Operator


JavaScript also contains a conditional operator that assigns a value to a variable based on
some condition.

variablename = (condition) ? value1:value2

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Comparison</h1>
<h2>The () ? : Ternary Operator</h2>
<p>Input your age and click the button:</p>
<input id="age" value="18" />
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
let age = document.getElementById("age").value;
let voteable = (age < 18) ? "Too young":"Old enough";
document.getElementById("demo").innerHTML = voteable + " to vote.";
}
</script>
</body>
</html>

Comparing Different Types


Comparing data of different types may give unexpected results.

When comparing a string with a number, JavaScript will convert the string to a number when
doing the comparison. An empty string converts to 0. A non-numeric string converts
to NaN which is always false.

Case Value
2 < 12 True
2 < "12" True
2 < "John" False
2 > "John" False
2 == "John" False
"2" < "12" False
"2" > "12" True
"2" == "12" False

JavaScript Type Operators


Operator Description
Typeof Returns the type of a variable
Instanceof Returns true if an object is an instance of an object type
In JavaScript there are 5 different data types that can contain values:

 string
 number
 boolean
 object
 function

typeof "John" // Returns "string"


typeof 3.14 // Returns "number"
typeof NaN // Returns "number"
typeof false // Returns "boolean"
typeof [1,2,3,4] // Returns "object"
typeof {name:'John', age:34} // Returns "object"
typeof new Date() // Returns "object"
typeof function () {} // Returns "function"
typeof myCar // Returns "undefined" *
typeof null // Returns "object"

Example : instanceof
<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>
<h2>The instanceof Operator</h2>
<p>The instanceof operator returns true if an object is an instance of a specified object:</p>
<p id="demo"></p>
<script>
const cars = ["Audi", "Volvo", "BMW"];

document.getElementById("demo").innerHTML =
(cars instanceof Array) + "<br>" +
(cars instanceof Object) + "<br>" +
(cars instanceof String) + "<br>" +
(cars instanceof Number);
</script>

</body>
</html>
JavaScript has 8 Datatypes
1. String
2. Number
3. Bigint
4. Boolean
5. Undefined
6. Null
7. Symbol
8. Object

The Object Datatype


The object data type can contain:

1. An object
2. An array
3. A date

// Numbers:
let length = 16;
let weight = 7.5;

// Strings:
let color = "Yellow";
let lastName = "Johnson";

// Booleans
let x = true;
let y = false;

// Object:
const person = {firstName:"John", lastName:"Doe"};

// Array object:
const cars = ["Saab", "Volvo", "BMW"];

// Date object:
const date = new Date("2022-03-25");

let x = BigInt("123456789012345678901234567890");
JavaScript Objects
JavaScript objects are written with curly braces {}.

Object properties are written as name:value pairs, separated by commas.

const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Empty Values
An empty value has nothing to do with undefined.

An empty string has both a legal value and a type.

Example

let car = ""; // The value is "", the typeof is "string"

JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<p>Call a function which performs a calculation and returns the result:</p>
<p id="demo"></p>
<script>
function myFunction(p1, p2) {
return p1 * p2;
}
let result = myFunction(4, 3);
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
Local Variables
Variables declared within a JavaScript function, become LOCAL to the function.

Local variables can only be accessed from within the function.

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<p>Outside myFunction() carName is undefined.</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
let text = "Outside: " + typeof carName;
document.getElementById("demo1").innerHTML = text;

function myFunction() {
let carName = "Volvo";
let text = "Inside: " + typeof carName + " " + carName;
document.getElementById("demo2").innerHTML = text;
}

myFunction();
</script>
</body>
</html>

JavaScript Objects
Real Life Objects, Properties, and Methods
In real life, a car is an object.

A car has properties like weight and color, and methods like start and stop:

All cars have the same properties, but the property values differ from car to car.

All cars have the same methods, but the methods are performed at different
times.
Properties Methods

car.name = Fiat car.start()

car.model = 500 car.drive()

car.weight = 850kg car.brake()

car.color = white car.stop()

All cars have the same properties, but the property values differ from car to car.

All cars have the same methods, but the methods are performed at different times.

JavaScript Objects
You have already learned that JavaScript variables are containers for data values.

This code assigns a simple value (Fiat) to a variable named car:

let car = "Fiat";

Objects are variables too. But objects can contain many values.

This code assigns many values (Fiat, 500, white) to a variable named car:

const car = {type:"Fiat", model:"500", color:"white"};

<script>
// Create an object:
const car = {type:"Fiat", model:"500", color:"white"};

// Display some data from the object:


document.getElementById("demo").innerHTML = "The car type is " + car.type;
</script>

The values are written as name:value pairs (name and value separated by a colon).

It is a common practice to declare objects with the const keyword.


Accessing Object Properties
You can access object properties in two ways:

objectName.propertyName

objectName["propertyName"]

<p id="demo"></p>

<script>
// Create an object:
const person = {
firstName: "John",
lastName : "Doe",
id : 5566
};

// Display some data from the object:


document.getElementById("demo").innerHTML = person.firstName + " " +
person["lastName"];
</script>

JavaScript objects are containers for named values called properties.

Object Methods
Objects can also have methods.

Methods are actions that can be performed on objects.

Methods are stored in properties as function definitions.

A method is a function stored as a property.

const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
In the example above, this refers to the person object.

I.E. this.firstName means the firstName property of this.

I.E. this.firstName means the firstName property of person.

What is this?
In JavaScript, the this keyword refers to an object.

Which object depends on how this is being invoked (used or called).

The this keyword refers to different objects depending on how it is used:

 In an object method, this refers to the object.


 Alone, this refers to the global object.
 In a function, this refers to the global object.
 In a function, in strict mode, this is undefined.
 In an event, this refers to the element that received the event.
 Methods like call(), apply(), and bind() can refer this to any object.

The this Keyword


In a function definition, this refers to the "owner" of the function.

In the example above, this is the person object that "owns" the fullName function.

<!DOCTYPE html>
<html>
<body>
<h1>The JavaScript <i>this</i> Keyword</h1>
<p>In this example, <b>this</b> refers to the <b>person</b> object.</p>
<p>Because <b>fullName</b> is a method of the person object.</p>
<p id="demo"></p>
<script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
// Display data from the object:
document.getElementById("demo").innerHTML = person.fullName();
</script>
</body>
</html>

In other words, this.firstName means the firstName property of this object.

Accessing Object Methods


You access an object method with the following syntax:

objectName.methodName()

If you access a method without the () parentheses, it will return the function definition:

name = person.fullName;

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>
<p>This example calls the fullName method of person, using it on person1:
</p>

<p id="demo"></p>

<script>
const person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person1 = {
firstName:"John",
lastName: "Doe"
}
const person2 = {
firstName:"Mary",
lastName: "Doe"
}
document.getElementById("demo").innerHTML = person.fullName.call(person1);
</script>
</body>
</html>
The call() Method with Arguments
The call() method can accept arguments:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>
<p>This example calls the fullName method of person, using it on person1:
</p>

<p id="demo"></p>

<script>
const person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}

const person1 = {
firstName:"John",
lastName: "Doe"
}

const person2 = {
firstName:"Mary",
lastName: "Doe"
}

document.getElementById("demo").innerHTML = person.fullName.call(person1, "Oslo", "Norway");


</script>

</body>
</html>
JavaScript Function apply()

Method Reuse
With the apply() method, you can write a method that can be used on different objects.

The JavaScript apply() Method


The apply() method is similar to the call() method.

In this example the fullName method of person is applied on person1:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>In this example the fulllName method of person is <b>applied</b> on person1:</p>
<p id="demo"></p>
<script>
const person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person1 = {
firstName:"John",
lastName: "Doe"
}
document.getElementById("demo").innerHTML = person.fullName.apply(person1);
</script>
</body>
</html>

The Difference Between call() and apply()


The difference is:

The call() method takes arguments separately.

The apply() method takes arguments as an array.

The apply() method is very handy if you want to use an array instead of an argument list.
The apply() Method with Arguments
The apply() method accepts arguments in an array:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>
<p>In this example the fulllName method of person is <b>applied</b> on person1:</p>

<p id="demo"></p>

<script>
const person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}

const person1 = {
firstName:"John",
lastName: "Doe"
}

document.getElementById("demo").innerHTML = person.fullName.apply(person1, ["Oslo", "Norway"]);


</script>

</body>
</html>

Simulate a Max Method on Arrays


You can find the largest number (in a list of numbers) using the Math.max() method:

Math.max(1,2,3); // Will return 3

<script>
document.getElementById("demo").innerHTML = Math.max(1,2,3);
</script>

Since JavaScript arrays do not have a max() method, you can apply
the Math.max() method instead.

<script>
document.getElementById("demo").innerHTML = Math.max.apply(null, [1,2,3]);

const c = [1,2,3,4,5];
document.getElementById("demo").innerHTML = Math.max.apply(null,c);

</script>
JavaScript Function bind()
Function Borrowing
With the bind() method, an object can borrow a method from another object.

The example below creates 2 objects (person and member).

The member object borrows the fullname method from the person object:

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Function bind()</h1>

<p>This example creates 2 objects (person and member).</p>


<p>The member object borrows the fullname method from person:</p>

<p id="demo"></p>

<script>
const person = {
firstName:"John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const member = {
firstName:"Hege",
lastName: "Nilsen",
}
let fullName = person.fullName.bind(member);

document.getElementById("demo").innerHTML = fullName();
</script>
</body>
</html>
Preserving this
Sometimes the bind() method has to be used to prevent losing this.

In the following example, the person object has a display method. In the display
method, this refers to the person object:

const person = {
firstName:"John",
lastName: "Doe",
display: function () {
let x = document.getElementById("demo");
x.innerHTML = this.firstName + " " + this.lastName;
}
}

person.display();

When a function is used as a callback, this is lost.

This example will try to display the person name after 3 seconds,
but it will display undefined instead:

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Function bind()</h1>
<p>This example will try to display a person name after 3 seconds.</p>
<p id="demo"></p>
<script>
const person = {
firstName:"John",
lastName: "Doe",
display: function() {
let x = document.getElementById("demo");
x.innerHTML = this.firstName + " " + this.lastName;
}
}
setTimeout(person.display, 3000);
</script>
</body>
</html>
O/P

The bind() method solves this problem.

In the following example, the bind() method is used to bind person.display to person.

This example will display the person name after 3 seconds:

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Function bind()</h1>

<p>This example will display a person name after 3 seconds:</p>

<p id="demo"></p>

<script>
const person = {
firstName:"John",
lastName: "Doe",
display: function() {
let x = document.getElementById("demo");
x.innerHTML = this.firstName + " " + this.lastName;
}
}

let display = person.display.bind(person);


setTimeout(display, 3000);
</script>

</body>
</html>
What is this?
In JavaScript, the this keyword refers to an object.

Which object depends on how this is being invoked (used or called).

The this keyword refers to different objects depending on how it is used:

 In an object method, this refers to the object.


 Alone, this refers to the global object.
 In a function, this refers to the global object.
 In a function, in strict mode, this is undefined.
 In an event, this refers to the element that received the event.
 Methods like call(), apply(), and bind() can refer this to any object.

You might also like