TypeScript tutorial: Lesson 3 – Operators


TypeScript – Operators

Arithmetic Operators

Operator Description Example
+ (Addition) returns the sum of the operands var z = x + y
– (Subtraction) returns the difference of the values var z = x – y
* (Multiplication) returns the product of the values var z = x * y
/ (Division) performs division operation and returns the quotient var z = x / y
% (Modulus) performs division operation and returns the remainder var z = x % y
++ (Increment) Increments the value of the variable by one x++
— (Decrement) Decrements the value of the variable by one –y
** (Exponential operator) Exponential operator x**y

Example:

var x = 2        
console.log(++x)
console.log(x)
console.log(x++)
console.log(x)

Result:

[LOG]: 3 
[LOG]: 3 
[LOG]: 3 
[LOG]: 4 

Relational Operators

Operator Description Example
> Greater than (x > y)
< Lesser than (x < y)
>= Greater than or equal to (x >= y)
<= Lesser than or equal to (x <= y)
== Equality (x == y)
=== Strict Equality (x === y)
!= Inequality (x != y)
!== Strict inequality (x !== y)

Example:

var x:any = 2        
console.log(x=="2")
console.log(x==="2")

Result:

[LOG]: true 
[LOG]: false 

Logical Operators

Operator Description Example
&& (And) The operator returns true only if all the expressions specified return true (x > 10 && y > 10)
|| (OR) The operator returns true if at least one of the expressions specified return true (x > 10 || y >10)
! (NOT) The operator returns the inverse of the expression’s result. For E.g.: !(>5) returns false !(x >10 )

Example:

var x:number = 2  
var y:number = 4      
console.log(x==2 && y==4)
console.log(!(x==4))

Result:

[LOG]: true 
[LOG]: true 

Bitwise Operators

Operator Description Example
& (Bitwise AND) It performs a Boolean AND operation on each bit of its integer arguments. (x & y)
| (BitWise OR) It performs a Boolean OR operation on each bit of its integer arguments. (x | y)
^ (Bitwise XOR) It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both. (x ^ y)
~ (Bitwise Not) It is a unary operator and operates by reversing all the bits in the operand. (~x)
<< (Left Shift) It moves all the bits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying it by 2, shifting two positions is equivalent to multiplying by 4, and so on. (x << 1)
>> (Right Shift) Binary Right Shift Operator. The left operand’s value is moved right by the number of bits specified by the right operand. (x >> 1)
>>> (Right shift with Zero) This operator is just like the >> operator, except that the bits shifted in on the left are always zero. (x >>> 1)

Example:

var x:number = 2  
var y:number = 4      
console.log(x & y)
console.log(x | y)
console.log(x ^ y)
console.log(~x)
console.log(x>>1)
console.log(y>>>1)
console.log(y<<1)

Result:

[LOG]: 0 
[LOG]: 6 
[LOG]: 6 
[LOG]: -3 
[LOG]: 1 
[LOG]: 2 
[LOG]: 8 

Assignment Operators

Operator Description Example
= (Simple Assignment) Assigns values from the right side operand to the left side operand z = x + y will assign the value of x + y into z
+= (Add and Assignment) It adds the right operand to the left operand and assigns the result to the left operand. z += x is equivalent to z = z + x
-= (Subtract and Assignment) It subtracts the right operand from the left operand and assigns the result to the left operand. z -= x is equivalent to z = z – x
*= (Multiply and Assignment) It multiplies the right operand with the left operand and assigns the result to the left operand. z *= x is equivalent to z = z * x
**= (Exponential and Assignment) It exponential the right operand with the left operand and assigns the result to the left operand. z **= x is equivalent to z = z ** x
/= (Divide and Assignment) It divides the left operand with the right operand and assigns the result to the left operand.

More Assignment Operators : <<=, >>=, >>=, &=, |=, >>>= and ^=

Miscellaneous Operators

The negation operator (-)
String Operators: Concatenation operator (+)
Conditional Operator (?)

Condition ? true_expr : false_expr

Result:

var x:number = 2  
var y:number = 4  
var z:number = (x>y)?1:-1
console.log(z)

Result:

[LOG]: -1 

Nullish coalescing operator – Null coalescing operator (??)

Result:

var x:number = 2  
var y:number = 4  
var z:number = x??y
console.log(z)

This operator is equal to:

var z:number = (x!== null && x !== undefined)?x:y

Result:

[LOG]: 2 

Rest Operator (Rest parameters)

Example:

function Func(a:any, b:any, ...params:any[]) { // used rest operator here
  console.log(a);
  console.log(b);
  console.log(params);
}

Func("H","E","L","L","O"); 

After compiling

"use strict";
function Func(a, b) {
    var params = [];
    for (var _i = 2; _i < arguments.length; _i++) {
        params[_i - 2] = arguments[_i];
    }
    console.log(a);
    console.log(b);
    console.log(params);
}
Func("H", "E", "L", "L", "O");

Result:

[LOG]: H 
[LOG]: E 
[LOG]: [ "L", "L", "O" ] 

Type Operators

typeof operator

Example:

var x = "tutorialspots"
console.log(typeof x)

Result:

[LOG]: string 

instanceof
This operator can be used to test if an object is of a specified type or not.

Example:

class Animal {
    name = "Alex"
    constructor(name:string){
        this.name = name
    }
    setName(newName:string):void{
        this.name = newName
    }
}
var cat = new Animal("MeoMeo")
console.log(cat instanceof Animal)

After compiling

var Animal = /** @class */ (function () {
    function Animal(name) {
        this.name = "Alex";
        this.name = name;
    }
    Animal.prototype.setName = function (newName) {
        this.name = newName;
    };
    return Animal;
}());
var cat = new Animal("MeoMeo");
console.log(cat instanceof Animal);

Result:

[LOG]: true 

Spread Operator

Example 1: For array literals or strings

var a = [1,2,3]
var b = [...a, '4', 'five', 6]

console.log(b)

Result 1:

[LOG]: [ 1, 2, 3, "4", "five", 6 ] 

Example 2: For object literals

var obj = {"a":1,"b":2}
var objClone = { ...obj };
console.log(objClone)

Result 2:

[LOG]: { "a": 1, "b": 2 } 

Example 3: for function calls

var obj = [2,3,4]
var myFunction = function(x:any,...params:any[]){ //rest operator
    console.log(x,params)
}
myFunction(0,1,...obj); //spread operator

Result 3:

[LOG]: 0,  [ 1, 2, 3, 4 ] 

Non-null assertion operator

A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.

// Compiled with --strictNullChecks
function validateEntity(e?: Entity) {
  // Throw exception if e is null or invalid entity
}

function processEntity(e?: Entity) {
  validateEntity(e);
  let s = e!.name; // Assert that e is non-null and access name
}

Use Non-null assertion operator in class: TypeScript tutorial: Lesson 13 – Class

Optional Chaining operator
The new ?. operator for optional property accesses
Example 1:

let x = foo?.bar.baz()

Equivalent to:

let x = (foo === null || foo === undefined) ?
    undefined :
    foo.bar.baz()

Example 2:

let x = arr?.[0]

Equivalent to:

let x = (arr === null || arr === undefined) ?
           undefined :
           arr[0]

Example 3: optional call

log?.(`some content`);

Equivalent to:

   if (log !== null && log !== undefined) {
          log(`some content`);
       }

1 Comment

Leave a Reply