This is Day 1 of a 10 day series on the latest version of Angular - it is very basic and mostly on JavaScript and TypeScript.
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 frameworks at this time. The Angular. Hope you all enjoy this 10 day journey. We will learn the 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 an 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 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 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
- Day 1 – Part 1
- Day 1 – Part 2
- Day 2
- Day 3
- Day 4 – Part 1
- Day 4 - Execution Trick
- Day 4 – Part 2
- Day 4 – Part 3
- Day 5 (Coming soon)
- Day 6 (Coming soon)
- Day 7 (Coming soon)
- Day 8 (Coming soon)
- Day 9 (Coming soon)
- Day 10 (Coming soon)
Contents – Day 1 – Part 1
What is JavaScript and Why JavaScript?
In almost all my training, I ask this question and most of the time, I hear "For validation".
JavaScript is definitely more than that. HTML is the basic necessity of every web application. No matter whether you are a .NET or Java developer, without HTML you cannot create a web application.
The biggest limitation of HTML is that it is static. If you create an HTML page displaying "Hello world
" in bold, it will always display the same output, no matter how many times you refresh the page.
To overcome this static limitation, we used to take the help of Server Side technologies like PHP, ASP.NET, etc. These server side technologies generate different HTML on every request and send back and thus lead to a full fledged dynamic application.
Important Note
To learn Angular, basic knowledge on JavaScript and HTML is a must. When I say basic knowledge, it's not just theoretical. It should be theory + practical. You can check out the following links to get some basic idea on the same:
What’s the Problem With This Traditional Methodology?
The Problem is in the modern era, competition is huge. All businesses are trying to make their web app better than their competitors' 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 case of most of apps):
- It handles client requests
- Get data from different places (may be from Database, Services, etc.)
- Execute some logic on that data
- Generate HTML
- 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 an 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 the cloud environment. In the cloud, server costs will be based on usage. We will be charged based on how much RAM and hard disk 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 overall web experience."
Introduction to NodeJS
As I said, JavaScript is mainly used for manipulating and creating HTML dynamically.
NodeJS took JavaScript to the 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 that are required for development and execution.
Now we can develop such applications using JavaScript too and for that, we will require NodeJS. You can find the NodeJS setup at 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 simply 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 the same. Each of these package managers has 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 packages 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 the 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 are 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 gets 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 steps 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 gets replaced or overridden by someone else’s code.
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 the above logic.
- IIFE accepts one parameter.
- JavaScript is dynamic in nature, so "
p.add=add
" will add a new property "add
" to "p
". p.add
will point to the add
function defined inside IIFE. - While invoking IIFE, global variable is passed as parameter.
- 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 the 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 browser.
If you haven’t understood the above logic for achieving Namespaces, then there is 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 a 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:
Namespace1
is dependent on Namespace2
and Namespace3
Namespace2
is dependent on Namespace4
and Namespace5
Namespace4
is dependent on Namespace6
In this situation, we should include Js files in the following order:
Namespace6
Namespace5
Namespace4
Namespace3
Namespace2
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) has 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 contains APIs for working with module formatters. SystemJs and requireJs are two examples of module loaders.
Don’t worry if you didn’t understand the definition.
Simply proceed, look at the demo and after that, again come back and read the definition.
(Once again, it’s not compulsory to try out this practical. Just go through the steps. The 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 caught up in 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 prompt 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 the above code, we created a new JavaScript Module called “reusable
”. (File name becomes the Module name) and the formatter used was AMD format.
- We have to invoke the “
define
” function. - “
define
” function expects two parameters:
- Dependencies – for instance, in our case, it need access of “exports”
- A function – which encapsulates our logic and which gets 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 the 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 requires 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 to the 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.
At the end of the 10th day, you will automatically realize the reason for calling Angular as framework instead of library.
Using Angular as our front end framework adds a lot of value to our front end development.
- As you know, JavaScript is mainly used for manipulating and creating HTML on the 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 lets us do it in a very loosely coupled way. We can see a clear separation between UI (HTML) and UI logic (JavaScript code).
- Angular allows us to extend the 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 a 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 the 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 the 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:
- Learning curve
Learning TypeScript is relatively easy. It won’t be like learning a new programming language from scratch. If you know JavaScript, you know TypeScript to some extent. People coming from C++ background find C# and Java syntaxes easy because both C# and Java inherit their syntax from C++.
In the same way, TypeScript has inherited its syntax from JavaScript. Hence, TypeScript is called as super script of JavaScript.
For example, function
s 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 more TypeScript demos in detail in the upcoming section.
- Compiled environment
JavaScript is not a compiled language but TypeScript is. It makes our life easy by reducing a lot of run time errors.
Let’s look at three JavaScript examples.
Example 1
var a=1;
console.log(a);
a= "Sukesh";
console.log(a);
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 a lot of run time errors.
TypeScript, on the other hand, lets us specify the exact datatype while declaring variables. In case invalid assignment is done, it will end up in a 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 is invoked without any parameter and second time with three parameters.
As JavaScript is not a compiled language, it simple works and may end up in 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);
myFunction(1,2,3);
As you can see, we have two functions with the same name but with different parameters. Many will call it function overloading. The 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 keeps invoking and another one will simply be ignored.
TypeScript as of now doesn’t support method overloading but it won’t even let you write two functions with the same name. It will throw a compile error.
- 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 a 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.)
- 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 a 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 require one editor to write code. You can choose the 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 lets 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 the below link.
https://code.visualstudio.com/
Demo 1 – var Example
In TypeScript, we can declare variables using one of the following keywords.
"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
Step 2 - Write the Code
Write the following code inside it:
var myVar= "Sukesh Marla";
console.log(myVar);
The above code seems like JavaScript code, but in reality, it’s a TypeScript code.
Step 3 – Compile
Step 4 – Test the File
You can test this file in two ways:
- Create HTML file, insert the generated ".js" file inside it using
script
tag and execute the HTML file.
OR
- Execute js file using node. For this open command prompt, navigate to Source folder and write the 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 the following:
console.log(a);
Now compile it like before. It will end up in the 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 the following and compile it again.
console.log(a);
var a;
This time, it will compile. Now execute the generated "varExample.js" using "node
" command like before.
The 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 the 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, the first statement will be hoisted.
Step 8 – Try One More Example
Now change code to the 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's 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
" becomes "var
" because current JavaScript (ES5) only has support for var
. If you are worried about "let
" becoming "var
", don’t worry. TypeScript does it very smartly. In one of the upcoming examples, 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 in an 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 generates 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 in an error because in case of "let
", variable will be considered as blocked level variables.
Step 6 – Try One More Example
Try with the following code:
var b=5
if(b>2){
let b=6;
console.log(b);
}
console.log(b);
After compilation, the generated JavaScript looks like the 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 has "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 the 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, the 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:
- Variable will be declared with either
var
or let
and assigned with value on the same line. - 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 the 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 has 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 lets us treat variables in dynamic way.
Check the below code.
Create a TypeScript file "dynamic.ts" with the 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 the 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 it's a 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 a 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 the following error:
TypeScript is forcing function to return value.
Example 2 – Parameter Checking
Now try the following code:
function myFunction(x:number,y:number):number {
return x+y;
}
myFunction(1,2,3);
On Compilation, we will get the 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, the 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, the same function can be invoked with two parameters as well as with only one parameter because the 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 the 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 the above case, function has three possibilities. Return string, return int or return nothing.
Output will be as follows:
Example 7 – Demo with Rest Parameter
Rest parameter makes 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, don't forget to vote for it.
If you are here at this line of article, also do go through the below Angular video:
Summary
Here ends Part 1 of Day 1. Take a power nap, have some snacks, play some games, relax and continue with part 2.
Stay tuned!
History
- 27th July, 2017: Initial version