Click here to Skip to main content
13,258,269 members (41,895 online)
Click here to Skip to main content
Add your own
alternative version

Stats

59.4K views
3.1K downloads
158 bookmarked
Posted 27 Jul 2017

Learn Angular in 10 days – Day 1 – Part 1

, 24 Oct 2017
Rate this:
Please Sign up or sign in to vote.
A 10 Days series on Latest version of Angular - Day 1 will be very basic and mostly on JavaScript, TypeScript.

Hey folks, I am back. After the huge success of Learn MVC Project in 7 days, I have decided to write a new series on one of the most popular JavaScript framework at this time. The Angular. Hope you all enjoy this 10 days journey. We will learn latest version of Angular Step by Step with a Project.

Note: 10 days != 10 articles. To keep everything sweet and simple, sometimes we will break individual day into multiple parts.

Day 1 will be very basic and mostly on JavaScript and TypeScript.
Day 2 will be about basic Angular terminologies, setup and “Hello World” example.
From Day 3 we will start with our Angular Project and with every new day you will see more and more advanced stuff coming up.  

Choose your day correctly

I request all of you to jump to the Day 1, Day 2 or Day 3 directly based on your interest. If you believe you know TypeScript then you can directly start with Day 2.

To get the best use of the series, I recommend everyone to start with Day 1. (At least get through day 1 very quickly as a revision.)

Note: Angular (commonly called as Angular 2 or higher) is very different from its ancestor AngularJS (commonly known as Angular 1). All terminologies and explanations used in this series are completely based on Angular (that is, Angular 2 or higher).

Complete Series

  1. Day 1 – Part 1
  2. Day 1 – Part 2
  3. Day 2
  4. Day 3
  5. Day 4 – Part 1
  6. Day 4 - Execution trick
  7. Day 4 – Part 2
  8. Day 4 – Part 3
  9. Day 5 (Coming soon)
  10. Day 6 (Coming soon)
  11. Day 7 (Coming soon)
  12. Day 8 (Coming soon)
  13. Day 9 (Coming soon)
  14. Day 10 (Coming soon)

 

Contents – Day 1 – Part1

What is JavaScript and Why JavaScript?

In almost all my trainings I ask this question and mostly I hear "For validation".

JavaScript is definitely more than that. HTML is the basic necessity of every web application. No matter if you are a .NET developer or Java, without HTML you cannot create a web application.

The biggest limitation of HTML is it's static. If you create a HTML page displaying "Hello world" in bold, it will always display same output. No matter how many times you refresh the page.

To overcome this static limitation we used to take help of Server Side technologies like PHP, ASP.NET etc. These server side technologies generates different HTML on every request and sends back and thus leads to a fully fledged dynamic application.

Important Note:
To learn Angular basic knowledge on JavaScript and HTML is must. When i say basic knowledge, it's not just theoretical. It shoul be Theory + practical. You can checkout following links to get some basic idea on same.

https://www.w3schools.com/js/default.asp

https://www.w3schools.com/html/default.asp

What’s the problem with this traditional methodology?

Problem is in the modern era, competition is huge. Every business is trying to make their web app better than their competitor's app. They are trying to build faster web applications with better user experience.

Relying on only server side technology affects the overall performance of our app. Just try to imagine the role of a server. (In the case of most of the apps)

  1. It handles client requests
  2. Get data from different places (may be from Database, Services etc.)
  3. Execute some logic on that data
  4. Generate HTML
  5. Return the response

Just try to think about another approach – the server will send the data as a response instead of HTML. In the client side, HTML will be dynamically manipulated and created with the help of JavaScript. The advantages of such approach is:

  • Performance - It will improve the user experience as application performance will be better as compared to earlier. In this approach there will be less overhead on the server plus data transmitted over the wire will be small compared to earlier. (It will be only data. Earlier it was data combined with HTML tags)
  • Cheaper servers - Today mostly all applications are moving to cloud environment. In the cloud, server costs will be based on usage. We will be charged based on how much RAM we need, hard disc we need, how much bandwidth we consume etc.

So the simple answer to the above question will be as follows:

"JavaScript is a client side scripting language for manipulating and creating dynamic HTML. Using JavaScript instead of server-side technologies improve the performance and over all web experience."

Introduction to NodeJS

As I said, JavaScript is mainly used for manipulating and creating HTML dynamically.

NodeJS took JavaScript to next level by providing a complete environment for executing JavaScript outside the browser. Yes you heard right. You can execute JavaScript without a browser now.

So far you must have seen people developing various kinds of applications (such as Desktop based applications, Web based applications, Web servers, Web services etc.) using programming languages such as Java, C#, VB.NET. In order to do that they have to first install the appropriate framework in their machine. For instance, if you want to develop an application in C# then you have to install the .NET framework.

Once installed, you will be able to create your application in C# and the .NET framework will give you all the things which are required for development and execution.

Now we can develop such applications using JavaScript too and for that we will be require NodeJS. You can find the NodeJS setup in following link.

https://nodejs.org/en/

Simply click the link and install the setup.

Introduction to NPM?

NPM stands for Node Package Manager. It will be installed as a part NodeJS installation.

This command line utility is simple a package manager for JavaScript and node packages.

Using this utility we can download any JavaScript libraries and Node package from NPM repository.

We can choose other package managers as well. Maven, Nuget and Bower are some examples of same. Each of these package managers have its own specialty. For instance, Nuget is famous for downloading packages related to .NET.

NPM is intended towards mostly Node packages. Node packages are simply utilities created using Node. They can be simply downloaded and installed using NPM. Typescript compiler is one of the node package we will be installing in the next step.

Note: In this part we won’t explore anything related to NodeJS development. We installed Node mainly because of NPM. NPM will be used further in the series.

Discussion on Namespaces and Modularity problem in JavaScript

Before we go and start with Angular, we have to understand one problem of JavaScript and the standard solution implemented by the industry for it. Problem is Namespaces and Modularity.

What are Namespaces?

Namespaces let us group related code/functionality into one group. Similar or related functionalities/codes will be written as part of one Namespace in such a way that, it is completely isolated from other Namespace.

Each Namespace will have its own scope and it always executes within its own scope unlike other code which executes in the global scope. It makes variables, functions, classes, etc. declared in a one Namespace invisible to other Namespace unless they are explicitly exported

By default, in the world of JavaScript everything we create belongs to global namespace. Just try to imagine a situation where we try to reuse multiple external JavaScript files in a single HTML file. If everything is global then there is a high possibility of having conflicts between the stuff defined inside those JavaScript files. Multiple files may end up into having same functions defined inside them but with different logic.

OOP languages such as C# and Java have provision for creating Namespaces which is missing in JavaScript. There is no readymade keywords to create Namespaces in JavaScript but it can be achieved by writing custom “logic”. Let me show you one way to implement Namespace in JavaScript with the help of “function scope” and IIFE.

IIFE stands for "Immediately Invoking Function Expression." It’s a function which gets invoked as soon as it get created.

Here is a quick look at simple IIFE.

(function () {
    alert('a');
})();

As you can see, we have a simple anonymous function which will execute immediately.

Let’s do a quick demo on JavaScript Namespace.
(It’s not compulsory to do the below practical in order to learn Angular. If you wish, simply read each of the step and proceed.)

Step 1 – Setup a folder

Create a new folder "JsNamespaceExample" and create three things inside it. One html file called Test.html and two JavaScript files called "Reusable.js" and "Index.js".

Step 2 – Create Namespace with functionality

Open the "Reusable.js" file and create two simple functions "add" and "sub" and wrap them inside IIFE.

(function () {
    function add(x, y) {
        alert(x+y);
    }
    function sub(x, y) {
        alert(x-y);
    }
})();

Now the "add" and "sub" functions are private to IIFE. No way it get replaced or overridden by someone else’s code. J

Step 3 – Expose public functions

It’s going to be very easy. First let’s look at the code.

var MathsNameSpace;
(function (p) {
    function add(x, y) {
        alert(x+y);
    }
    function sub(x, y) {
        alert(x-y);
    }
    p.add = add;
})(MathsNameSpace || (MathsNameSpace = {}));

Let’s understand above logic.

  1. IIFE accepts one parameter.
  2. JavaScript is dynamic in nature, so "p.add=add" will add a new property "add" to "p"
  3. p.add will point to the add function defined inside IIFE.
  4. While invoking IIFE, global variable is passed as parameter.
  5. It means finally, that global variable will have a property called add, which will point to add function defined inside the IIFE.

Step 3 – Invoke Namespace functions

Open the Index.js file and put the following code inside it.

MathsNameSpace.add(1, 2);

As you can see, the Global variable defined inside "Reusable.js" is used inside "Index.js"

Step 4 – Setup HTML

Open Test.html and write down below html snippet inside it.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="Reusable.js"> </script>
    <script src="Index.js"> </script>
</head>
<body>
</body>
</html>

Step 5 – Execute and Test

Simply open the Test.html file in some brower.

If you haven’t understood the above logic for achieving Namespaces then no issue at all. Just move ahead. In industry lot of such solutions exists with different syntax and logic. Later in the stage, we will look into TypeScript which will make working with Namespace very easy task.

What is modularity?

Modularity means grouping our application code/functionality into multiple modules. Similar or related functionalities/code will be written as part of one module in such a way that, it is completely isolated from other modules.

Each Module will have its own scope and it always executes within its own scope unlike other code which executes in the global scope. It makes variables, functions, classes, etc. declared in one module invisible to other module unless they are explicitly exported

Is Modules == Namespaces true?

Not at all. Modules also take care of dependency management.

When it comes to Namespaces, developers need to take care of all dependencies manually. For instance, in the last demo you must have noticed, in the HTML file we manually included all the JavaScript files in proper sequence (first "reusable.js" and then "Index.js").

If we include "Index.js" before "reusable.js" or if we include only "index.js we won’t get the expected output.

Try to think about a scenario where a hierarchy is too big. Let’s say we have something like the following:

  1. Namespace1 is dependent on Namespace2 and Namespace3
  2. Namespace2 is dependent on Namespace 4 and Namespace 5
  3. Namespace4 is dependent on Namespace6

In this situation we should include Js files in following order.

  1. Namespace6
  2. Namespace5
  3. Namespace4
  4. Namespace3
  5. Namespace2
  6. Namespace1

In such scenarios Namespacing won’t be enough. We need some better solution. Solution is Modules which also take care of dependency management.

JavaScript doesn’t have any support for modularity as of now. ES2015 (new version) have built in module support but unfortunately we cannot rely on it 100%. As of now ES2015 is not supported by all the browsers.

In the JavaScript world (at least as of now) modularity can be achieved logically with the help of two concepts.

  • Module formatters - It’s the format in which we will write code. AMD and Common JS are two examples of Module formatters. It’s simply a standard way of encapsulating application logic.
  • Module loaders – It’s the library which contain APIs for working with module formatters. SystemJs and requireJs are two examples of module loaders.

Don’t get tense if you didn’t understood the definition. J

Simply proceed, look at the demo and after that again comeback and read the definition.
(Once again, it’s not compulsory to try out this practical. Just go through the steps. Main motive of this practical is give you a glimpse of code you are supposed to write in order to get support for modularity in JavaScript. Don’t get too much into the syntaxes. Later in the series we will see the easier way to achieve the same with the help of TypeScript.)

Demo on AMD with System JS

Step 1 – Setup a folder

Create a new folder called "AmdExample" and create three things inside it. One html file called Test.html and two JavaScript files called "Reusable.js" and "Customer.js".

Step 2 – Download Module loader

Open command promt and navigate to "AmdExample" Folder. Download "systemjs" library using npm as follows.

npm install systemjs

Note:

Command is case sensitive. Its systemjs not systemJs

It will create a new sub folder inside the "AmdExample" folder and place the downloaded SystemJs library inside it.

Step 3 – Define Reusable Module

Create two functions getValue and getValue2 inside "Reusable.js" file in AMD format.

define(["exports"], function (exports) {
    function getValue() {
        return getValue2();
    }
    exports.getValue = getValue;
    function getValue2() {
        return "Sukesh Marla";
    }
});

In above code we created a new JavaScript Module called “reusable”. (File name become the Module name) and the formatter used was AMD format.

  1. We have to invoke the “define” function
  2. “define” function expects two parameter
    1. Dependencies – for instance in our case it need access of “exports”
    2. A function – which encapsulates our logic and which get dependency as parameter.

Both “define and export” keywords are defined inside SystemJs.

Step 4 – Define Customer Module

Put the following code inside Customer.js.

define(["exports", './reusable.js'], function ( exports, reusabl) {
    "use strict";
    alert(reusabl.getValue());
});

This time we created a JavaScript Module called "customer".

You can also see that "customer" Module is using "reusable" Module

Step 5 – Import startup file

Put following HTML in Test.html.

<!DOCTYPE html>
<html>
<head>
    <title></title>
	<meta charset="utf-8" />
    <script src="../../node_modules/systemjs/dist/system.js"></script>
    <script>
        SystemJS.import('./Customer.js');
    </script>

</head>
<body>

</body>
</html>

As you can see "Customer.js" is loaded into Test.html using SystemJS.

Once loaded, statements inside Customer.js will start executing line by line.

Customer.js is dependent on Reusable.js hence at run time Reusable.js will be downloaded.

Step 6 – Execute

Now in order to test such examples, we have to host this web project. Simply host these sample in a Web Server of your choice and then send request for Test.html file.

For this and future demos, we will use a Node Module called "http-server". It’s a very simple command line http server. It require no configuration at all.

Use the following command to install it.

npm install http-server -g

As you can see this time we used "-g" as a flag with "npm install".

This flag will be used when we want to install a Node Module which is going to be directly used inside the command line. After installation its binaries end up in your PATH environment variable as well.

Once installation is complete, simply write "http-server" in command prompt. It will start a webserver pointing same folder. Once the server is started, open the browser and send request to Test.html file.

Compatibility between Module formatter and module loader

All module loaders won’t support all module formatters. For instance, requireJs supports only AMD format whereas SystemJs supports lot of module formatters including AMD and Common JS.

Let’s have two quick demos to understand Module loaders and Module formatters properly.

What is Angular and Why Angular?

The simplest definition for angular should be, "It’s a JavaScript framework for building HTML based dynamic applications".

Note: Don’t get confused between the word library and word framework.

Library is simply a collection of reusable APIs whereas Framework is a complete platform for building an application.

A library will provide some ready to use functions (or classes) whereas a framework will help developers with compilers, utilities like garbage collection, a complete execution runtime and many reusable libraries. Best example for framework will be .NET or Java framework.

In the end of 10th day you will automatically realize the reason for calling Angular as framework instead of library.

Using Angular as our front end framework add lot of value to our front end development.

  • As you know JavaScript is mainly used for manipulating and creating HTML at client side. Angular makes it easy.
  • Angular allows us to develop our UI in a very structured way. Unlike in traditional development approach where HTML contents will be directly accessed in the code (JavaScript code) and manipulated, Angular let us do it a very loosely coupled way. We can see a clear separation between UI (HTML) and UI logic (JavaScript code).
  • Angular allows us extend existing HTML (UI) without affecting JavaScript logic.
  • Angular allows us to develop our UI in a Component oriented style. It’s a new standard in the HTML 5 world which asks us to develop UI as collection of reusable web components.

Don’t scratch your head too much to understand these points. I request you to complete your 10 day series and after that go through these points again.

What is TypeScript?

Typescript is a compiled language which will generate JavaScript on compile.

Generated JavaScript will be same traditional JavaScript code.

To make it simple, "We will write our code in TypeScript. Compile it and generate the JavaScript and simply use that auto-generated JavaScript in our HTML instead of manually writing JavaScript."

How to setup TypeScript?

Open the command prompt and write following command.

npm install typescript -g

In order to test the installation, simply write tsc in command prompt and press enter. You should get something like below.

If you get message "npm is not recognized as an internal or external command," Install NodeJS once again as an administrator.

If you get message, "tsc is not recognized as an internal or external command," open command prompt as an administrator and try the above command again.

Why TypeScript?

Many of you must be wondering why we should use TypeScript instead of JavaScript if our ultimate goal is JavaScript only.

TypeScript will give us the following benefits

  1. Learning curve

    Learning TypeScript is relatively easy. It won’t be like learning a new programming language from the scratch. If you know JavaScript, you know TypeScript to some extent. People coming from C++ background feel C# and Java syntaxes easy. Because both C# and Java inherit its syntaxes from C++.

    In the same way TypeScript has inherited its syntaxes from JavaScript. Hence TypeScript is called as super script of JavaScript.

    For example, functions in Typescript can be defined as follows.

    function myFunction(a,b){
    	return a+b;
    }

    If condition will be written as follows.

    if(b== "A"){
    }

    The above code snippet clearly depicts the similarity between syntaxes in JavaScript and TypeScript. We will look into the more TypeScript demos in detail in upcoming section.

  2. Compiled environment

    JavaScript is not a compiled language but TypeScript is. It makes our life easy by reducing lot of run time errors.

    Let’s look at three JavaScript examples.

    Example 1

    var a=1;
    console.log(a); //display 1
    a= "Sukesh";
    console.log(a); //display "Sukesh"

    As you can see, there is no type safety in JavaScript or in simple words there is no fixed datatype. One variable which is integer right now, may be string in later case. It opens the door for lot of run time errors.

    TypeScript on the other hand let us specify the exact datatype while declaring variables. In case invalid assignment is done it will end up into compile error.

    Example 2

    function myFunction(a,b){
    ...
    }
    myFunction();
    myFunction(1,2,3)

    Function is defined with two parameters and invoked twice. First time it was invoked without any parameter and second time with three parameters.

    As JavaScript is not a compiled language it simple works and may end up into some kind of runtime exception.

    TypeScript won’t allow this. It will generate compile error if such code is written.

    Example 3

    function myFunction(a,b){
    console.log ('a');
    }
    function myFunction(a,b,c){
    console.log ('b');
    }
    myFunction(1,2); // display b
    myFunction(1,2,3); // display b

    As you can see we have two functions with same name but with different parameters. Many will call it function overloading. Question is, do we have function overloading in JavaScript? No we don’t. No matter how many parameters you pass while invoking function, only one of them keep invoking and another one simply be ignored.

    TypeScript as of now don’t support method overloading but it won’t even let you write two functions with same name. It will throw compile error.

  3. New features

    Right now we are limited to "ES5" (current JS standard) features because all browsers are not completely compatible right now with ES2015.

    Typescript allows us to do lot of things which we cannot do normally in JavaScript. When compiled it will generate appropriate logic for us.

    For example, Typescript has support for modules whereas JavaScript won’t. Code written using TypeScript Module will simply generate AMD or "CommonJS" code.

    (We will be looking at a demo very soon)

  4. Easy migration

    At the end of the day, the browser will be executing JavaScript only. If you think about manually writing JavaScript instead of using TypeScript, it becomes difficult to migrate code to new ES standard in the future as migration leads to lot of rewriting.

    In the case of TypeScript it will be a one step process.

    (We will be looking at a demo very soon)

Fundamentals of TypeScript

Now let’s do some demo on TypeScript.

Initial setup

  • Make sure NodeJS is installed
  • Make sure TypeScript is installed
  • Prepare your Editor. We will be required one Editor to write code. You can choose editor of your choice. You can go with Eclipse, Visual Studio, Web Storm, and Visual Studio Code or even in the worst case notepad. (Any editor which let us write JavaScript code, can be used for TypeScript as well).

    For demonstration I will be using Visual Studio code, which is a free editor from Microsoft. It can be downloaded from below link.

    https://code.visualstudio.com/

Demo 1 –var example

In TypeScript we can declare variables using one of the following keywords.

  • var
  • let
  • const

"var" is the traditional way of declaring variables in JavaScript. Same is inherited in TypeScript. Let’s do some demos on "var".

Step 1 – Create TypeScript file

  • Open Visual studio Code
  • Select File>New File from Menu.

    It will simply launch editor.

  • Now select File>>Save OR press Ctrl-S. Select the folder of your choice, set "File name" to "varExample.ts", select "Save as type" to "TypeScript" and click ok.

Step 2 - Write the code

Write the following code inside it.

var myVar= "Sukesh Marla";
console.log(myVar);

Above code seems like JavaScript code, but in reality it’s a TypeScript code.

Step 3 – Compile

  • Open command prompt and navigate to your TypeScript source folder.
  • Simply write the following command.
    tsc varExample.ts

    It will generate a new file in same folder called varExample.js

Step 4 – Test the file

You can test this file in two ways.

  1. Create HTML file, insert the generated ".js" file inside it using script tag and execute the HTML file.

    OR

  2. Execute js file using node. For this open command prompt, navigate to Source folder and write following command.
    node varExample.js

    It will execute the JS file and show the output in command line.

Step 5 – Try one more example

Change the code to following.

console.log(a);

Now compile it like before. It will end up into following error.

As you can see, we will get to all problem before execution phase itself.

Step 6 – Try one more example

Now change code to following and compile it again.

console.log(a);
var a;

This time it will compile. Now execute generated "varExample.js" using "node" command like before.

Following output will be displayed.

Were you expecting the same error as before? When variables are declared with "var" declarations will be moved up. In simple words no matter in which line variable is declared it will be available from line 1. This concept is called hoisting.

Step 7 – Try one more example

Now change code to following.

console.log(a);
var a=5;

Compile and execute.

Why value is not 5? I said variable declarations will be hoisted not assignments.

Just to make it easy, try to imagine as var a=5; is internally written as two statements. var a; and a=5;

From these two statements first statement will be hoisted.

Step 8 – Try one more example

Now change code to following.

console.log(a);
var b=5
if(b>2){
    var a=5;
}

Output will be something like below.

Is it unexpected?

When variables are declared with "var" keyword then there won’t be any block level scoping. Normally in other programming languages, if a variable is declared inside the block it won’t be available outside the block but this is not true in case of JavaScript.

Step 9 – Try one more example

Let’s try one more example of block level problem. Try the following code.

var b = 5;
if (b > 2) {
    var b = 6;
    console.log(b);
}
console.log(b);

Compile it. Generated JavaScript will be exactly as the source. Execute it using Node.

Output will be as follows.

So, let’s list down the problem with "var"

  • Variables get hoisted
  • No block level scoping

This problem can be solved easily using the new "let" keyword.

Let have few demos on "let" keyword.

Demo 2 – let example

Step 1 – Create TypeScript file

Follow the above step and create a TypeScript file called "letExample.ts" and check the below code.

Step 2 - Write the code

Try the following code and check the output.

let myVar= "Sukesh Marla";
console.log(myVar);

Step 3 - Compile

Compile it using tsc and check the generated output file

As you can see, in final JavaScript code "let" become "var" because current JavaScript (ES5) only have support for var. If you are worried about "let" becoming "var", don’t worry. TypeScript does it very smartly. In one of the upcoming example you will see that.

Step 4 – Try one more example

Try the following code and check the output.

console.log(a);
let a;

It will end up into error because in case of "let", variable must be declared first and then should be used.

Note: By default TypeScript is configured to generate output even if there is a compile error. It simply generate the statement as it is in output file (which has error). We will learn how to override this configuration later in the stage.

Step 5 – Try one more example

Try the following code and check the output.

console.log(a);
var b=5
if(b>2){
    let a=5;
}

It will end up into error because in case of "let", variable will be considered as blocked level variables.

Step 6 – Try one more example

Try with following code.

var b=5
if(b>2){
   let b=6;
   console.log(b);
}
console.log(b);

After compilation, generated JavaScript look like following.

var b = 5;
if (b > 2) {
    var b_1 = 6;
    console.log(b_1);
}
console.log(b);

As you can see, TypeScript compiler is very smart. Current JavaScript only have "var" so in generated code it simply changed the variable name itself.

So in short, using "let" instead of "var" solves the hoisting problem and block level scoping problem. Compile errors will give you an indication that something is wrong in code.

Demo 3 – const example

"const" is same as let with one additional behavior. Once value is assigned it cannot be changed.

Follow the above step and create a TypeScript file called "constExample.ts" and check the below code.

const a=5;
a=6;

Compile it, we will get following error.

Demo 4 – Basic data types

Unlike JavaScript TypeScript is Type Safe. Here we have an option to specify data type while declaring variable.

Follow the above step and create a TypeScript file called "typeExample.ts" and check the below code.

let n:number=5;
let s:string="Sukesh";
let b:boolean=true;
n="A";
s=5;
b="A";

On compilation following error will occur.

Once the variable is declared with data type it won’t allow any invalid values.

Are you pondering about previous where variables are declared without data type?

Now there are two variations.

  1. Variable will be declared with either var or let and assigned with value on the same line.
  2. Variable will be declared with either var or let and assigned with value in a different line.

Let’s try out the first variation

let n =5;
n="A";

Compile it. It will generate following error.

As you can see, datatype is integer. When variables are declared without datatype there datatype will be decided based on first assignment. This is called "Type Inference".

Second variation we will try after Demo 5.

Demo 5 – Dynamic TypeScript

As I said before, TS is a super script of JS. Whatever we can do in JS we can do in TS as well.

JavaScript is dynamic in nature whereas TypeScript on the other hand provides a type safe environment for client side developers.

TypeScript have its own features which makes dynamic coding easier. We will explore many of these features though out this course.

"any" datatype is one of those features. It let us treat variables in dynamic way.

Check the below code.

Create a TypeScript file "dynamic.ts" with following code snippet.

let n:any=5;
console.log(n+1);
n="A";
console.log(n+1);

Compile it and you will notice that nothing will break.

Execute it using Node command. Output will be as follows.

As you can see, a variable which was integer in beginning becomes string in the later stage.

Now let’s try the second variation we spoke about in Demo 4.

Check the below code

let n;
n =5;
n="A";

You will notice that code will simply compile. By default when variables are declared without datatype and not assigned with any value it becomes "any" type.

Note:

Compiled and type safe environment always reduces the number of run time errors. Hence using "any" is not a best practice always. Use it when its must. In all other situations try to stick with Specific datatypes.

Demo 6 – Generic arrays

JavaScript arrays are dynamic in nature but in TypeScript we have support for Generic arrays.

Follow the above step and create a TypeScript file called "arrayExample.ts" and check the below code.

let values:Array<number>=new Array<number>();
values.push(1);
values.push(2);
values.push("Sukesh");

Here is the compile result.

As you can see, we cannot add any invalid value inside array.

Note: We can take advantage of "any" with arrays too. Simply declare variable of type of Array<any> and it will become dynamic array.

Demo 5 – Functions

As discussed before, TypeScript provides us a compiled environment. This is even true for functions.

Example 1 – Force to return

Try the following code.

function myFunction():number {  
}

On Compilation we will get following error.

TypeScript is forcing function to return value.

Example 2 – Parameter checking

Now try following code.

function myFunction(x:number,y:number):number {
    return x+y;
}
myFunction(1,2,3);

On Compilation we will get following error.

TypeScript is forcing to invoke function with proper parameters.

Example 3 – Function duplication

Try the below code.

function myFunction(x:number,y:number):number {
    return x+y;
}
function myFunction(x:number,y:number,z:number):number {
    return x+y;
}

On Compilation following error will occur.

TypeScript is not allowing to create two functions with same name.

Example 4 – Optional parameter

With the help of optional parameters we can make TypeScript functions just behave like JavaScript functions. For defining optional parameters we have to put "?" symbol after parameter name.

Check the below code.

function myFunction(x:number,y?:number):void {
    console.log(x);
    console.log(y);
}
console.log('With two parameters');
myFunction(1,2);

console.log('With 1 parameter');
myFunction(1);

Compile it. It will succeed.

As you can see, same function can be invoked with two parameters as well as with only one parameter because second parameter is an optional parameter.

Here is the output.

Example 5 – Default parameter

Typescript functions can also be defined with default parameters.

Check the below code.

function myFunction(x:number,y:number=5):void {
    console.log(x);
    console.log(y);
}
console.log('With two parameters');
myFunction(1,2);

console.log('With 1 parameter');
myFunction(1);

Compile it. It will succeed.

Here is the output.

Example 7 – Without return type

Creating function without specifying a return type is same as having "any" as return type.

Check the below code.

function myFunction(x:number,y:number){
  if(x>y)
      return  "Sukesh";
  }
  else if(y>x){
      return 55;;
  }
}
console.log(myFunction(1,2));
console.log(myFunction(2,1));
console.log(myFunction(2,2));

Compile it and check the output.

In above case function have three possibilities. Return string, return int or return nothing.

Output will be as follows.

Example 7 – Demo with Rest Parameter

Rest parameter make our life easy when we want to define a function having array as a parameter. Create a TypeScript function as follows.

function myFunction(x:Array<number>):number{
  let sum:number=0;
  for (let e of x) {
      sum+=e;
  }
  return sum;
}
let values:Array<number> =new Array<number>();
values.push(1);
values.push(2);
values.push(3);
console.log(myFunction(values));

Now the same code can be rewritten using Rest Parameter as follows.

function myFunction(...x:Array<number>):number{
  let sum:number=0;
  for (let e of x) {
      sum+=e;
  }
  return sum;
}
console.log(myFunction(1,2,3));

As you can see, just add “...” before parameter name and it will become Rest parameter and after that pass multiple values as multiple parameters, no need to explicitly create the array.

Note: We cannot have two rest parameters in one function.

If you liked this article, dont forget to vote for it.

https://www.codeproject.com/script/Surveys/Vote.aspx?srvid=2051

Summary

Here it ends the part 1 of day 1. Take a power nap, have some snacks, play some games, get relax and continue with part 2.

Stay tuned.

I am in twitter, Facebook, linked in.

Want to know more about me. Visit here

www.sukesh-marla.com

www.justcompile.com

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Marla Sukesh
Instructor / Trainer Train IT
India India
Learning is fun but teaching is awesome.

Code re-usability is my passion ,Teaching and learning is my hobby, Becoming an successful entrepreneur is my goal.

By profession I am a Corporate Trainer.
I do trainings on WCF, MVC, Business Intelligence, Design Patterns, HTML 5, jQuery, JSON and many more Microsoft and non-Micrsoft technologiees.

Find my profile here



My sites



@Twitter
@Facebook

You may also be interested in...

Pro
Pro

Comments and Discussions

 
Question10 on 10, Thanks!!! Pin
Member 1353640523hrs 38mins ago
memberMember 1353640523hrs 38mins ago 
Question'http-server" is not recognized? Pin
Member 1315531425-Oct-17 23:48
memberMember 1315531425-Oct-17 23:48 
BugExample 7 – Without return type Pin
Steven Diaz G.20-Oct-17 12:34
memberSteven Diaz G.20-Oct-17 12:34 
QuestionHello sir need some clarification Pin
dhirensolanki7-Oct-17 7:04
memberdhirensolanki7-Oct-17 7:04 
QuestionNeed all the link of 10 days of angular js 2 Pin
Member 1341384718-Sep-17 8:09
memberMember 1341384718-Sep-17 8:09 
QuestionWow!! Impressive content. Pin
Matt Slay11-Sep-17 15:10
memberMatt Slay11-Sep-17 15:10 
AnswerRe: Wow!! Impressive content. Pin
Marla Sukesh11-Sep-17 23:59
mvp Marla Sukesh11-Sep-17 23:59 
QuestionIs there an error in what you trying to convey? Pin
KentsCode9-Sep-17 1:49
memberKentsCode9-Sep-17 1:49 
AnswerRe: Is there an error in what you trying to convey? Pin
Marla Sukesh10-Sep-17 23:09
mvp Marla Sukesh10-Sep-17 23:09 
PraiseVery good tutorial Pin
Claudio González8-Sep-17 11:03
memberClaudio González8-Sep-17 11:03 
GeneralRe: Very good tutorial Pin
Marla Sukesh8-Sep-17 11:18
mvp Marla Sukesh8-Sep-17 11:18 
QuestionUncaught exception in system.js Pin
Mark McArthey8-Sep-17 5:41
memberMark McArthey8-Sep-17 5:41 
AnswerRe: Uncaught exception in system.js Pin
Marla Sukesh8-Sep-17 6:40
mvp Marla Sukesh8-Sep-17 6:40 
GeneralRe: Uncaught exception in system.js Pin
Mark McArthey8-Sep-17 7:00
memberMark McArthey8-Sep-17 7:00 
GeneralRe: Uncaught exception in system.js Pin
Marla Sukesh8-Sep-17 7:02
mvp Marla Sukesh8-Sep-17 7:02 
GeneralRe: Uncaught exception in system.js Pin
Mark McArthey8-Sep-17 9:47
memberMark McArthey8-Sep-17 9:47 
GeneralRe: Uncaught exception in system.js Pin
Marla Sukesh8-Sep-17 11:17
mvp Marla Sukesh8-Sep-17 11:17 
QuestionMany thanks! Pin
ade_m8-Sep-17 3:50
memberade_m8-Sep-17 3:50 
AnswerRe: Many thanks! Pin
Marla Sukesh8-Sep-17 6:38
mvp Marla Sukesh8-Sep-17 6:38 
QuestionWrong filename Pin
Member 117408557-Sep-17 22:49
memberMember 117408557-Sep-17 22:49 
AnswerRe: Wrong filename Pin
Marla Sukesh7-Sep-17 23:16
mvp Marla Sukesh7-Sep-17 23:16 
BugRemove quotation mark from code example Pin
Hans Zijlstra7-Sep-17 6:54
memberHans Zijlstra7-Sep-17 6:54 
GeneralRe: Remove quotation mark from code example Pin
Marla Sukesh7-Sep-17 21:15
mvp Marla Sukesh7-Sep-17 21:15 
SuggestionA few 'cosmetic' corrections Pin
cBaldo31-Aug-17 6:20
membercBaldo31-Aug-17 6:20 
GeneralRe: A few 'cosmetic' corrections Pin
Marla Sukesh5-Sep-17 3:04
mvp Marla Sukesh5-Sep-17 3:04 
QuestionBug: Error when installing typescript Pin
Dibu Jean Johnson22-Aug-17 0:44
memberDibu Jean Johnson22-Aug-17 0:44 
AnswerRe: Bug: Error when installing typescript Pin
Marla Sukesh22-Aug-17 9:31
mvp Marla Sukesh22-Aug-17 9:31 
PraiseHave been waiting for this Pin
Mutahar15-Aug-17 2:27
memberMutahar15-Aug-17 2:27 
GeneralRe: Have been waiting for this Pin
Marla Sukesh18-Aug-17 0:09
mvp Marla Sukesh18-Aug-17 0:09 
GeneralMy vote of 5 Pin
TinTinTiTin11-Aug-17 1:50
memberTinTinTiTin11-Aug-17 1:50 
GeneralRe: My vote of 5 Pin
Marla Sukesh11-Aug-17 7:18
mvp Marla Sukesh11-Aug-17 7:18 
GeneralMy vote of 5 Pin
Raul Iloc10-Aug-17 10:47
professionalRaul Iloc10-Aug-17 10:47 
GeneralRe: My vote of 5 Pin
Marla Sukesh10-Aug-17 20:08
mvp Marla Sukesh10-Aug-17 20:08 
PraiseAngular Tutorial Pin
Member 800608931-Jul-17 6:11
memberMember 800608931-Jul-17 6:11 
GeneralRe: Angular Tutorial Pin
Marla Sukesh31-Jul-17 20:32
mvp Marla Sukesh31-Jul-17 20:32 
PraiseThank you Pin
Member 1197642228-Jul-17 5:25
memberMember 1197642228-Jul-17 5:25 
GeneralRe: Thank you Pin
Marla Sukesh28-Jul-17 20:45
mvp Marla Sukesh28-Jul-17 20:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171114.1 | Last Updated 25 Oct 2017
Article Copyright 2017 by Marla Sukesh
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid