What is React and why you should learn it!

If you’ve been following my blog, you’ve noticed that I have a number of tutorials and courses about Angular. I never liked Angular 1 or AngularJS but thought Angular 2 is a framework in the right direction. So I adopted it since its beta release. Recently, however, I started using React and fell in love with it! So, over the next few weeks, I’ll be writing a series of posts about this awesome library. Let’s get started!

What is React?

React is a JavaScript library for building fast and interactive user interfaces.

It was developed at Facebook in 2011 and currently, it’s the most popular JS library for building user interfaces. Here’s a comparison of the top 3 libraries/frameworks for building user-interfaces: React, Angular and Vue:

React vs Angular vs Vue

As you can see, it is dominating the space. So, if you want to expand your job opportunities as a front-end developer, you should have it on your resume.


At the heart of all React applications are components.

A component is essentially a piece of the user interface. So, when building applications with React, we build a bunch of independent, isolated and reusable components and then compose them to build complex user interfaces.

Every React app has at least one component, which we refer to as the root component. This component represents the entire application and contains other child components. So, every React application is essentially a tree of components. If you’ve worked with Angular 2 or higher, this should sound familiar!

A Real Example

Here’s an example. Let’s imagine we want to build an application like Twitter. We can split this page into components like NavBar, Profile, Trends, and Feed. Here’s a representation of these components in a tree.

React Component Tree

So, on the top, we have App. This component has 4 children: NavBar, Profile, Trends, and Feed, which includes several Tweet components. Each Tweet component can include a Like component, which we can re-use on other pages or even in different applications!

So, as you see, each component is a piece of UI. We can build these components in isolation and then put them together to build complex user interfaces.

Show Me the Code!

OK, I know you’ve been curious what the code looks like. A component is typically (but not always) implemented as a JavaScript class that has some state, and a render method.

class Tweet { 
   state = {};
   render() { 
      // Here we return a React element 

The state here is the data that we want to display when that component is rendered. And the render method, as you can tell, is responsible for describing what the UI should look like. If a component doesn’t have a state, we can implement it using a pure function instead of a class. More on this later.

Virtual DOM

The output of this render method is a React element which is a simple, plain JavaScript object that maps to a DOM element. It’s not a real DOM element, it’s just a plain JS object that represents that DOM element in memory.

So, React keeps a light-weight representation of the DOM in memory. We refer to this as the virtual DOM. Unlike the browser or the real DOM, this virtual DOM is cheap to create. When we change the state of a component, we get a new React element. React will then compare this element and its children with the previous one, it figures out what is changed, and then, it’ll update a part of the real DOM to keep it in sync with the virtual DOM.

React vs Vanilla JavaScript/ jQuery

So, that means when building applications with React, unlike vanilla JavaScript or jQuery, we no longer have to work with the DOM API in browsers. In other words, we no longer have to write code to query and manipulate the DOM or attach event handlers to DOM elements.

const element = document.querySelector('#course');
element.addEventListener('click', ...);

We simply change the state of our components, and React will automatically update the DOM to match that state.

React vs Angular 2+

React and Angular are similar in terms of their component-based architecture. But Angular is a framework or a complete solution, while React is a library. It only takes care of rendering the view and making sure that the view is in sync with the state. That’s all React does, nothing less, nothing more! For this very reason, it has a small API to learn.

So, when building applications with React, we need to use other libraries for things like routing or calling HTTP services and so on. But this is not necessarily a bad thing, because you get to choose the libraries that you prefer as opposed to being fixed with what Angular gives you, which often breaks from one version to another!

That’s it for today. Stay tuned for the next post!


4 Modern JavaScript (ES6+) Features You Should Be Using Now

JavaScript has progressed a lot over the past few years. Whether you are new to JavaScript, or have some experience up your sleeves and want to quickly get up to speed with the most commonly used features in modern JavaScript, this post is for you.

In this post, I’m going to share with you the features I use on a daily basis. These features include:

  • Template literals
  • Let and Const
  • Arrow Functions
  • Destructuring

This is not a comprehensive list of all the new features since ECMAScript 2015 (ES6). But these are the 20% of features that you use 80% of the time. Plus, this article is a work in progress. I’ll be adding more features to this list. For now, I want to publish this today!

All these new features are natively supported in all modern browsers. If you want to try out any of the code snippets below, simply open up Chrome Developer Tools and type the code.

So, let’s get started!

Template Literals

Before ES6, we had to deal with these ugly string concatenations:

var name = 'Mosh'; 
var message = 'Hi ' + name + ',';

Now, with template literals (previously called template strings), we can define a string with placeholders and get rid of all those concatenations:

var name = 'Mosh'; 
var message = `Hi ${name},`;

Note that I’m using the backtick character here. As funny as it sounds, nobody knew what backticks were until Angular 2 was released! That’s the character before number 1 on your keyboard.

To add a placeholder in a template literal, we use the ${expression} syntax. You can replace “expression” with any JavaScript expressions. Here, we are adding the name variable there. You can also call a function or pass any JavaScript expressions that results in a value.

Another benefit of using template literals is that they can expand multiple lines. They are particularly useful when composing email messages:

var message = `
Hi ${name},

Thank you for joining my mailing list. 

Happy coding,

Let and Const

Prior to ES6, we used the var keyword to define variables. The scope of a variable defined using the var keyword is the entire enclosing function. Here’s an example:

function doSomething() {
   for (var x = 0; x < 5; x++) { 
      // Technically, x should only be scoped to this block because this is 
      // where we have defined x. 

   // But it turns out that x is available here as well! 
   console.log(x); // 5 

That’s not how most if not all other programming languages behave! Variables defined within a block should be scoped to that block only. In this example, x should not be accessible outside of the for block.

Another issue with the var keyword is that if you use it at the top level outside of a function, it creates a property on the global object:

var x = 1; 
console.log(window.x); // 1

ES6 introduced 2 new keywords for resolving these issues: let and const. Both these keywords define variables that are scoped to the containing “block” not “function”:

function doSomething() {
   for (let x = 0; x < 5; x++) { 
      // With the "let" keyword, now x is only accessible in this block.

   // x is out of the scope here
   console.log(x); // x is not defined  

With const we can define a constant. So we cannot reassign it later:

const x = 1; 
x = 2; // throws "Assignment to constant variable."

Also, unlike the var keyword, let and const don’t create a property on the global object if you use them at the top level:

let x = 1; 
console.log(window.x); // undefined 

So, here is what you should take away:

  • Ditch the var keyword. Use only let and const.
  • Prefer const to let. Use let only if you need to re-assign the identifier; otherwise, use const to prevent accidentally re-assigning a constant.

Arrow Functions

My favorite feature in ES6! Inspired by lambda expressions in C#, arrow functions give you a clean and concise syntax for writing function expressions. Here’s a function expression in ES5:

const square = function(number) { 
   return number * number; 

With arrow functions, we get rid of the function keyword and put a fat arrow (=>) between the parameters and the body of the function:

const square = (number) => { 
   return number * number; 

If our function is a one-liner and returns a value, we can drop the return keyword as well as the curly braces:

const square = (number) => number * number; 

Isn’t that much cleaner and more concise than the former syntax?

But wait, we can make this even shorter: If our arrow function includes only a single parameter, we can even drop the parenthesis:

const square = number => number * number; 

What if our arrow function doesn’t have any parameters? We need to use a pair of parenthesis:

const sayHello = () => { console.log('hello'); };

Arrow functions are particularly useful when you need to pass callback functions as arguments:

// ES5
var activeJobs = jobs.filter(function(job) { 
    return job.isActive; 

// ES6
const activeJobs = jobs.filter(job => job.isActive); 

Arrow functions, unlike normal functions,  don’t rebind this.  Does this pattern look familiar to you?

// ES5
function onSubmit() { 
    // Keep a reference to "this" so we can use it in the inner function below. 
    var that = this;, function(result) { 
       // In JavaScript, ever function defines its own "this" value. So, "this" in this inner function 
       // here is different from "this" in the onSubmit() function. That's why we had to keep a 
       // reference to "this" and store it in "that". Now, we can use "that": 

       that.result = result; 

Arrow functions, unlike normal functions, don’t rebind this. They use the this value of the enclosing execution context. So, if we replace the inner function above with an arrow function, we don’t need to keep a reference to this anymore.

// ES6
function onSubmit() {, result => { 
       // Since we're using an arrow function here, "this" references the "this" value of the containing function
       // (onSubmit). Arrow functions don't re-define "this". 
       this.result = result; 


Destructuring is an expression that allows us to extract properties from an object, or items from an array. Let’s say we have an address object like this:

const address = { 
   street: '123 Flinders st',
   city: 'Melbourne',
   state: 'Victoria'

Now, somewhere else we need to access these properties and store their values in a bunch of variables:

const street = address.street;
const city =; 
const state = address.state; 

We have this repetitive code over and over: “address.” repeated 3 times. Object destructuring gives us a short and clean syntax to extract the value of multiple properties in an object:

const { street, city, state } = address;

That’s it! This code is exactly equivalent to the snippet above. We use curly braces on the left to destructure the address object. Inside the braces, we’re defining 3 variables: street, city, and state. Their values will be extracted from the corresponding properties in the address object.

Note that we don’t have to list all the properties in the address object. Maybe we’re interested only in the street property:

const { street } = address;

Object destructuring is particularly useful when you’re dealing with nested objects:

const person = { 
   name: 'Mosh', 
   address: {
      billing: { 
         street: '123 Flinders st',
         city: 'Melbourne',
         state: 'Victoria'

Without destructuring, we would have to write this ugly and repetitive code:

const street = person.address.billing.street;
const city =;
const state = person.address.billing.state;
// So annoying! 

Now, we can achieve the same result using a single line of code:

const { street, city, state } = person.address.billing; 

We can also destructure arrays but we use square brackets ([]) instead of curly braces ({}). Let’s say we have an array and we want to extra the first and second item and store them in two different variables:

// ES5
const values = ['John', 'Smith'];
const first = values[0];
const last = values[1]; 
// ugly! 

With destructuring, we can re-write the above code like this:

// ES6
const values = ['John', 'Smith'];
const [first, last] = values; 


I’m planning to create a comprehensive course on the topic. If you’re interested, join my mailing list to get notified when the course is ready and get it with a discount.

What are your favorite ES6+ features? Use the comment box below and let us know!

If you enjoyed this post, please share it.


Tags: ,

New Course: Unit Testing for C# Developers

I just published my unit testing course yesterday! There are limited early-bird discounts available until November 1st. Redeem yours if you want to master unit testing.

Tags: ,

Developers who don’t write tests!

A lot of companies have been practicing unit testing for years, yet there are many developers who don’t write unit tests. Here are some of the excuses I hear often:

We don’t have time to write tests!

Unit tests are waste of time. They slow you down and decrease your productivity!

I don’t know how to write unit tests!

So, in this post, I’m going to touch on these arguments.

You do have time to write unit tests!

When you don’t have a suite of automated tests, every time you make a simple change to your code, you run the application and test the same functions over and over!

If you spend less time on those tedious and repetitive manual tests, you’ll find enough time to write unit tests, at least for the critical parts of your application.

The good thing about unit tests is that you write them once, and run them over and over. You’ll get immediate feedback if your code is “really” working!

With these tests, you can test your business rules in a fraction of a second. Manually testing the functions with multiple execution paths takes a significant amount of time.

Unit tests help you save time and money

Multiple studies have shown that the later you catch a software bug in the software development lifecycle, the more costly it is to fix it.

With unit tests, you can catch a lot of bugs early on in the software development lifecycle. You catch bugs right when you’re coding before you deploy your application for QA testing or production!

The reality is that building software is costly. You either choose to pay that cost upfront by writing tests or pay a far greater cost to fix bugs after releasing your software.

Am I saying that with unit tests you release bug-free software? Not at all! But with unit tests, you release software of better quality and with fewer defects. Also, software built with unit testing in mind has a better design. You’ll end up with properly designed classes, each focusing on a single responsibility. You’ll have good separation of concerns in your code.

Unit tests help you go faster!

One of the common arguments about writing unit tests is that they slow you down. You have to write extra code to test your code and this delays the delivery. As you code, you also have to deal with broken tests. Fixing those tests, again, takes extra time.

Can you relate to this? If yes, let me tell you something: you got it wrong, my friend!

“Good” unit tests help you go faster. If your tests are 50 lines of code, where the first 30 lines are just the setup code and mock objects, you’re doing it wrong!

Your unit tests should be less than 5 lines of code. Yes, it is possible to write unit tests like that! If you want to learn how to write unit tests like that, check out my upcoming unit testing course.

Unit tests tell what your code should do

Good unit tests express what your code should do right now. They’re far better than those ugly and often outdated comments that you put above your code. Those comments don’t get compiled. As different developers work on the code, those comments get outdated. They rot. They stink.

Unit tests don’t! They get compiled. They express the behavior of your code. They act as a living documentation for your code.

Not sure how to write unit tests?

I’ve been working on a comprehensive course on unit testing for C# developers. In this course, I take you on a journey to master unit testing, from beginner to pro. You’re going to learn the secrets to write clean, maintainable and trustworthy tests. The kind of tests that you can rely upon. When they pass, you know your code is working and whey they fail, you know that something is wrong with your code.

It took me years to really master unit testing. I read several books, watched tons of videos, worked with different developers and tried different approaches to unit testing. Some worked, some failed. What you’ll find in this course is the result of the best practices I’ve discovered, packed with lots of real-world examples, exercises and step-by-step solutions.

You’ll learn about:

  • Characteristics of great unit tests
  • What to test and how
  • The tooling
  • All about dependency injection
  • Mocks, what they are, when to use them and how
  • Refactoring legacy, untestable code into loosely-coupled, testable code
  • Tips and tricks to keep your tests clean
  • Pitfalls to avoid

And much, much more…

This course will be published over the next few days. If you like to be notified and get the course with an early bird discount, join my mailing list now. I’ll send you an email as soon as the course is published.

Tags: ,

Angular 4 Tutorial: Angular 4 in 20 minutes

So, do you want to learn the fundamentals of Angular 4 in a quick and easy way? You have come to the right place! You don’t need familiarity with any previous versions of Angular. In this tutorial, I’m going to take you from the ground up and show you Angular 4 in action. You only need a basic familiarity with HTML, CSS, and JavaScript.

If you learn better by videos, you can also watch this tutorial on YouTube; otherwise, continue reading.

Beginner’s questions

Let’s start with a few beginner’s questions. If you’ve used any previous versions of Angular, feel free to skip this section and jump to “Getting the tools”.

What is Angular?

Angular is a framework for building client applications in HTML, CSS, and either JavaScript or a language like TypeScript that can be compiled (more accurately, transpiled) to JavaScript. If you have never worked with TypeScript before, don’t worry. I will give you the basics in order to complete this tutorial.

What is TypeScript?

TypeScript is a superset of JavaScript. That means any valid JavaScript code is valid TypeScript code. But many prefer TypeScript because it has additional features that we don’t have in the current version of JavaScript that most browsers understand. So, when building Angular applications, we need to have our TypeScript code converted into JavaScript code that browsers can understand. This process is called transpilation which is the combination of translate and compile. And that’s the job of  the TypeScript compiler.

Why do I need a framework like Angular?

A common question a lot of beginners ask me is: “Why do we need Angular in the first place? What’s wrong with the plain old vanilla JavaScript and jQuery?”.

There is nothing inherently wrong with using vanilla JavaScript/jQuery. In fact, a lot of web applications out there are built this way. But as your application grows, structuring your code in a clean and maintainable and more importantly, testable way, becomes harder and harder. I’m not saying this is impossible. But using a framework like Angular, makes your life far easier. Sure, there is a learning curve involved, but once you master Angular, you’ll be able to build client applications faster and easier.

Is Angular better than React/Vue.js?

These days there is a lot of debate between Angular vs React vs Vue.js. Whether Angular is better than React or Vue.js depends on how you define “better”. Each of these frameworks have strengths and weaknesses and there is no one shiny framework that makes every developer in the world happy. My suggestion to you is to learn the fundamentals of each of these frameworks and choose the one that works best for each project depending on its requirements.

Getting the tools

Now, let’s get dive into some code and get our hands dirty! The first thing you need to install is the latest version of Node. So, if you haven’t installed Node, head over to, and install the latest stable version.

Node comes with a tool called Node Package Manager or NPM, which is used for installing third-party libraries. In this tutorial, we’re going to use NPM to install Angular CLI. That is a command-line tool we use to create a new Angular project. It is also used for generating some boilerplate code during development (such as components, services, etc) as well as building an application for deployment. We do all this in the terminal.

So, once again in the Terminal, run the following command to install Angular CLI:

npm install -g @angular/cli

The -g flag stands for global. If you don’t put -g here, Angular CLI will be installed only in the current folder, and it’s not going to be accessible anywhere else.

If you’re on Mac, you need to put sudo at the beginning of this command to execute it as an administrator; otherwise, you’ll get permission errors.

Your First Angular App

So with Angular CLI in place, now we can create a new Angular project using the following command:

ng new hello-world

As you can see, we can access Angular CLI using ng. We provide a command (in this case new) to instruct Angular CLI on what we want it to do for us. Here, we are telling Angular CLI to generate a new project called “hello-world” and store it in a folder with the same name. We’ll be looking at these generated files shortly. For now, let’s finish the first step and see our new Angular app in the browser.

So, run the following commands in the terminal:

cd hello-world
npm install 
ng serve

With the second command (npm install) we install all the dependencies of our application. The last command (ng serve) compiles our application and hosts it using a lightweight web server. Now, we can access our application at http://localhost:4200. 

So, open up your browser and navigate to this address. You should see the following page:

Congratulations! You generated and served your first Angular 4 application. Now, let’s have a quick look at the files and folders in our new Angular project.

Structure of Angular Projects

Inside the generated folder, you’ll find the following top-level folders:

  • e2e: includes end-to-end tests.
  • node_modules: all the third-party libraries that our project is dependent upon.
  • src: the actual source code of our Angular application.

99.9% of the time you’ll be working with the files inside the src folder. But let’s quickly overview the other files we have in this project:

angular-cli.json: a configuration file for Angular CLI. We use this file to import third-party stylesheets or define additional environments (eg testing environment) for our application.

package.json: a standard file for Node-based projects. It contains metadata about our project, such as its name, version as well as the list of its dependencies.

protractor.conf.js: Protractor is a tool for running end-to-end tests for Angular projects. We hardly need to modify this file.

karma.conf.js: Karma is a test runner for JavaScript applications. This file contains some configuration for Karma. We rarely need to modify this file.

tsconfig.json: includes setting for the TypeScript compiler. Again, we hardly, if ever, need to modify this file.

tslint.json: includes the settings for TSLint which is a popular tool for linting TypeScript code. That means it checks the quality of our TypeScript code based on a few configurable parameters. This is especially important in a team environment to ensure that everyone follows the same conventions and produces code of the same quality. We can run linting on our code using Angular CLI in the terminal or we can add it to our editor as a plug-in.

So, as you see, all these files are configuration files that work smoothly out of the box. Unless you want to customize them for your specific environment, you don’t ever have to modify them.

Architecture of Angular Apps

Ok, so you’ve learned how to generate and serve a new Angular project. You’ve also learned about various files and folders in a new Angular project. Now, let’s look at the architecture of Angular applications.

The most fundamental building block in an Angular application is a component. You can think of a component as a view component. It represents a view or part of a view (what the user sees). A component consists of three pieces:

  • HTML markup: to render that view
  • State: the data to display on the view
  • Behavior: the logic behind that view. For example, what should happen when the user clicks a button.


A component can contain other components. For example, let’s imagine you’re going to build a web app like Twitter using Angular. In your implementation, you may have a tree of component likes this:

  • App
    • NavBar
    • SideBar
    • ContentArea
      • Tweets
        • Tweet
          • Like


Now, at the root of the application, we have a component called AppComponent. This is the root of every Angular application. Our AppComponent contains 3 child components: NavBar, SideBar, and ContentArea.

The reason for such separation is because the navigation bar is logically a separate part of the view. It has its own markup, state, and behavior.  We can encapsulate all that using a component called NavBarComponent. This way, when modifying or extending the navigation bar of our application, we can focus on a small component with a lightweight template.

Benefits of Component-based Architecture

As you can see, this component-based architecture makes our applications more organized and maintainable. Plus, we can potentially reuse these components in various parts of an application or in an entirely different application. For example, tomorrow, we can grab this NavBarComponent and put it in an entirely different project. We just need to modify the links. But all the HTML markup will remain the same.

Back to our tree of components, you can see that inside the content area, we have a tree of components like this:

  • Tweets
    • Tweet
      • Like

Again, this is one way to model this. We don’t necessarily have to have a separate component for the list of tweets and each tweet. We could combine TweetsComponent and TweetComponent into one component. But, I’d like to separate the LikeComponent because we could potentially reuse this like button somewhere else in this application or in another application. Even if we don’t reuse it, separating the markup, state and behavior of this like button into a separate component, makes our application more maintainable and testable.

An Angular Component in Action

Now, let’s inspect a real component in action.

Back to our project, open up the src/app folder. Inside this folder, you should see the following files:

  • app.component.css
  • app.component.html
  • app.component.spec.ts
  • app.component.ts
  • app.module.ts


These files represent AppComponent, which is the root component for our application. In this particular case, all these files are inside the app folder. But when we generate a new component using Angular CLI, all the files that make up a component will be grouped by a folder.

So, in terms of the implementation, each component in an Angular project is physically implemented using four files:

  • A CSS file: where we define all the styles for that component. These styles will only be scoped to this component and will not leak to the outside. This is what Shadow DOM does. But not all browsers today support Shadow DOM. So, Angular uses a technique to emulate the Shadow DOM.
  • An HTML file: contains the markup to render in the DOM.
  • A spec file: includes the unit tests.
  • A TypeScript file: where we define the state (the data to display) and behavior (logic) of our component.

You will also see an app.module.ts file.  This file defines the root module of our application and tells angular how to assemble the app.


Creating a Component

Now that you know what a component is, let’s use Angular CLI and add a new component to this application.

Imagine we want to build an e-commerce application. On the home page, we’re going to display the list of products and below each product, we want to have a button for adding that product to the shopping cart.

So, for this exercise, we want to create a super simple component to represent each product on the home page. This component will include the HTML markup to display that product, and it’ll respond to the click event of a button to add that product to the shopping cart.

When we click this button, it also shows the number of products of this type in the shopping cart. Initially, the number should be 0. Every time we click the Add to Shopping Cart button, the number is increased. Of course, in a real-world application, there’s far more complexity involved. For example, we may want to call some back-end services to store this item in a database. But for now, let’s just focus on the fundamentals. If you understand the fundamentals well, you can always add these other details later. So, for now, forget about the server-side, databases and other complexities.

Ok, we’re ready to create a component. We can manually create all those four files by hand, but there is a faster way. We can use Angular CLI!

Generating a Component Using Angular CLI

Run the following command in the terminal, inside the project folder:

ng g c product

Here, g is short for generate, c is short for component and product is the name of our component. Now, if you look at the project folder, inside the src/app folder, you should see a new folder called product. Expand this folder. You should see the following files:

  • product.component.css
  • product.component.html
  • product.component.spec.ts
  • product.component.ts

Open product.component.ts. This is what you should see:

import { Component, OnInit } from '@angular/core';

  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
export class ProductComponent implements OnInit {
  constructor() { }

  ngOnInit() { 

If this code looks complex to you, don’t worry! I’m going to make it super simple. It’s actually far easier than you may think!

For now, I want you to note the value of the selector property. It’s app-product. This is a CSS selector. So app-product represents an element by this name. With this, we can extend the HTML vocabulary. Anywhere we add this app-product element, Angular will render the HTML markup of ProductComponent inside that element. So, let’s add this element to the template for our AppComponent.

Using a Component

Open up src/app/app.component.html. Replace all the markup with the following:


Now, our application includes a tree of components:

  • App
    • Product

At the root of this tree, we have our AppComponent. This component includes a child component: ProductComponent. 

Save the changes. Back to the browser, now, you should see this:

Our ProductComponent has a simple template that includes “product works!”. We can modify product.component.html and add some complex markup here. For example, we can use Bootstrap 4 cards to render the product inside a card.

But for now, we don’t want to waste our time and make our application pretty. Our focus is on understanding Angular. We can always come back to the template for ProductComponent and improve it.

Examining an Angular Component

You successfully generated and used a component. Now, let’s examine this component in detail. So, open up product.component.ts. Here is the code for reference:

import { Component, OnInit } from '@angular/core';

  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
export class ProductComponent implements OnInit {
  constructor() { }

  ngOnInit() { 

Inside of this file, we have a TypeScript class called ProductComponent.

What is a Class?

A class is a fundamental building block of many object-oriented programming languages. It’s a container for a bunch of related functions and variables.

So, unlike vanilla JavaScript where all our functions and variables are hanging from the global namespace, we put them in containers called classes. With these classes, we don’t pollute the global namespace and as a result, we won’t have one function overwriting another function with the same name. Because these functions are now in separate containers (classes). Also, because each class includes a bunch of highly related functions and variables, our code is more organized and maintainable.

In object-oriented programming terms, we call these functions and variables that reside in a class, methods and fields/properties respectively. Fields and properties are technically different but they are often used interchangeably. A field is like a variable where we store some data. A property looks like a field from the outside, but internally, it is a function around a field that gives us read or write access to that field. If this sounds confusing, don’t worry about it now. I’m planning to publish a separate post about TypeScript. For now, you can assume fields and properties are the same, even though they are not!

Example of a Class

So, in product.component.ts, we have a class called ProductComponent. This class has 2 functions (methods): constructor and ngOnInit.

export class ProductComponent implements OnInit {
  constructor() { }

  ngOnInit() { 

Constructor is a reserved keyword in TypeScript. A method by that name is a special method in a class. This method is called automatically when we create an instance of that class.

ngOnInit is a special method in Angular. Angular calls this method when it creates an instance of this component and displays it to the user in the browser.

For this exercise, we don’t have to worry about either of these methods. So, delete both of them. You should also delete implements OnInit in front of the class name. For now, don’t worry about it, but basically, it tells Angular that this class has some initialization code that should be executed before this component is displayed to the user.

So, your code should look like this:

import { Component, OnInit } from '@angular/core';

  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
export class ProductComponent {

Component Metadata

So, you’ve seen that we implement a component using a TypeScript class. But a class on its own is just a class. It only includes some data and logic for a view. It doesn’t include any HTML markup or CSS styles. In order to attach these to this class, we need to promote this class to a component. We can do this by using the @Component() decorator function on top of this class (lines 3-7):

import { Component, OnInit } from '@angular/core';

  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
export class ProductComponent {

With this, we can attach metadata to this class that Angular understands. This @Component() decorator function is defined in Angular and you can see we’re importing it on line 1. It takes an object with the following properties:

  • selector
  • templateUrl
  • styleUrls

You’ve seen the selector in action. It associates a new HTML element to this component. With this, we can extend the standard HTML vocabulary. So, now we have a new custom element (app-product) that we can use anywhere in our application. When Angular sees that element, it’ll place the HTML markup of our ProductComponent inside that element.

The other 2 properties (templateUrl and styleUrls)  are self-explanatory. They specify the path to the HTML template and CSS file(s) for this component.

Property Binding

In Angular, unlike vanilla JavaScript or jQuery, we don’t work directly with the DOM. So, we don’t write code like this:


Instead, we use property binding. Let me show you how that works.

In our ProductComponent, let’s add a new field:

import { Component, OnInit } from '@angular/core';

  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
export class ProductComponent {
   title = 'USB Stick 8GB';

This title field contains the title for our product. In a real-world scenario, we get this title from a database somewhere on the server. So we don’t hardcode it here. But for now, let’s not worry about this and see property binding in action.

Now, open up product.component.html. Replace all the markup there with:

<p>{{ title }}</p>

This special double curly brace syntax you see here is what we call interpolation in Angular. Fancy name again, right? This basically tells Angular to replace what we have between curly braces with the value of the title field in our component.

This syntax is a shorthand for the actual property binding syntax we have in Angular. The code you wrote above is equivalent to the following code:

<p [innerHtml]="title"></p>

What is this? Very simple! In vanilla JavaScript, we can simply get a reference to an element in the DOM and set its innerHTML property like this:

var el = document.getElementById("myElement");
el.innerHTML = "USB Stick 8GB";

So, every DOM element has a property called innerHTML. In our Angular application, we’re using the square bracket syntax to bind a property of a DOM element to a field/property in our component:

<p [innerHtml]="title"></p>

So, at run-time, Angular will set the innerHtml property of this paragraph to the title field we defined in our component. And more importantly, if the value of our title field changes in the future, Angular will automatically update the view (DOM) for us! This is property binding in action. We have bound the innerHTML property of this element to the title field of our ProductComponent.

A Simple Exercise

Now, here is a simple exercise for you. I want you to extend our product component and display the number of USB sticks in the shopping cart below the name of this product. So, stop reading and make any necessary changes in the code. Then, come back here and see my solution.

Ok, so you should have added a new field in ProductComponent:

export class ProductComponent {
   title = "USB Stick 8GB";
   itemCount = 0; 

And used interpolation or property binding syntax to render it in the template:

<p>{{ title }}</p>
<p>{{ itemCount }}</p>

Event Binding

Similar to property binding, we have another concept in Angular called event binding. With property binding, we bind properties of DOM elements to fields/properties in our component. With event binding, we bind events of DOM elements (such as clicks) to methods in our component. So, for example, when the user clicks on a button, a method in our component will be called.

We’re going to extend our product component and add a button to increase the number of USB sticks in the shopping cart. So, modify product.component.html as follows:

<p>{{ title }}</p>
<p>{{ itemCount }}</p>
<button (click)="addItem()">Add</button>

Note the difference between property and event binding syntax. We use square brackets for property bindings and parenthesis for event binding. With this code, whenever our button is clicked, Angular calls the addItem() method in our component.

So, let’s implement this method in our component. Open up product.component.ts:

export class ProductComponent {
   title = "USB Stick 8GB";
   itemCount = 0; 

   addItem() { 

Here, we’re simply incrementing the itemCount field. Now, save the changes and go back to the browser. Test this application by clicking the Add button. You can see the count gets updated immediately. This is the beauty of property and event binding in action!

As I explained, Angular watches our itemCount field. When its value gets changed, Angular updates the DOM immediately.

What you’ve seen far is just the tip of the iceberg. There is far more to property and event binding and Angular in general. It’s impossible to cover it all in one blog post. If you’re serious about learning Angular, I have a complete course with 30 hours of high-quality videos. This is equivalent to a book with more than a thousand pages!


Let’s quickly recap what you’ve learned in this post:

  • Angular is a framework for building client apps with HTML, CSS and TypeScript.
  • It gives our applications a proper, maintainable and testable structure.
  • At the core of every Angular application, we have a tree of components.
  • Each component encapsulates the state (data), the HTML markup and the behavior for a view.
  • At a minimum, a component is implemented using a class. This class may include a bunch of fields for displaying data and methods, which will be called in response to events raised from the DOM events.
  • A component may have an external template stored in a separate HTML file.
  • It may also include one or more external stylesheets.
  • A component also has a selector. That tells Angular where in the DOM to place this component.
  • We use the property binding syntax (square brackets) to bind properties of DOM elements to fields/properties in our components.
  • When the value of these fields/properties change, Angular automatically updates the DOM (view).
  • We use the event binding syntax (parenthesis) to bind events of DOM elements to methods in our component.
  • Angular automatically calls these methods to handle events raised from the DOM elements.


Once again, if you want to learn everything about Angular from the basic to the advanced topics, I encourage you to enroll in my complete Angular course. This is far easier and faster than jumping from one tutorial to another. With this course, you can learn all these concepts in one place, step-by-step and you’ll build and deploy real e-commerce app with Angular and Firebase at the end of the course.


If you’ve enjoyed this tutorial, please show the love by sharing it with others. Thank you!



What is Unit Testing and Why You Need to Learn It

In this post, I’m going to give you a brief introduction to unit testing and its benefits. So, let’s get started!

What is unit testing?

Unit testing is the practice of writing code to test your code and then run those tests in an automated fashion.

Here is an example. Imagine you have this function somewhere in your code. It’s a basic calculate function that takes an input and depending on some conditions, it returns different values.

public float CalculateTax(int input) 
    if (x) return ...;
    if (y) return ...;
    return ...;

If you want to test this function manually, you have to run your application, perhaps you have to login, or maybe do a few clicks here and there to get to a page where this function is used. Then, you have to fill out a form, submit it and verify if this function returned the right result. And then you have to repeat all these steps, each time using different values in your form.

Manual testing is expensive!

As you can see, this is very time-consuming.  This workflow to test this function may take several minutes every time! Now to make matters worse,  this is not the only function in your application. In a real application, you have tens or hundreds of functions like this! As your application grows in size and complexity, the time required to manually test all the different bits and pieces increases exponentially. So, that’s why we use automated testing.

Unit testing

With automated testing, you create a separate project for writing tests. In that project you’ll write code and directly call this function with different inputs and verify that this function returns the right output.

var result = CalculateTax(1);
Verify(result == 1.5f);

We refer to these types of tests as unit tests. With unit tests, we test a unit of the application in isolation without its external dependencies such as files, databases, web services, etc.  Tests that include these external dependencies are called integration tests, and that’s the topic for another post.

Unit tests are repeatable!

The good thing about unit tests is that they are repeatable. You write them once and run them a million times! So, every time you change your code, every time you commit your code to a repository, and before deploying your application. With this approach, you can test all the execution paths in this function in a fraction of a second! You can write several hundreds or thousands of unit tests for various parts of your application, and run them all in just a few seconds.

Unit tests help you deploy with confidence!

If you properly cover your code with a comprehensive suite of tests, you can run these tests before deploying your application to the production. If you’ve broken something that used to previously work, you’ll know straight away. With unit tests you can catch more bugs before deploying our application and this means you can deploy with confidence.

Have you ever been in a situation where you deployed your application, left the office thinking everything is working, and then got a call from your boss or an end-user, telling you that one of the major functions of the application is not working? Then you had to go back to the office and you thought that was a quick fix, but you ended up staying there till midnight!

That’s why you should write tests: to reduce the number of defects or bugs that will go in the production. Note that I’m not saying that with unit tests you’re gonna release bug free software. That’s not true! But you can certainly reduce the number of bugs and improve the quality of your software.

Unit tests help you refactor with confidence!

Refactoring means changing the structure of your code without changing its behaviour. If you extract a few lines of a method into a separate private method, that’s refactoring. If you rename a method, that’s refactoring too. You’re changing the structure of your code to make it cleaner and more maintainable, but you’re not changing the functionality.

When you don’t have unit tests, every time you refactor your code, you have to manually test every part of the application that could be affected by your refactoring. And this is very painful because first of all, it’s time consuming, and second, as your application grows, you may forget about the parts that need to be tested! With unit tests, every time you refactor your code, you run your tests and make sure you didn’t accidentally break anything that used to previously work.

Unit tests help you write better code!

When writing tests, you’re forced to think about the edge cases of every function in your application. You write tests for these functions, giving them various inputs and make sure they behave as you expect. This will help you produce better quality software with less defects. A lot of bugs in our applications are the result of unforeseen edge cases. One of your functions receives an input that you forgot to predict and boom! It blows up!  With unit tests, you make sure that every function works with different inputs under varying circumstances.

Also, applications written with unit testing in mind often have cleaner and more maintainable source code. That means smaller functions with a clear responsibility and few parameters.

Benefits of unit testing

So, to recap, unit tests help you:

  • Test your code frequently and in less time
  • Catch more bugs before deploying
  • Deploy your application with confidence
  • Refactor your code with confidence
  • Write cleaner and maintainable code

You need to have unit testing on your resume!

If you’re a senior developer, you must know how to write unit tests! If you don’t know, you’re probably more of an intermediate-level developer even if you have a senior position at your company.

If you’re a junior/intermediate-level developer and want to become a senior developer, you must have unit testing on your resume to get a better job. Most good companies with good programmers practice unit testing these days.

Unit testing C# code

I’m currently working on a comprehensive course on unit testing for C# developers. In this course, I’ll take you from the ground and teach you how to write unit tests for your C# code. I’m planning to release this course by the end of October. If you’re interested to get this course with an early-bird discount, drop your email and join my mailing list. I won’t spam you, and you can unsubscribe at anytime.


What is your story with unit testing? Drop in the comments below and let us know! 


If you enjoyed this post, please share it with others!


The art of asking “coding” questions

One question (or more accurately, comment) that I frequently get on my YouTube videos is:

… is not working!

Examples: “npm install is not working”, “interpolation is not working”, etc.

“It’s not working” is not helpful! It doesn’t tell me or others about the problem you’re facing.

What error do you get? Have you tried to Google the exact same error message? If not, did you know that if you do that, 90% of the time, you can find the answer to your question within minutes? In fact, 90% of the time, the first link on Google search result is a link to a page on StackOverflow, where someone else faced the exact same problem!

3 tips that make you a better developer

Tip 1: Learn the art of asking ‘programming’ questions. Be specific about why “it’s not working”!

Tip 2: Learn to find the answer to your question yourself. You cannot always reach out for help every time “it’s not working”. Successful programmers are independent. Linus Torvalds, the creator of Linux, even wrote his own editor and assembler! Now, you don’t need to do this to be independent, but a Google search takes only a few seconds and helps you become less dependent on other developers in your team.

Tip 3: Read about rubber duck debugging. It works!

If you enjoyed this article, please share it with others.


6 Essential VSCode Extensions for Angular Developers

In this post, I’m going to list my top favorite Visual Studio Code (VSCode) extensions for building Angular applications. If you know a great extension that is missing here, please let us know using the comment box below the post.

Installing an Extension

If you know how to install an extension in VSCode, feel free to skip this section. Otherwise, launch VSCode, and open the Extensions tab from the left side bar. Here, you can see the list of installed extensions. You can also search for other extensions. Once you find an extension, simply click the Install button. Then, reload VSCode and you’re good to go.

TypeScript Hero

This is by far my absolute favorite extension! You no longer have to manually import types in TypeScript. TypeScript Hero automatically imports the types for you as you write code. When pasting some code from somewhere else, you can also add all the missing import statements in one go!

Another useful feature of this extension is that it allows you to sort and remove the unused import statements. You also get code completion and several other useful features. Highly recommended!

Angular Language Service

This extension provides a rich editing experience for Angular templates. Imagine you have a field in your component as follows:

course = { 
   title: 'The Complete Angular Course', 
   author: { 
      name: 'Mosh Hamedani'

With this extension, you’ll get auto-completion in your HTML templates:


Bracket Pair Colorizer

This extension allows matching brackets to be identified with colors.


Move TS

As your application grows, you may want to break it down into smaller and more maintainable modules. You’ll have to move files and folders around. But what happens to all your import statements? They break! So, that’s what this extension is for. With Move TS extension, you can simply move files/folders around and this extension will automatically update your import statements.

Material Icon Theme

Do you like to have pretty icons in the project explorer? Install this extension!

Angular TypeScript Snippets

Another useful extension developed by John Papa that boosts your productivity when building Angular applications. It gives you a bunch of code snippets that allow you to quickly generate code. There are snippets for creating a component, service, directive, etc. You may argue that now we can easily create these artifacts using Angular CLI and that is absolutely right. However, this extension gives you some useful HTML snippets as well:

Angular TypeScript Snippets

You can find the complete list of snippets provided by this extension here.

What is your favorite extension that you frequently use? Use the comment box below and let us know.

If you enjoyed this article, please share it with others.

Tags: ,

Get paid to work with Me!

I constantly get requests about creating new courses and with 24-hour days I’m constantly behind my schedule. There are courses that many of you have been awaiting for a long time!

So, to speed things up, I’m looking for a passionate teaching assistant who can help me produce new courses faster and support my existing students. This will be a part-time job with the potential to go full-time.



In order to be considered for this position:

  • You should be a US citizen
  • You should be fluent in English and have excellent writing skills
  • You should be a great communicator
  • You should have a passion for learning and teaching new things



As a teaching assistant, you’ll help me with one or more of the following tasks. This depends on your capabilities and interests.

Creating materials for my future courses
I’ll give you some direction about a course topic and your job will be to come up with the structure for a course as well as the detailed materials for each lecture. This includes the script, slides, examples, and exercises. I’ll use these materials to create new videos.

In order to be considered for this, you should have a fair amount of understanding of the given topic and have excellent writing skills (for writing the script).

Writing blog posts
This involves writing a clean, professional and properly formatted post on a given topic. You should have excellent writing skills and pay great attention to the readability and formatting of these posts.

Answering the questions on the discussion boards
You should have a fair amount of experience on a given topic (e.g. C#, Angular, etc) and be able to answer students’ questions. You don’t have to be an expert in the given topic but willing to research and guide students in the right direction.

Reviewing the upcoming courses
Once I record and edit my videos, you’ll have to watch each lecture and make sure all the videos are edited properly, all the supplementary materials are there and the course is ready to go live.



To apply, fill out the following this Google Form. Since I may be receiving a large number of applicants, I won’t be able to respond to each of you individually. So, I’ll reach out only to eligible applicants.

%d bloggers like this: