Do you use Template Literals in JavaScript?

String manipulations and formatting is one of the tedious tasks in many programming languages and it is true in JavaScript as well. If you have to write string with some special character like new line, colon etc, code becomes ugly. Let’s see a quick example

Here we can see that to write a text in two lines, we have to write a newline character (\n) at the right place, we cannot simply write it in two lines as it appears in output so actually you cannot visualize the output until you run it. Or you have other options to break it into multiple strings and use + operator as above which may look little similar but doesn’t look clean at all.

As mentioned earlier that there are times when we have to put special characters in the string like colon, quote, double quote, backslash etc and it becomes more ugly and confusing. To get it working, we need to add special escape character (\) every time it appears in the text as

var message = 
'Hello \'Brij\'\n, Did you use special chars in your new post \' Truthy and Falsy in JS\'?' 

Or if you want to write some regex which would be full of special characters.

Template Literals

Earlier there were three literals in JavaScript as Object ({}), Boolean (true or false) and string (” or “”) and starting from ES6, we have one more literal called template literal which is denoted by backtick character (“), it is mostly just below the escape character on keyboard.

Let’s see the above example using the template literal.

Here we can see that we have message appearing in IDE and console exactly same and we didn’t have any escape character.

Template literal also allows to have expressions which could be a normal variable or normal mathematical expression as

Here we can see the JavaScript code in the upper part and then output in the lower part. In the code, we used an expression three places: name, date object and normal addition of two numbers. Each expression should start with a dollar sign ($) as in the example. We can call any JavaScript function and can use other normal expressions like ternary operators.

This kind of capability has been added to C# some time back and seeing a similar feature in JavaScript made me very happy and couldn’t stop myself from sharing it with you all. (look at my signature ūüôā )

Cheers

Truthy and Falsy in JavaScript

Many times, we observe in JavaScript that some values when used in a boolean context, behave as true or false, this is not common in other languages. For many experienced developers, even they get used to it but it is a mystery while for new developers it is confusing.

These are not the boolean values but these are known as Truthy and Falsy values. Any value which behaves as a true value in a boolean context (like conditions, loops), called Truthy and the values that behave as false, are called Falsy values. Internally, JavaScript converts a value to true or false when used in the boolean context and this is called Type Coercion.

This also means that a single value can be used in conditions.

Falsy

As mentioned before, every value in JavaScript returns true and false when it is used in a Boolean context and the values that return false are called Falsy values. There are 7 falsy values in total in JavaScript.

  1. false (the boolean false value)
  2. 0 (number 0 including all decimal or zeroish number such as 0.0, 0.00, 0x0)
  3. 0n (represents bigint)
  4. ” “,’ ‘ (empty strings)
  5. null
  6. undefined
  7. NaN

To test, I wrote a generic function which writes Falsy or Truthy on console  with some examples as

function TruthyOrFalsy(val)
{
  return val ? console.log("Truthy") : console.log("Falsy");
}

// All the below call logs 'Falsy'
TruthyOrFalsy('')
TruthyOrFalsy("")
TruthyOrFalsy(0)
TruthyOrFalsy(null)
TruthyOrFalsy(undefined)
TruthyOrFalsy(NaN)

Now let’s discuss Truthy values.

Truthy

In simple words, any value which is not falsy is truthy. These values return true if used in a boolean context. Some important truthy values are

  1. “0” or ‘0’ (Any non-empty string is a truthy value including just spaces)
  2. ‘false’ (A string with value false)
  3. [] (An empty array)
  4. {} (An empty object
  5. -1 (A negative number)
  6. function() {} (An empty function)
  7. Infinity (infinity value)

Now let’s see some examples

// All the below call logs 'Truthy'
TruthyOrFalsy(' ')
TruthyOrFalsy(" ")
TruthyOrFalsy(" Some text")
TruthyOrFalsy("0")
TruthyOrFalsy(108)
TruthyOrFalsy(-108)
TruthyOrFalsy(Infinity)
TruthyOrFalsy([])
TruthyOrFalsy([0])
TruthyOrFalsy({})

In normal programming, this truthy and falsy behavior can be helpful in writing concise and readable code. The typeof operator with some of these values can be interesting so let’s see

// All the below call logs 'Truthy'
TruthyOrFalsy(typeof(undefined))
TruthyOrFalsy(typeof(null))
TruthyOrFalsy(typeof(NaN))
All the above are truthy value even the values used in typeof operators are falsy. For first, it even returns undefined but it is ‘undefined’ (string undefined) similar for next two examples. Second one returns ‘object’ and third one returns ‘number’.
These truthy values behave differently sometimes when used in comparison. Let’s see few

 

// Any falsy value wrapped under type becomes Truthy
TruthyOrFalsy(new Number(0))
TruthyOrFalsy(new Boolean(false))

// But comparing these truthy logs falsy
TruthyOrFalsy(new Number(0) == new Boolean(false))

Few other objects like [], [0], [[]] etc are although truthy values but returns false when compared with eatch other or even itself like [] == [].

Conclusion

Javascript is an interesting and powerful language and has some unique characteristics. In this post, we covered the truthy and falsy behavior of it. First we discussed all the Falsy values with examples and covered Truthy values later. As mentioned every value which is not Falsy is Truthy but it can be confusing sometimes and we discuss it with some with examples including typeof operator. Finally, we saw a behavior where even a few values are Truthy but returns true when used with ==.

Hope it helps.

Cheers
Brij

Inheritance with JavaScript

This post is in continuation in my last post.¬† In my last post, I discussed various ways to create custom object in JavaScript. I’ll advise you to go through that if you didn’t get a chance to have a look then you can go through it. Please find the link below

Various ways to Create custom objects in JavaScript

In this post, We will discuss, how we can use other features of Object Oriented concepts in JavaScript. Today I’ll discuss one of the main concepts of Object Orient Programming that is Inheritance.

So how can we use Inheritance with JavaScript ?

Various ways and plugins are available that provides similar ways to use Inheritance that we have used in other object oriented language. But the prototype based Inheritance is used most.

JavaScript is a object based language that is based upon Prototype based programming. It is free from Class and completely rely on objects only .

Did you hear earlier  that What is Prototype based language or what is Prototype based programming?

I would say this is just another way to provide object oriented feature by a language. As per wiki

Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is performed via a process of cloning existing objects that serve as prototypes. This model can also be known as classless, prototype-oriented or instance-based programming. Delegation is the language feature that supports prototype-based programming”.

So let’s start learning. To create a Class in JavaScript, we are required to create a function¬† that we also used to call a Constructor. I’ll use the word constructor in my further discussion. So Let’s create a Constructor called person

         function Person() {
             this.ToString = function () { alert('I am a Person'); }
             this.DisplayResidence = function () { alert('I stay near my office'); }
         }

As in my last post, I mentioned that Person is a nested function. As you can see that here we have following two functions in the Person constructor.

  1. ToString
  2. DisplayResidence

So let’s create a new object and display it

function DisplayObject()
{
var objPerson = new Person(); // Line- 1 Creates the instance of Person
objPerson.ToString();  // Line- 2
objPerson.DisplayResidence(); // Line- 3
}

Here both display as expected . Line 2 РI am a Person and Line 3 РI stay near my office

Now let’s say we want to create a constructor Employee as

         function Employee() {
             this.ToString = function () { alert('I am an employee'); }
             this.DisplayRole = function () { alert('My role is development and implementation'); }
         }

As you can see it has two methods ToString and DisplayRole. Now how can Employee inherit the properties/methods of Person. It can be done by writing as

Employee.prototype = new Person();

Now the employee has the properties of person as well. Now it has three methods

  • ToString()
  • DisplayResidence()
  • DisplayRole()

Let’s examine it by the method

         function DisplayObject() {
                var objPerson = new Person(); // Line- 1: Calles constrouctor Person to create an instance and assign it to objPerson
                objPerson.ToString(); // Line- 2: Calles ToString method of Person
                objPerson.DisplayResidence(); // Line- 3: Calles ToString method of Person

                var objEmployee = new Employee();  // Line- 4: Calles constrouctor Employee to create an instance and assign it to objEmployee
                objEmployee.ToString(); // Line- 5: Calles ToString method of Person
                objEmployee.DisplayResidence(); // Line- 6:  Calles ToString method of Person
                objEmployee.DisplayRole(); // Line- 7:  Calles ToString method of Person

                alert(objPerson instanceof Person);  // Line- 8:  Checks the type of objPerson
                alert(objEmployee instanceof Person);  // Line- 9:  Checks the type of objEmployee
         }

Let’s discuss it by Line numbers

Line 2 and Line 3- same as discussed above

Line 5- What it will display ? It displays I am an employee because ToString is available at both current and parent. But because the objEmployee holds the instance of derived class so the overridden method is called.

Line 6- Here DisplayResidence is not defined in Employee so it calls the base class(Person) method and displayed.

Line 7- ¬†DisplayRole is added in Employee object only and it shows ‘My role is development and implementation‘.

Line 8 – To check more on the type I added the last two lines. As objPerson is instance of Person only so it shows true.

Line 9 – As Employee inherits Person so it also shows true but if you delete the below line ….

<br />Employee.prototype = new Person();<br />

then it’ll show false as it does not inherit person any more.

Now you must have got enough Idea about prototype based inheritance in JavaScript.

There is one more way to add a method to and existing constructor as Person has two methods and  that we defined as nested class. You can write that in the following way as well

         function Person() {
         }
         Person.prototype.ToString = function () { alert('I am a Person'); }
         Person.prototype.DisplayResidence = function () {alert('I stay near my office');}

Now the question arises,  how Inheritance works in JavaScript.

Whenever we create an instance using the new Operator, It creates all the properties/methods and also has internally a variable called __proto__ (double underscore at both side) this is the variable which is responsible for the inheritance feature. So let’s say I created a instance of Employee as

var objEmployee = new Employee();

It’ll be having two methods/properties as defined and on __proto__ as

  1. ToString
  2. DisplayRole
  3. __proto__

Just because I have written also as

Employee.prototype = new Person();

The __proto__ variable gets assigned to the person instance. This __proto__ used to determine the prototype chain and return the property values. This allows us to access the base class methods and public properties.

As I talked about prototype chain, means as soon as I assign

Employee.prototype = new Person();

a proto variable gets available to us that can be be further used for inheritance. So lets create another constructor as

         function TeamLead() {
             this.ToString = function () { alert('I am a Manager.'); }
             this.DisplayRole = function () { alert('I rarely code but do lot of code reviews'); }
             this.DisplayMeetings = function () { alert('I have 3 meetings scheduled daily'); }
         }

Now as soon as I’ll create an instance using new operator then instance will be have the properties

  1. ToString
  2. DisplayRole
  3. DisplayMeetings
  4. __proto__

Now if we write the code for inheritance as

TeamLead.prototype = new Employee();

It can access all the properties in the hierarchies. We can check the type of instances as

 function DisplayObject() {
             var objTeamLead = new TeamLead();
             alert(objTeamLead instanceof Person);  // returns true because TeamLead inherits base class Person
             alert(objTeamLead instanceof Employee);  // returns true because TeamLead inherits  base class Employee
             alert(objTeamLead instanceof TeamLead); // returns true as expected
             }

You can see the results and they are expected

Let’s see the prototype chain as discussed earlier

         function DisplayObject() {
             var objTeamLead = new TeamLead();

             // Also here I'll show, How the prototype chain works
             alert(objTeamLead.__proto__ == TeamLead.prototype); // returns true because it represents the same prototype
             alert(objTeamLead.__proto__.__proto__ == Employee.prototype);  // returns true because second level __proto__ belongs to Employee.prototype
             alert(objTeamLead.__proto__.__proto__.__proto__ == Person.prototype);  // returns true because third level __proto__ belongs to Employee.prototype
         }

As you can see that actually __proto__ variable is actually the key for the inheritance.

Now you all must have got enough Idea about Prototype based programming and how we can use inheritance with JavaScript.

Do share your feedback.

Happy Coding,
Brij

Popup boxes in JavaScript : Do you use all ?

How many times have you used alert popup in your JavaScript code?

Most of the web developer’s answer would just less than infinite. This is the most used keyword and become rescue tool when we stay late at office to resolve a silly JavaScript issue. Alert prompts user a popup with some information. Earlier it was also used heavily for showing validation error messages.

But do you know what all are other popup options available with JavaScript?

These are in total three as below

popupboxes

Let’s discuss one by one

Alert

It is the simplest one and most widely used to show some message to user in one way. Once the message on browser, it shows OK button which is required to be pressed before moving further as

alert

Syntax

Syntax is pretty simple

   alert("Your meesage to user");

Confirm

This is another important  message box which instead of just showing a message to user, it also accepts the user’s response. It is used to take a Boolean response (true/false) from the user. When displays it show two buttons Ok and Cancel. Ok return true and Cancel returns false. Lets see it

confirm

Syntax
    if(confirm("Do you want to proceed"))
    {
        // Proceed further
    }
    else
    {
        // Stop 
    }

Prompt

This is another popup message box which is used least. But this can be very helpful in certain scenarios. This allows to take some input from the user. When it is shown to user, it provides an input box in popup where user can enter some text with OK and Cancel button. If OK is pressed then the entered value is passed to the backend else it returns null. It also allows us provide a default value in text box.
prompt

Syntax
    var enteredSocialMedia = prompt("Which social media site you use most", "Twitter")
    if (enteredSocialMedia == null)
    {
        alert("No worries!! You can save your preference any time");
    }
    else
    {
        alert("We have saved your preference");
    }

I have used Internet Explorer for this example and if you have used alert or any of them with earlier version of IE like IE 6/7, its looks much better now. It looks different on different browser because its the browser which shows its own popup. Although in most of the cases, we don’t use these popup due to its limitation and look n feel but can help in many scenarios and suitable for small applications.

Cheers,
Brij

Various ways to Create custom objects in JavaScript

Hi All,

Many developers still put their data at client side in multiple variables and some times it becomes very tough to manage them. If we store the data in object format then it becomes very easy to manage and control it. We can have similar model as we use at server side, it provides consistency of the data model in our application.

So today we’ll see various ways to store the data in Object format at Client side.

A Simple way:

We can create a normal object and can encapsulate related data in a single object. To create  a simple object, you just need to assign a variable with new Object() and create the properties according to our requirement and assign the values as

 var person = new Object();
 person.FirstName = "Brij";
 person.LastName = "Mishra";
 person.Age = 27;

This is a simple object with few properties like FirstName, LastName and Age. You can read the object as

function displayObject() {
      alert(person.FirstName + " " + person.LastName);
      alert("Age: " + person.Age);
}

Here as you can see it is an object which contains the details of an person but here we didn’t define any class (as we do in C#) then we create an object assign some values in that. But we just created a object and created properties on the fly. Now obviously, while reading the object, you¬† might not get any intellisense on some editor and we need to remember the name of the properties. And if we wrongly typed the property name then we’ll get an error at run time.

Because JavaScript is loosely coupled language. There is no way if we create similar object and check whether they are similar type of object. Also it is impossible to identify  the object that you are using is actually of what type.

But there are more standard ways to Create a Type. We’ll discuss in coming section. First, we are going to discuss

Closure
Closure is function that encapsulate a class. Actually closure is not a normal function but it contains other functions and you can say it is a nested function. Inner functions actually constitutes its properties and methods. It provides an elegant way to create multiple instances of a type like person. It provides exactly similar behavior like class and object. Let’s create a closure

        function Person(fisrtName, lastName, age) {
            var _firstName = fisrtName;
            var _lastName = lastName;
            var _age = age;

            this.set_FirstName = function (fisrtName) {
                _firstName = fisrtName;
            }
            this.get_FirstName = function () {
                return _firstName;
            }
            this.set_LastName = function (lastName) {
                _lastName = lastName;
            }
            this.get_LastName = function () {
                return _lastName;
            }
            this.set_Age = function (age) {
                _age = age;
            }
            this.get_Age = function () {
                return _age;
            }
        }

Now let’s use the person and person instantiate it. As you can see that it is taking three parameters, fisrtName, lastName and age. So you need pass the values while instantiating it. Using it, you can create an instance similar like C# as

function DisplayClosure() {
        function DisplayClosure() {
            var person = new NewPerson("Brij", "Mishra", 27);

            alert(person.get_FirstName() + " " + person.get_LastName());
            alert("Age: " + person.get_Age());

            person.set_FirstName("Rahul");
            person.set_LastName("Khanna");
            person.set_Age("30");

            alert(person.get_FirstName() + " " + person.get_LastName());
            alert("Age: " + person.get_Age());
        }

So you can see, How I created instance. I have created a setter and getter to set and get the properties.

Lets’s discuss another way.

Prototype:

Prototypes provides another way to create custom objects in JavaScript. Every JavaScript object has public prototype property . This actually exposes the public interface of the object. Using this feature, we can add some public properties and methods to a JavaScript object. Let’s see it with example

        Person = function (firstName, lastName, age) {
            this._firstName = firstName;
            this._lastName = lastName;
            this._age = age;

            Person.prototype.set_FirstName = function (firstName) {
                this._firstName = firstName;
            }
            Person.prototype.get_FirstName = function () {
                return this._firstName;
            }
            Person.prototype.set_LastName = function (lastName) {
                this._lastName = lastName;
            }
            Person.prototype.get_LastName = function () {
                return this._lastName;
            }
            Person.prototype.set_Age = function (age) {
                this._age = age;
            }
            Person.prototype.get_Age = function () {
                return this._age;
            }
        }

So you can see that person is assigned to a function which is actually also a nested function but it is uses prototype property of an object. Lets instantiate it and check it.

function DisplayClosure() {
        function DisplayClosure() {
            var person = new NewPerson("Brij", "Mishra", 27);

            alert(person.get_FirstName() + " " + person.get_LastName());
            alert("Age: " + person.get_Age());

            person.set_FirstName("Rahul");
            person.set_LastName("Khanna");
            person.set_Age("30");

            alert(person.get_FirstName() + " " + person.get_LastName());
            alert("Age: " + person.get_Age());
        }

So you can see that this also is used in the similar way as Closure.
So what are the benefits of prototypes over closure. There are many..

  • Prototypes provide better support for Intellisense and debugging.
  • Prototypes also provide better performance in several browsers.
  • Prototypes support reflection and that’s why used a lot in ASP.NET AJAX.
  • Closure does not create an instance, it just specialized members to your object. instanceof does not work with Closure. While Prototype configured once then copied to every instance created using new.

Hope you all like it.

Cheers,
Brij

Creating Random number in JavaScript

Hello All

Have you ever needed to create random number in JavaScript?

No.

In C#, creating random number is simple and provides multiple¬†options. Random class is used for the same, it’s Next method used to create random number. It also takes min and max value as parameter to create a random number in a range.

In Javascript it is more simple :). Let’s see that

Math.random is used to create a random number. But it returns a decimal numal number between between 0 (including) to 1(excluding). Let’s see that

function displayRandom()
{
    alert(Math.random());
}

It will create different number each time. So if you want to create a random number say upto 10000 then you can get it by simply writing

var randomnumber = Math.random() * 10000;

Pretty simple Right!!

But it will always create a number less than 10000 (till 9999.999..) and if you take the integer part then the max value you will get 9999. But what if want inclusive of 10000?

Then you can leverage the other method Math.ceil which generates the ceiling number as

Math.ceil(6.0001)

Math.ceil(6.203)

Math.ceil(6.0001)

Math.ceil(6.9001)

For all you will get 7. So if you write the original method as

function displayRandom()
{
    alert(Math.ceil(Math.random()));
}

You will get the number between 0 to 10000 both inclusive. You can also use Math.floor or Math.abs to have your own logic for getting random number in a range.

This is small post but I found it bit interesting and useful sometime.

Cheers,
Brij

Dependency Injection (DI) in {{AngularJS}} – Part 16

Dependency Injection (DI) is one of the hottest terms being used in software development nowadays. Most of the application developers talking about this and try using it in their applications. One of the key reasons Agile methodology, as it is used in almost every project in one or other way and DI easily fits into this model and help in achieving its goal. I have been getting many request to write about DI in AngularJS so let’s start exploring that.

Note ‚Äď This post is a part of series of posts on AngularJS and it is 16th one. Click here to view all the post. Apart from that you can also use the navigation links for next and previous post in each post at the bottom to check all. Continue reading