Tag Archives: js

Learn TypeScript – A Brief Overview for Beginners

Overview:

TypeScript is pure object oriented language with classes, interfaces and statically typed like Java. It helps programmers to write object-oriented programs and have them compiled to JavaScript, both on server side and client side. In other words, TypeScript is JavaScript plus some additional features.
The popular framework written in TypeScript is Angular 2.

Features of TypeScript:

  • It is just JavaScript.
  • It supports other JS libraries.
  • It is portable.
  • It is aligned with ES6 specifications.

Benefits of TypeScript include:

  • Compilation: TypeScript transpiler provides the error-checking feature. It will compile the code and generate compilation errors, if it finds some sort of syntax errors. This helps to highlight errors before the script is run.
  • Static Typing: TypeScript provides static typing and type inference system through the TLS (TypeScript Language Service). The type of a variable, declared with no type, may be inferred by the TLS based on its value.
  • Type definitions: TypeScript Definition file (with .d.ts extension) provides definition for external JavaScript libraries. Hence, TypeScript code can contain these libraries.
  • Object Oriented Programming: TypeScript supports concepts like classes, interfaces, inheritance, etc.

A TypeScript program is composed of –

  • Modules
  • Functions
  • Variables
  • Statements and Expressions
  • Comments

Example:

var message:string = "My first TypeScript file"
console.log(message)

Note:  

  • To compile the file use – tsc fileName.ts
  • To Execute the file use – node fileName.js
  • Multiple files can be compiled at once – tsc file1.ts, file2.ts, file3.ts

Object Oriented JavaScript:

TypeScript is object-oriented javascript. It considers a program as a collection of objects that communicate with each other via mechanism called methods.
Example:


class FirstTSClass{
display(message):void {
console.log(message)
}
}
var obj = new FirstTSClass();
obj.message("My First TypeScript class.");

TypeScript Data Types:

TypeScript provides data types as a part of its optional Type System.

Data type classification:

  • Any: It is the super type of all types in TypeScript.
  • Built-in types: It includes number, string, Boolean, void, null, undefined.
  • User-defined Types: It includes Enumerations (enums), classes, interfaces, arrays, and tuple.

TypeScript Variables:

Use var keyword to declare variables. It must follow the JavaScript naming rules:

  • It can contain alphabets and numeric digits.
  • It cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign.
  • It cannot begin with a digit.

Variable declaration in TypeScript:

  • Declare its type and value in one statement.

//Syntax: var [identifier] : [type] = value ;

var message:string = "sample";

  • Declare its type but no value. The declared variable will be set to undefined.

//Syntax: var [identifier] : [type];

var message:string;

  • Declare its value but no type. The declared variable data type will be set to any.

//Syntax: var [identifier] = value;

var message = "Hello";

  • Declare neither value not type. The declared variable will be set to undefined and declared variable data type will be set to any.

//Syntax: var [identifier];

var message;

Strong Typing:

TypeScript follows Strong Typing. The Strong typing syntax ensures that the types specified on either side of the assignment operator (=) are the same.

This code will result in a compilation error:


var value:number = "One"; //compilation error

Type Assertion:

TypeScript allows changing a variable from one type to another. It refers to this process as Type Assertion.


//Syntax: var [identifier]:[type] = <target type> <source type> [value];

var value = '1';

var newValue:number = <number> <any> value;

console.log(newValue);

Inferred Typing:

In TypeScript we can declare variable without a type. In this case, compiler will find the first usage of that variable and determine the type of the variable on the basis of the value assigned to it. This type should be same for that variable in the complete code block else compiler will throw an error.


var num = 2;

console.log("Value of num " + num);

num = "12"; // Compilation error - error TS2011: Cannot convert 'string' to 'number'.

console.log(num)

TypeScript Variable Scope:

TypeScript variables can be of the following scopes:

  • Global Scope : accessed from anywhere within your code.
  • Class Scope : accessed using the object of the class.
  • Local Scope : accessible only within the construct where they are declared.

var global_var = 10;

class TypeScriptScope{

class_var = 5;

static static_var = 15;

localMethod():void{

var local_var = 4;

console.log("Local Variable :: "+ local_var);

}

}

console.log("Global Variable :: "+ global_var); 

console.log("Static variable :: "+ TypeScriptScope.static_var);

var typeScriptScope = new TypeScriptScope();

 console.log("Class variable :: "+ typeScriptScope.class_var);

typeScriptScope.localMethod();

TypeScript Operator, Statements and Loops:

The major operators in TypeScript can be classified as:

  • Arithmetic operators
  • Logical operators
  • Relational operators
  • Bitwise operators
  • Assignment operators
  • Ternary/conditional operator
  • String operator
  • Type Operator

The major statements in TypeScript can be classified as:

  • If statement
  • If…else statement
  • else..if and nested…if statement
  • switch statement
  • break
  • continue

The major loop in TypeScript can be classified as:

  • For loop
  • while loop
  • do…while loop

TypeScript Functions:

A. Parameterize Functions:

  • Positional Parameters:

//Syntax: function function_Name(arg1:[data type], arg2:[data type]){...}

function displayLog(line:number, message:string){

 console.log("Exception at "+line+" : "+message);

 }

 displayLog(23,"Undefined variable!!");

  • Optional Parameters:

//Syntax: function function_Name(arg1:[data type], arg2:[data type], arg3?:[data type]){...}

function displayLog(line:number, message:string, module?:string){

 if(module != undefined){

 console.log("Exception in "+ module +" module at "+line+" : "+message);

 }else{

 console.log("Exception at "+line+" : "+message);

 }

  • Rest Parameters:

//Syntax: function function_Name(...args:[data type]){...}

function displayNumber(...table:number[]){

 for(i=0; i<table.length; i++){

 console.log("Argument - "+ (i+1) + " value :: "+ table[i]);

 }

 }

  • Default Parameters:

//Syntax: function function_name(arg1:[data type], arg2:[data type] = default_value) {...}

 function displayLog(line:number, message:string, module:string = "Test App"){

 console.log("Exception in "+ module +" module at "+line+" : "+message);

 }

B. Anonymous Functions:


//Syntax: var func = function([args]){...}

var fullName = function(firstName:string, lastName:string){

 return (firstName +" "+lastName);

 }

C. Function Constructor:


//Syntax: var func = new Function([args],{function logic with return result})

var addition = new Function("a","b","return a+b");

console.log("Function constructor example :: "+ addition(1,2));

D. Lambda Functions:


//Syntax: var lamdaFn = ([arg1,arg2,...arg n]) => statement;

var sumFn = (arg1:number,arg2:number) => (arg1 + arg2);

 console.log("Lambda Function Example :: "+sumFn(2,6));

E. Overload Functions:

To overload a function in TypeScript, you need to follow the mentioned steps:

    • Declare multiple functions with the same name but different function signature.
      • The data type of the parameter.
        //Syntax: function display(num:number)
        function display(str:string)
        
      • The number of parameters.
        //Syntax: function display(num:number)
        function display(num:number, str:string)
        
      • The sequence of parameters.
        //Syntax: function display(num:number)
        function display(str:string, num:number)
        
    • Declaration must be followed by the function definition.
      Note: If the parameter types differ during overload then parameter types should be set to any. For Case B, mark one or more parameters as optional during the function definition.
    • Finally, invoke the function to make it functional.

Example:


			function overloadFn(arg1:number):void;
			function overloadFn(arg1:number,arg2:string):void;

			function overloadFn(arg1:any,arg2?:any):void{
				if(arg2){
					console.log("Overload function having two arguments :: "+ arg1 +" and "+arg2);
				}else{
					console.log("Overload function having single arguments :: "+ arg1 + " only.");
				}
			}

			overloadFn(10);
			overloadFn(11,"Sample");

TypeScript Numbers:

TypeScript supports numeric values as Number objects which converts numeric literal to an instance of the number class using its constructor.

Properties of Numbers:

  • MAX_VALUE – 1.7976931348623157E+308.
  • MIN_VALUE – 5E-324.
  • NaN – Not a Number
  • NEGATIVE_INFINITY – Less than MIN_VALUE.
  • POSITIVE_INFINITY – Greater than MAX_VALUE.
  • prototype – Static property of Number object to assign new properties and methods to it.
  • constructor – To create Number object instance.

Methods of Number:

  • toExponential() – to display an exponential notation.
  • toFixed() – to display specific number of digits to the right of the decimal.
  • toLocaleString() – to return a string value version of the current number. It may vary according to a browser’s local settings.
  • toPrecision() – to display specified digits of a number(including digits to the left and right of the decimal). A negative precision will throw an error.
  • toString() – to return the string representation of the number’s value.
  • valueOf() – to return the number’s primitive value.

Example of Number Properties and Methods:

		interface Number{
			toSquare(): number;
		}

		function showNumberProperties(){

			//Max Value
			var max_value = Number.MAX_VALUE;
			console.log("Maximum Value of Number :: "+ max_value);

			//Min value
			var min_value = Number.MIN_VALUE;
			console.log("Minimum Value of Number :: "+ min_value);

			//Nan
			var nonNumber = new Number("acs");
			console.log("Example of not a number :: "+nonNumber);

			//prototype
			Number.prototype.toSquare = function () : number{
				return this*this;
			}
			var num:number = 10;
			console.log("Prototype example :: "+ num.toSquare());
		}

		showNumberProperties();

		function showNumberMethods(){
			//toExponential()
			var numExp = 1234.567
			console.log("toExponential Example :: "+ numExp.toExponential());

			//toFixed()
			console.log("toFixed() Example :: "+ numExp.toFixed());
			console.log("toFixed(1) Example :: "+ numExp.toFixed(1));

			//toLocaleString()
			console.log("toLocaleString Example :: "+ numExp.toLocaleString("cs"));
			console.log("toLocaleString Example :: "+ numExp.toLocaleString("en"));

			//toPrecision()
			console.log("toPrecision() Example :: "+ numExp.toPrecision());
			console.log("toPrecision(4) Example :: "+ numExp.toPrecision(4));
			console.log("toPrecision(5) Example :: "+ numExp.toPrecision(5));

			//toString()
			console.log("toString() Example :: "+ numExp.toString());
			console.log("toString(2) Example :: "+ numExp.toString(2));

			//valueOf()
			console.log("valueOf() Example :: "+ numExp.valueOf());
		}

		showNumberMethods();

TypeScript Strings:

Example of String Properties and Methods:

		interface String{
			doPrefix(arg1:string) : string;
		}

		function showStringProperties(){

			//constructor
			var str = new String("Hello World");
			console.log("Example of String constructor :: "+ str);

			//Length
			console.log("Example of String Length :: "+ str.length);

			//prototype
			String.prototype.doPrefix = function(arg1:string):string{
					return (arg1+this);
			}

			console.log("Example of String prototype :: "+str.doPrefix("String prototype "));
		}

		showStringProperties();

		function showStringMethods(){

			var strExp = "String Methods Example";

			//charAt()
			console.log("charAt() example :: "+ strExp.charAt(7));

			//charCodeAt()
			console.log("charCodeAt() example :: "+strExp.charCodeAt(7));

			//concat()
			console.log("concat() example :: "+strExp.concat("concat method"));

			//indexOf()
			console.log("indexOf() example :: "+strExp.indexOf("Example"));

			//lastIndexOf()
			console.log("lastIndexOf() example :: "+strExp.lastIndexOf("h"));

			//localeCompare()
			console.log("localeCompare() example :: "+strExp.localeCompare("String Methods Example"));

			//replace()
			console.log("replace() example :: "+strExp.replace("Methods","Functions"));

			//search()
			console.log("search() example :: "+strExp.search("Methods"));

			//slice()
			console.log("slice() example :: "+strExp.slice(0,7));

			//split()
			console.log("split() example :: "+strExp.split(" ").length);

			//substr()
			console.log("substr() example :: "+strExp.substr(7,strExp.length));

			//substring()
			console.log("substring() example :: "+strExp.substring(7,strExp.length));

			//toLocaleUpperCase()
			console.log("toLocaleUpperCase() example :: "+strExp.toLocaleUpperCase());

			//toLocaleLowerCase()
			console.log("toLocaleLowerCase() example :: "+strExp.toLocaleLowerCase());

			//toLowerCase()
			console.log("toLowerCase() example :: "+strExp.toLowerCase());

			//toUpperCase()
			console.log("toUpperCase() example :: "+strExp.toUpperCase());

			//toString()
			console.log("toString() example :: "+strExp.toString());

			//valueOf()
			console.log("valueOf() example :: "+strExp.valueOf());

		}

		showStringMethods();

TypeScript Arrays:

Example of Arrays Properties and Methods:

		//Simple Array
		var employeeNameArray : String[]; //declaration
		employeeNameArray = ["Test Name 1","Test Name 2"]; //initialization
		console.log("Array Example :: "+ employeeNameArray[0] +" And "+employeeNameArray[1]);

		//Declaration and initialization in single statement
		var numArr:number[] = [1,2,3,4,5,6];
		console.log("Array declaration and initialization in single statement :: "+ numArr);

		//Array Object
		var arrObj:number[] = new Array(10);
		console.log("Array object example ::");
		for(var i=0; i<10; i++){
			arrObj[i] = (i+1)*2;
			console.log((i+1) + "*2 = "+arrObj[i]);
		}

		//Array Constructor
		var arrConstructor:string[] = new Array("one","two");
		console.log("Array constructor example :: "+arrConstructor);

		//Arrays methods

		function everyFn(element, index, array){
			return (element< 11);
		}

		function filterEvenNum(element, index, array){
			return (element % 2 === 0);
		}

		function cube(element, index, array){
			return Math.pow(element,3);
		}

		function smallerValue(arg1,arg2){
			return (arg1<arg2?arg1:arg2); 		} 		function someFn(element){ 			return (element >= 10);
		}

		function sortFn(arg1,arg2){
			return (arg1 > arg2 ? -1 : arg1==arg2 ? 0 : 1)
		}

		function displayOdd(arg:number[]){
			console.log("Arrays as parameter example :: "+arg)
		}

		function showArraysMethods(){

			var oddArr:number[] = [1,3,5,7,9];
			var evenArr:number[] = [2,4,6,8,10]; 

			var concatArr:number[] = oddArr.concat(evenArr)
			//concat()
			console.log("concat() example :: "+ concatArr);

			//every()
			var everyExample = concatArr.every(everyFn);
			console.log("every() example :: "+ everyExample);

			//filter()
			var filterExample = concatArr.filter(filterEvenNum);
			console.log("filter() example :: "+ filterExample);

			//forEach()
			console.log("forEach() example :: ");
			concatArr.forEach((element,index) => {
				console.log("Value at position-"+index+" :: "+element);
			});

			//indexOf()
			console.log("indexOf() example :: "+ concatArr.indexOf(5));

			//join()
			console.log("join() example :: "+ concatArr.join("-"));

			//lastIndexOf()
			console.log("lastIndexOf() example :: "+ concatArr.lastIndexOf(10));

			//map()
			console.log("map() example :: "+ evenArr.map(cube));

			//pop()
			console.log("pop() example :: "+ oddArr.pop());

			//push()
			console.log("push() example - length of oddArr before push :: "+ oddArr.length);
			console.log("push() example - length of oddArr after push :: "+ oddArr.push(11));

			//reduce()
			console.log("reduce() example :: "+ concatArr.reduce(smallerValue))

			//reduceRight()
			console.log("reduceRight() example :: "+ concatArr.reduceRight(smallerValue))

			//reverse()
			console.log("reverse() example :: "+ concatArr.reverse())

			//shift()
			console.log("shift() example :: "+ oddArr.shift())

			//slice()
			console.log("slice() example :: "+ concatArr.slice(1,7));

			//some()
			console.log("some() example :: "+ concatArr.some(someFn));

			//sort()
			console.log("sort() example :: "+ concatArr.sort(sortFn));

			//splice()
			var spliceFnExm = concatArr.splice(2,0,16);
			console.log("splice() example of adding new element :: "+ concatArr);
			spliceFnExm = concatArr.splice(2,1);
			console.log("splice() example of removing the element :: "+ concatArr);

			//toString()
			console.log("toString() example :: "+ concatArr.toString());

			//unshift()
			var unshiftArrExm = concatArr.unshift(11,12);
			console.log("unshift() example :: "+ concatArr);

			//Array destructuring
			var[first,,second] = concatArr;
			console.log("Array destructuring example :: "+ second)

			//for...in loop
			for (var index in concatArr) {
				console.log(concatArr[index]);
			}

			//multidimensional array
			var multidimArr:String[][] = new Array();
			for (var outer = 0; outer < 3; outer++){
				multidimArr[outer] = new Array(3);
				for(var inner = 0; inner < 3; inner++){
					multidimArr[outer][inner] = new String("*");
				}
			}

			console.log("Multidimensional Array declaration and initialization Example :: "+ multidimArr)

			//Arrays as argument
			displayOdd(oddArr);

		}

		showArraysMethods()

Advertisements

JavaScript Functional Programming

Functional Programming in JavaScript:

JavaScript supports functional programming and functional programming represents data in our application.

Arrow functions:

const display = name => console.log(name)

Function as variable:


const person = {
name:"test data",
display(name){
console.log(name) }
}
person.display(person.name)

Function in array:


const person = ["Test one",
name => console.log(name),
"Test two",
name => console.log(name)]

person[1](person[0]) // Test one
person[3](person[2]) // Test two

Higher order functions, functions that either take or return other functions (i.e. more than one arrow):


const person = display => name => logger(name + !!!!!)

const showName = person(name => console.log(name))

showName("Test data") //Test data !!!!!

Notes:

  1. Functions can be saved, retrieved, or flow through your applications just like variables.
  2. Functional programming is a part of declarative programming.

Core concepts of functional programming:

  1. Immutablitiy: In functional programming, data is immutable. It never changes.
    let employee = {
    name: "Test",
    gender: "M",
    age: 23,
    grade: 'B'
    }
    
    const addGrade = (employee, grade) => ({...employee,grade})
    console.log(addGrade(employee,'A').grade) // A
    console.log(employee.grade) // 'B'
    
  2. Pure functions: A pure function is a function that returns a value that is computed based on its arguments.
    To create a pure function, try to follow the mentioned rules:
    – It should take in at least one argument.
    – It should return a value or another function.
    – It should not change or mutate any of its arguments.

    const addGrade = employee => ({
    ...employee,
    age: 30,
    grade: 'C'
    })
    
    console.log(addGrade(employee)) // {name:"Test", gender:"M", age:"30", grade:"C"}
    console.log(employee) // {name:"Test", gender:"M", age:"23", grade:"B"}
    
  3. Data Transformations: Functional programming is all about transforming data from one form to another. Two core functions with functional javascript – Arrays.map and Arrays.reduceFew useful javascript functions:

    Array.join :

    const fourWheelers = ["Car","Bus","Truck"]
    console.log(fourWheelers.join("-")) // Car-Bus-Truck
    

    Array.filter:

    const lmv = fourWheelers.filter(fourWheeler => fourWheeler === "Car")
    console.log(lmv) // Car
    

    Array.map:

    const fourWheelersName = fourWheelers.map(fourWheeler => '${fourWheeler} is Four wheeler.')
    
    console.log(fourWheelersName.join('/n'))
    /* Car Four Wheeler
    Bus Four Wheeler
    Truck Four Wheeler */
    
    console.log(fourWheelers.join('/n'))
    /* Car
    Bus
    Truck */
    
    const names = ["Test","Test1","Test2"]
    const editName = (oldName,newName,names) => names.map(name => (name === oldName)? newName : name)
    
    console.log(editName("Test","Test New", names)) //["Test New","Test1","Test2"]
    console.log(names) //["Test","Test1","Test2"]
    
    ** Object.keys is a method that can be used to return an array of keys from an object.
    
    

    Array.reduce/Array.reduceRight : These functions can be used to transform an array into any value including a number, string, Boolean, object or even a function.

    Reduce takes two arguments, a callback method and an original value.

    const scores = [23,3,12,14,34,1,25]
    const maxScore = scores.reduce((max,score) => (score > max)? score : max, 0)
    
    console.log(maxScore) //34
    

    ReduceRight works the same way as reduce, the difference is that it start reducing from the end of the array rather than the beginning.

    const values = [1,2,2,3,4,2,3,5,6]
    const distinctValues = values.reduce((newValues,value) => (newValues.indexOf(value) !== -1 ? newValues : [...newValues,value]),[])
    
    console.log(distinctValues)// [1,2,3,4,5,6]
    
  4. Higher-order functions: These are the functions that can manipulate other functions.
    const showTrue = () => console.log('Execute true function')
    const showFalse = () => console.log('Execute false function')
    const checkCondition = (condition, trueFn, falseFn) => (condition ? trueFn() : falseFn())
    
    console.log(checkCondition(true,showTrue,showFalse)) //Execute true function
    console.log(checkCondition(false,showTrue,showFalse)) //Execute false function
    
  5. Recursion: It is a technique that involves creating functions that recall themselves.
    const countdown = (maxvalue, showVal) => {
    showVal(maxvalue)
    return (maxvalue > 0) ? (countdown(maxvalue-1, showVal)) : maxvalue
    }
    
    countdown(10, value => console.log(value)); //10 9 8 7 6 5 4 3 2 1 0
    
    **Recursion should be used over loops but large amount of recursions can cause JavaScript errors.
    
  6. Composition: The goal of composition is to generate higher order function by combings simpler functions. It takes functions as arguments and return a single function.
    const name = person => appendSalutation(completeName(person))
    const name = compose(
    appendSalutation,
    completeName,
    )
    name(new Person())
    
    const compose = (...fns) => (args) => fns.reduce((composed,f) => f(composed), arg)
    

NOTE:
Follow these three simple rules to achieve functional programming :

  1. Keep data immutable.
  2. Keep functions pure – accept at least one argument, return data or another function.
  3. Use recursions over looping (wherever possible).