Category Archives: Javascript

Learn TypeScript – A Brief Overview for Beginners


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


var message:string = "My first TypeScript file"


  • 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.

class FirstTSClass{
display(message):void {
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;


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'.


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;


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);


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);


 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.


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

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


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
  • 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);

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

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


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

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

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

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

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

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


TypeScript Strings:

Example of String Properties and Methods:

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

		function showStringProperties(){

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

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

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

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


		function showStringMethods(){

			var strExp = "String Methods Example";

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

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

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

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

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

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

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

			console.log("search() example :: ""Methods"));

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

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

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

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

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

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

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

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

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

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



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)
			console.log("concat() example :: "+ concatArr);

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

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

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

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

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

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

			console.log("map() example :: "+;

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

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

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

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

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

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

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

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

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

			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);

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

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

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

			// loop
			for (var index in concatArr) {

			//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




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",
console.log(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 !!!!!


  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 => ({
    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 – and Arrays.reduceFew useful javascript functions:

    Array.join :

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


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

    const fourWheelersName = => '${fourWheeler} is Four wheeler.')
    /* Car Four Wheeler
    Bus Four Wheeler
    Truck Four Wheeler */
    /* Car
    Truck */
    const names = ["Test","Test1","Test2"]
    const editName = (oldName,newName,names) => => (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) => {
    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(
    name(new Person())
    const compose = (...fns) => (args) => fns.reduce((composed,f) => f(composed), arg)

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).

ES6 Basics

JavaScript Basics

1. Const : We cannot reset the value of constant variable.

const value = true;

2. let : with let keyword, we can limit the scope of a variable to any code block.

let topic = true;

3. Template String: with template string, we can create one string and insert the variable values by surrounding them with ${}

`${Salutation} ${firstName} ${lastName}`

4. Default Parameters: If a value is not provided for the argument, default value will be used. default argument can be any type.

function activity(name="Test"){

5. Arrow Function: With arrow functions, you can create the functions without using the function keyword.

var showName = (firstName,lastName) =>`${firstName} ${lastName}` 
var displayRole = role => {
  throw new Error('Role is required');
return `${role}` 

Note: Arrow function protect the scope of this, but not block the scope of this.

6. Transpiling ES6: Not all browser supporting ES6, so we need to convert it to ES5 code before running it in browser.One of the popular tool for transpiling  is Babel.You can transpile the javascript directly in the browser using inline Babel transpiler. You just include the browser.js file and any script with type=”text/babel” will be converted.

<script src=""> </script>
<script src="script.js" type="text/babel"></script>

Note: Transpiling approach is not a good idea for production because it will slow down the application.

ES6 Objects and Arrays:

1. Destructuring Assignment:

It allows us to locally scope fields within an object and to declare which values will be used.

  • Destructuring object having four keys and we only want to use two keys out of them.
var object= { salutation: "Mr.",
 firstName: "Test",
 lastName: "Data",
 role: "Developer"}

var {firstName,lastName} = object console.log(firstName,lastName); 
  • Destructuring incoming function argument:
var name = { firstName: "Test",
lastName: "Data" }

var showFirstName = ({firstName}) => console.log(`${firstName}`)
  • Assign the specific element value of an array to a variable name:
var [salutation] = ["Salutation","FirstName","LastName"]
console.log(salutation) //Salutation
var [,,lastName] = ["Salutation","FirstName","LastName"]
console.log(lastName) //LastName 

2. Object Literal Enhancement:

It the process of restructuring or putting back together.

  • with object literal enhancement, we can grab variables from global scope and turn them into an object.
var firstName = "Test"
var lastName = "Data"
var name = {firstName,lastName}
console.log(name) // {firstName:"Test", lastName:"Data"} 
  • with object literal enhancement, we can create object method.
var print = () =>{ console.log(`${this.firstName} ${this.lastName}`)}
var name = {firstName, lastName, print}
name.print() // Test Data 
  • while defining object methods, it is no longer necessary to use the function keyword
const newName = { firstName,
console.log(`${this.firstName} ${this.lastName}`);
 console.log(`salutation ${this.firstName} ${this.lastName}`);}

3. The Spread Operator:

It represents with three dots(…) that performs several different tasks.

  • With Spread Operator, we can combine the contents of arrays.
 var fruits = ["Mango","Grapes","Banana"]
 var drinks = ["Mazza","Rani","Tropicana"]
 var fruitDrink = [...fruits,...drinks] 
 console.log(fruitDrink.join(",")) //Mango,Grapes,Banana,Mazza,Rani,Tropicana

Note: Spread Operator creates the copy of the array and then do the specified process.

  • Spread Operator can be used to get some, or the rest, of the items in the array
 var [first,] = fruits
 console.log(rest.join(",")) //Grapes,Banana
  • Spread Operator can also be used to collect function arguments as an array.
function directions(...args){ 
var [start, ...remaining] = args
 var [finish, ...stops] = remaining.reverse()
 console.log(`drive through ${args.length} towns`)
 console.log(`start in ${start}`)
 console.log(`the destination is ${finish}`)
 console.log(`stopping ${stops.length} times in between.`) 
  • Spread Operator can also be used for Objects.
var employee = { name: "Test", age: "20" }
var department = " Admin"
var company = { ...employee, department }
console.log(company) // { name:"Test", age:"20", department:"Admin" }


It give us a way to make sense out of asynchronous behavior. It simplify back to a simple pass or fail.


ES6 introduces class declaration, but javascript still works the same way. Functions are objects and inheritance is handled through the prototype.

class Person
constructor(name,age){ = name this.age = age
 console.log('My name is ${} and I am ${this.age} years old.') }

Note: All types should be capitalized, due to that we will capitalize all class names.

  • We can create the new instance of the class using new keyword.
const personObj = new Person("Test data", 30);
 console.log(personObj.display()); //My name is Test data and I am 30 years old.

Simple Inheritance:

class UID extends Person{
 constructor(name, age, uniqueID){
 this.uniqueID = uniqueID 
 console.log('And ${this.uniqueID} is my uniqueID.') }

const personDtl = new UID("Test Data", 30, 1234567)
 console.log(personDtl.print()); //My name is Test data and I am 30 years old. And 1234567 is my uniqueID.

ES6 Modules:

JavaScript module is a piece of reusable code that can easily be incorporated into other javascript files.JavaScript module stored in separate file, one file per module.

  • Export multiple javascript object per module.

export const display(name) => log(name, new Date())
export const log(name, timestamp) =>
console.log(`${timestamp.toString()} : ${name}`)
  • export default, using this we can export single javascript object from a module.
const person = new Person("Test data", 26)
export default person
  • Modules can be consumed in other javascript file using import statement. Modules containing multiple export can take advantage of object destructuring.
import {display, log} from './script1'
import person from './script2'

display("display Test data details")
log("logging test data details")

  • we can scope modules variables locally under different variable names.

import {display as d, log as l} from './script1'

p("display test data details")  l("logging test data details")

  • we can import everything into single  variable using *.

import * as prsn from './script'


It is the module pattern that is supported by all versions of Node.js

  • with commonJS, object are exported using module.exports
module.exports = {display, log}
  • with commonJS, objects are imported using require function

const {display, log} = require('./script1')