Data Types



Introduction


We have all heard of this term somewhere or the other but what actually are Data types and why do we even need them in the first place?





A Data type or simply type is an attribute(property) of data that tells the compiler or interpreter how the programmers like us intend to use the data.

Basically, they convey what we want to the compiler or interpreter.

So, As we have a clear understanding of what data types actually are, let us look at Data Types in Javascript.


In JavaScript data types are divided into two major categories -

  1. Primitive Data Type

  2. Non-Primitive(Reference) Data Type.

Both these categories are further divided into various categories and we will have a detailed study of each and every one of them.



Var, const and let

Whenever we need to store something around us what do we need?

We need a box or a container to hold that thing for us.

Similarly to store a value in javascript, we need a container for it.

There are three ways to store values in javascript and that are

  • Variable

  • Constants

  • Let

All three of them can contain any type of data whether it is string, numbers or boolean. Whatever we decide to store in them their type will be set accordingly


Variables


Variables are the data containers declared using the var keyword. We decide the name for a variable and assign a value to it.

The process of creating a variable using var keyword is known as declaration and the process of assigning the variable a value is known as initialisation.

Now there is one more interesting feature to variables, which we derive from its name itself, that is its value can vary, that is variables can be redeclared and updated.




In the example above the variable first is declared and initialised with the value “hello” and later it is redeclared and assigned a value “world”


Const


As the name suggests constants are the data containers in which the value remains the same that is constant throughout the program.

We can declare a constant using const keyword. After assigning a value to a constant we cannot redeclare or update it.




Here the constant is named as first and contains a string value that is “hello”.


Let


Let data containers are very similar to var but the only difference is let can be updated but not redeclared.It allows us to update the the value assigned to it but we cannot redeclare it.




Notice the difference between var and let. Here we just updated the value of first instead of redeclaring it again.






Characteristics of Javascript


But before understanding data type in detail, let us understand some major characteristics of Javascript.



  • Javascript is a dynamic type language i.e we don’t need to specify the type of data that we will store in a variable or a constant because Javascript Engine takes care of it.

Okay so what exactly does the above statement implies?

It means that we can simply assign any value to a variable or a constant like string, number, or boolean.

We can consider variables or constants as a box in which we can store any type of data.



Let us have a look at how we will implement this in code.



In the example above temp is a variable and is holding a number and temp1 is also a variable but is holding a string. The point to notice is that we did not specify the type for any one of them. Javascript automatically identifies our choice and act accordingly.




  • Javascript variables are loosely typed which means that you can assign any type of literal values to a variable e.g. string, integer, float, boolean, etc, and redeclare it later. That means we have the flexibility to change our minds anytime during the program and JavaScript will act accordingly.




Now let us look at our good friend box. Here it first contained a string value which was then replaced by a number and finally was replaced by a boolean value.

Let us have a look at some code.




In the example above we first declared the variable first as a number and then as a string.


Primitive Data Types


Introduction


As we know that we need to tell the interpreter about our choice of data types. But think of a situation in which each programmer is creating their own data types according to their preference. What will happen? Our interpreter will be super confused about what to do and how to do it. Moreover no programmer will be able to understand the code of other programmers. Ohh!!! What confusion..




But thank god there is an easier way. Javascript defines the 5 most data types for us to choose from just like a restaurant offers us a menu.

These data types act as building blocks and help to ensure clear and smooth communication between the programmer and the interpreter. These are 5 types of primitive data types in JavaScript-



Now let us look at each and every data type in detail-


  1. Strings


Strings are a series of characters like “Learning JavaScript”. Whenever we want to store a textual value we use strings.

We can write strings using-

  1. Single quotes

  2. Double quotes

  3. Backticks

Let us look at an example of how to write strings in JavaScript.



In the example above we stored strings using single quotes, double quotes, and backticks where single quotes and double quotes are practically the same but backticks provide us with some functionality. When we want to include the value of a Javascript variable inside an expression we can do that in the following way-




The output for the above example will be Hello user 1. We see that the value of num is replaced by its original value, this is exactly how backticks help us.

Primitive values like Strings cannot have properties or methods(because they are not objects) but with Javascript, methods, and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.



That means we can play around with strings a lot!!! So let us now learn how exactly we can do that.


String Length


If you are given a string and you want to know the exact length of the string how are you gonna do that?

We can simply use the length property of the strings which return the length of the string. Let us look at how to write it in the code.




Yes, it is that simple. If you will print len then you will get 18 i.e. the length of the string stored in length.




String Inside String


What if we want to find a substring from a string?

We have various methods to do that. If we want to find out the exact position(index) i.e the first occurrence of the substring we use indexOf() method.

For example if we want to find out the position of “how” in the given string “Hello how are you?”, then we will pass “how” as a parameter in the method indexOf, which will return the first occurrence of the specified string in the index. Let us look at how can we do that-




The value of len in the above example will be 6 i.e. the starting index of “how”.

Now, Instead of finding the first index, we can also find the last index i.e the last occurrence of the string. Then we use the method lastIndexOf() in which we pass the string whose last occurrence we want to know.




The value of len in the above example will be 19 i.e. the last index of “Hello”.


Both indexOf(), and lastIndexOf() return -1 if the text is not found.

Both methods accept a second parameter as the starting position for the search.

In the example below, we passed the parameter 10 with the string, now the start position of the search will be 10.




In the example below, we passed the parameter 10 with the string, now the start position of the search will be 10.

We can also use the search() method to search for a string and return the position of the match.




The value of len in the above example will be 6 i.e. the first index of “how”.







Extracting String from String


Extracting means taking a part out. So to extract a string from another string we have three methods-


  • slice(start, end)

  • substring(start, end)

  • substr(start, end)

The slice() method extracts a part of a string and returns the extracted part in a new string. The method takes two parameters: the start position, and the end position(end not included).




The value of res in the above example will be Banana.

We can also omit the second parameter, which will result in slicing i.e. extracting the rest of the string.




The value of res in the above example will be Banana, Kiwi.

You might be curious what will happen if we provide negative values inside, then simply the counting will begin from the end.




The value of res in the above example will be Banana.

So that is enough for slicing, isn’t it😂😂?





Okay, we have learned a lot about slice. Let us now understand the substring() method. substring() is very similar to slice() but the only difference is that it cannot accept negative values.



The value of res in the above example will be Banana, I am sure you must have guessed it right.

Last but not the least, javascript also provides us substr() method which also helps us to extract strings. In substr() the first parameter specifies the starting point but the second parameter specifies the length of the string to be extracted.



The value of res in the above example will be Banana.


Converting to uppercase or lowercase


If we have a string with us and we wish to change the entire string to uppercase or to lowercase then we have two methods to do the same.


toUpperCase() - This method helps us to convert the string into uppercase. Now see how we can that-



The value of res in the above example will be “HELLO, HOW ARE YOU?”






toLowerCase() - This method helps us to convert the string into lowercase. Now see how we can that-




The value of res in the above example will be “hello, how are you?”


Concatenating two strings


Concatenating two strings means joining two strings. We have two ways to do that -

  1. Using the + operator, we can simply use the + operator between two strings to concatenate them.

  2. Using concat() method.

Let us look at an example-




Both res1 and res2 will have the same value “Hello How are you?”


LAB EXERCICE-

Strings - CodeSandbox


  1. Numbers


We all know what numbers, we have all worked with them somewhere or the other in our life. But by definition Numbers represent integer and floating numbers (decimals and exponentials).For example-




The example above represents 3 different types of numbers.


Numbers can also store the values like +infinity, -infinity, and NaN(not a number).



In the example above when we divide string by number we get NaN,

As this operation is not allowed.

After the knowledge that you have gained from the two topics, an idea might cross your mind: what will happen if we add a string and a number? Can you think of any result?




The value of z in the above example will be 1020. Yes!! They get concatenated just like strings.


  1. Boolean


Boolean represents a logical entity. It can have 2 values either true or false. For example-




The correct and wrong in the above example simply holds true and false value respectively.







  1. Undefined


Now you might wonder what exactly is Undefined. Undefined refers to the type of data whose value is not defined. Let’s say we declare a variable and not assign any value to it then it will have an undefined value. For example-




We can also explicitly set the value to undefined. For example-




Then variable random in the above examples holds the value undefined.


  1. Null


The last primitive data type that we are going to discuss is null.

A null value means no value i.e an empty or unknown value. It is something that doesn’t exist. For example-










From this, we end our discussion on primitive data type and you should be very proud of yourself to be able to come this far. Well done!!! Keep Going😀😀😀







In the upcoming discussion, we will study the non-primitive data types and great detail while looking at all the examples so that you have a firm understanding of the same. See you there!!





Non- Primitive Data Types


As we are aware that javascript provides us with some basic data types to work with but it also provides us with an ability to create our own data types as objects, functions, and arrays. Let us look at how we can do that.


  1. Functions


So what exactly are functions? Functions are objects that execute a block of code and may or may not return any value.

We provide a certain input and receive an output based on the body of the function.




Take an instance that we need to create a line and change its thickness. We can create 2 functions


  • First to create a line

  • Second to change its thickness


We see how conveniently we divided the entire task into small functions. These functions also help with reusability, like if we want to create a circle and then change its thickness then we can use the change thickness function that we created earlier.





Declaring a function


Declaring a function is very easy.

  • A function is declared using the function keyword.

  • The body of the function is written within {}.

  • While naming a function we should keep in mind all the rules used for variable naming.

  • We should try to keep the name of the function very similar to the function that it performs.


We can define the body of the function as per our choice and need.

Let us look at an example and the output of the code will be the “Say Hello” string in the console.




Calling a function