JavaScript Course 2: Operators

From WikiMLT
Revision as of 09:20, 18 June 2022 by Spas (talk | contribs) (Стадий: 6 [Фаза:Утвърждаване, Статус:Утвърден]; Категория:JavaScript)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Ref­er­ences

Op­er­a­tors in JavaScript

The dif­fer­ent kinds of op­er­a­tors in JavaScript are as fol­low:

  • Arith­metic op­er­a­tors
  • As­sign­ment op­er­a­tors
  • Com­par­i­son op­er­a­tors
  • Ternary (con­di­tion­al) op­er­a­tors
  • Log­i­cal op­er­a­tors
  • Bit­wise op­er­a­tors

Ex­pres­sion in JavaScript is some­thing that pro­duces a val­ue, for ex­am­ple x + y is an ex­pres­sion.

let x = 10;
let y = 3;
console.log(x ** y);  // Exponetiation: 'x' to the power of 'y'
1000

Arith­metic op­er­a­tors

Arith­metic op­er­a­tors are used for per­form­ing cal­cu­la­tions just like we per­form­ing cal­cu­la­tions in math­e­mat­ics. The Arith­metic op­er­a­tors are:

  • + Ad­di­tion op­er­a­tor
  • Sub­trac­tion op­er­a­tor
  • * Mul­ti­pli­ca­tion op­er­a­tor
  • / Di­vi­sion op­er­a­tor
  • % Re­main­der of di­vi­sion op­er­a­tor (mod­u­lus)
  • ** Ex­po­nen­ti­a­tion op­er­a­tor
  • ++ In­cre­ment op­er­a­tor
  • -- Decre­ment op­er­a­tor
console.log(x + y);   // 13
console.log(x - y);   // 7
console.log(x * y);   // 30
console.log(x / y);   // 3.3333333333333335
console.log(x % y);   // 1
console.log(x ** y);  // 1000
console.log(++x);     // 11   (the value is incremented by 1 before the expression evaluation)
console.log(x++);     // 10   (the value is incremented by 1 after the expression evaluation)
console.log(--x);     // 9    (the value is decremented by 1 before the expression evaluation)
console.log(x--);     // 10   (the value is decremented by 1 after the expression evaluation)

As­sign­ment op­er­a­tors

As­sign­ment op­er­a­tors are used to as­sign a val­ue to a vari­able. As­sign­ment op­er­a­tors are:

  • = Sim­ple as­sign­ment op­er­a­tor
  • += Ad­di­tion as­sign­ment op­er­a­tor
  • −= Sub­trac­tion as­sign­ment op­er­a­tor
  • *= Mul­ti­pli­ca­tion as­sign­ment op­er­a­tor
  • /= Di­vi­sion as­sign­ment op­er­a­tor
  • %= Re­main­der of di­vi­sion as­sign­ment op­er­a­tor
  • **= Ex­po­nen­ti­a­tion as­sign­ment op­er­a­tor
  • ++  In­cre­ment op­er­a­tor al­so as­sign a new val­ue to the vari­able
  • --  Decre­ment op­er­a­tor al­so as­sign a new val­ue to the vari­able
x++;        // is equal to
x = x + 1;  // is equal to
x += 1;
x = 10;   console.log(x);  // 10
x += 10;  console.log(x);  // 20
x -= 10;  console.log(x);  // 10
x *= 10;  console.log(x);  // 100
x /= 10;  console.log(x);  // 10
x **= 3;  console.log(x);  // 1000
x %= 3;   console.log(x);  // 1

Com­par­i­son op­er­a­tors

Com­par­i­son op­er­a­tors are used to com­pare the val­ue of a vari­able with some­thing else and re­turn a Boolean true/false . Com­par­i­son op­er­a­tors are:

Re­la­tion­al op­er­a­tors

  • > Is greater than?
  • >= Is greater than or equal to?
  • < Is less than?
  • <= Is less than or equal to?
x = 1;
console.log(x > 0 );   // true
console.log(x >= 1);   // true
console.log(x < 1 );   // false
console.log(x <= 1);   // true

Equal­i­ty op­er­a­tors

  • === Is equal to? (strict equal­i­ty op­er­a­tor: com­pare the Val­ue and the Type of the vari­able)
  • !== Is not equal to? (strict not equal­i­ty op­er­a­tor: com­pare the Val­ue and the Type of the vari­able)
  • == Is equal to? (lose equal­i­ty op­er­a­tor: com­pare on­ly the Val­ue the vari­able)
  • != Is not equal to? (lose not equal­i­ty op­er­a­tor: com­pare on­ly the Val­ue of the vari­able)
let x = 1;
console.log(x === 1);   // true
console.log(x !== 1);   // false
console.log(x === '1');  // false (because '1' is a string not a number)
console.log(x == '1');   // true (because we compare only the values)
console.log(x == true );  // true (because 'x' will be converted to a bulean before the evaluation)
console.log(x == false);  // false 
console.log(x === true);  // false (because 'x' is a number not a bulean)

Ternary (con­di­tion­al) op­er­a­tors

Ternary (con­di­tion­al) op­er­a­tors as­signs a val­ue to a vari­able based on some con­di­tion.

let variable = (condition) ? value_if_true : value_if_false;
let poinsts = 110;
let type = points > 100 ? 'good customer' : 'bad customer';
console.log('The customer is: ' + type);
The customer is: good customer

Log­i­cal op­er­a­tors

Log­i­cal op­er­a­tors are used to make de­ci­sions based at mul­ti­ple con­di­tions that re­turn Boolean val­ues – false or true. In JavaScript we have three types of log­i­cal op­er­a­tors.

&& Log­i­cal AND – re­turns TRUE if both operands are TRUE.

console.log(true  && true );   // true
console.log(false && true );   // false
console.log(true  && false);   // false

|| Log­i­cal OR – re­turns TRUE if one operands are TRUE.

console.log(true  || true );   // true
console.log(false || true );   // true
console.log(true  || false);   // true
console.log(false || false);   // false

! Log­i­cal NOT – gives an op­po­site log­ic.

console.log(! true );   // false
console.log(! false);   // true

Note the fol­low­ing con­struc­tion could be use­ful in some cas­es but it is not sub­sti­tu­tion of if.. then.. else state­ment, and should be used care­ful­ly:

(true) && console.log('then do') || console.log('else do');

In this case (in a re­al world ap­pli­ca­tion) if the ex­press­ing 'then do' in some­way re­turns true the ex­pres­sion 'else do' will be ex­e­cut­ed too.

Log­i­cal op­er­a­tors with Non-booleans – Truthy and Fal­sy

With­in JavaScript we can use the log­i­cal op­er­a­tors with non boolean val­ues. Here is how a log­i­cal ex­pres­sion works with boolean val­ues:

console.log(false || true);   // true  (as it is in the examples above)

The re­sult of a log­i­cal ex­pres­sion is not nec­es­sar­i­lytrue or false that de­pends on the val­ues and the operands we have.

console.log(false || 'Spas');  // "Spas"
console.log(false || '1');     // 1

The JavaScript en­gine tries to eval­u­ates the ex­pres­sions, looks at each operand and if the operand is not a boolean true or false it will tried to in­ter­pret­ed as what we called truthy or fal­sy. Fal­sy is not ex­act­ly a boolean false and truthy is not a boolean true.

The JavaScript fal­sy val­ues are:

  • un­de­fined
  • null
  • 0
  • false
  • '' (emp­ty string)
  • NaN (not a num­ber)

Any­thing is not fal­sy is truthy! Ex­am­ples with short-cir­cuit­ing where the eval­u­a­tions stops at some truthy val­ue, no mat­ter how many oth­er operands we have on the right side they will be ig­nored:

console.log(false || 1 || 2);       // 1
console.log(false || 1 || 0 || 2);  // 1

An ex­am­ple for pro­vid­ing de­fault val­ues by us­ing this tech­nique.

let userColor = 'red';
let defaultColor = 'blue';
let currentColor = userColor || defaultColor;
console.log(currentColor);
red
userColor = undefined;
console.log(currentColor);
blue

Bit­wise op­er­a­tors

Bit­wise op­er­a­tors are sim­i­lar to Log­i­cal op­er­a­tors but they work wit the in­di­vid­ual bits of a num­ber. Bit­wise op­er­a­tors are rarely used in the days prac­tice, but they have their place.

Num­bers in Dec­i­mal sys­tem Num­bers in Bi­na­ry sys­tem
1 00000001
2 00000010
3 00000011
4 00000100
5 00000101
Num­bers in Dec­i­mal sys­tem Num­bers in Bi­na­ry sys­tem
6 00000110
7 00000111
8 00001000
9 00001001
0 00000000

| Bit­wise OR (sin­gle pype/​​​vertical line). It com­pares each bit of the bi­na­ry num­bers in the ex­pres­sion and if one of them is 1 it re­turns 1.

console.log(1 | 2); // 3
1 = 00000001
2 = 00000010
3 = 00000011 (this is the result)

& Bit­wise AND (sin­gle am­per­sand). It com­pares each bit of the bi­na­ry num­bers in the ex­pres­sion and if one of them is 0 it re­turns 0.

console.log(1 & 2); // 0
1 = 00000001
2 = 00000010
0 = 00000000 (this is the result)

In JavaScript there are few more Bit­wise op­er­a­tors, but in the re­al world these are not that com­mon. For more de­tails read the ar­ti­cle: W3Schools: JavaScript Bit­wise Op­er­a­tions. One re­al world ex­am­ple of Bit­wise op­er­a­tors us­age is Bit­wise op­er­a­tors for per­mis­sions.

Op­er­a­tors Prece­dence

console.log(100 + 50 * 3); // 250

As in tra­di­tion­al school math­e­mat­ics, the mul­ti­pli­ca­tion is done first. Mul­ti­pli­ca­tion (*) and di­vi­sion (/) have high­er prece­dence than ad­di­tion (+) and sub­trac­tion (-). And (as in school math­e­mat­ics) the prece­dence can be changed by us­ing paren­the­ses:

console.log((100 + 50) * 3); // 450

More about the op­er­a­tors prece­dence could be found at the ar­ti­cle W3School: JavaScript Arith­metic – JavaScript Op­er­a­tor Prece­dence Val­ues.

String op­er­a­tors

The + op­er­a­tor can al­so be used to add (con­cate­nate) strings.

let text1 = "John";
let text2 = "Doe";
let text3 = text1 + " " + text2;
console.log(text3);
John Doe

The += as­sign­ment op­er­a­tor can al­so be used to add (con­cate­nate) strings:

let text1 = "What a very ";
text1 += "nice day!";
console.log(text1);
What a very nice day!

If you add a num­ber and a string, the re­sult will be a string!

Type op­er­a­tors

  • type­of – re­turns the type of a vari­able.
  • in­stance­of – re­turns true if an ob­ject is an in­stance of an ob­ject type.

For more in­for­ma­tion read: 1) W3School: JavaScript Type Con­ver­sion, 2) W3School: Ja­va in­stance­of Key­word, 3) W3School: JavaScript type­of.