In this article we’ll cover all about variables and data types and why we need them!

So what are variables ?

Imagine that a variable is a box, and in that box we can put different types of things that are data types. So basically variables can hold many data types: numbers, strings, objects and more.

Why do we need data types?

In programming, data types is an important concept.

We need them so we can be able to operate on variables, and to do that, it is important to know something about the type.

Without data types, a computer cannot safely solve this:

var x = 1 + "two";

Does it make any sense to add “two” to 1? Well normally it would make sense and the result would be 3 but in our case, will our machine add a number to a text? Will it produce an error or will it produce a result?

Let me tell you what will happen!

In this case, when adding a number to a string, JavaScript will treat the number as a string.

Try out var x =”1”+”two” and the result will be

You also need to know that JavaScript treats operations from left to right

See what happens when we tell him to execute this line of code

var x = 1+2 + "two";

So basically JavaScript treated 1 and 2 as numbers until it reached the text “two” and treated all of them as strings.

Let me tell you a magic trick about JavaScript variables: they are dynamic!

=>This means that the same variable can be used to hold different data types:

var x;           // Now x is undefined
x = 77;           // Now x is a Number
x = "RBK";      // Now x is a String

And that was what we call dynamic typing !

If we go back to all the data types of JS, we find that we have 9 types defined by ECMAScript standard which are: Undefined, Boolean, Number, String, BigInt, Symbol, null, Object, Function

A variable that has not been assigned a value has the value undefined.

Boolean represents a logical entity and can have two values: true and false.

Numeric values have two types: Number and BigInt

String type is used to represent textual data.

A Symbol is a unique and an immutable primitive value and may be used as the key of an Object property.

The Null type has exactly one value: null

To know more about objects check out “Introduction to JavaScript Objects”

Functions are regular objects with the additional capability of being callable.

In addition to these objects, we can find Arrays, Array methods, Iterables, Map and Set, WeakMap and WeakSet, Date and time and JSON.

 JavaScript has a standard library of built-in objects that can be determined with the typeof operator.

So typeof operator can help you find the type of your variable.

Let’s test ourselves with a little exercice

var length = 16;          //number 
var lastName = "Johnson"; //String 
var x = {
  firstName: "John",
  lastName: "Doe"
};                        //Object