Saturday, March 30, 2024

What are operators in Javascript?

 Javascript operators are used to perform different types of mathematical and logical computations.

Sample example to demontrate addition, substraction, division:

let x = 5;

let y = 2;

let a = x + y;

let b = x - y;

let c = x / y;

console.log(a);

console.log(b);

console.log(c);

Output:

7

3

2.5

JavaScript Assignment Operators:

The Addition Assignment Operator (+=) adds a value to a variable. Similarly, you can use the other operators as shown below.

let x = 10;

x += 5;

console.log(x);

Output:

15

The += assignment operator can also be used to add (concatenate) strings:

let text1 = "My Name is ";

text1 += "Farukh";

console.log(text1);

Output:

My Name is Farukh

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

JavaScript Comparison Operators:

Operator Description

== equal to

=== equal value and equal type

!= not equal

!== not equal value or not equal type

> greater than

< less than

>= greater than or equal to

<= less than or equal to

? ternary operator

Logical Operators:

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

let x = 6;

let y = 3;

let a = 6;

let b = 6;

if((x < 10 && y > 1))

{

  console.log('Yes satisfied');

}

if((x < 10 || y > 1))

{

  console.log('Yes satisfied');

}

if(!(a == b))

{

    console.log('Yes satisfied');

}

else{

  console.log('Not satisfied');

}

Output:

Yes satisfied

Yes satisfied

Not satisfied

What is the difference between == and === operator?

The == operator compares the values of two variables after performing type conversion if necessary. On the other hand, the === operator compares the values of two variables without performing type conversion.

const num = 1;

const str = "1";

console.log(num == str); 

console.log(num === str); 

Output:

true

false

Conditional (Ternary) Operator:

let name="Test"

let printValue = (name == "Test") ? "Yes":"No";

console.log(printValue);

Output:

Yes

No comments:

Post a Comment