Javascript Data Types

Javascript Data Types

·

2 min read

In this post, I will be describing JavaScript's main data types.

Javascript can hold many different types of data such as numbers, strings, and objects.

Javascript Is A Weakly-Typed Language

What is cool about weakly typed language is that you do not have to be conscious of data types for your code to execute. In a strongly typed language, you must assign all variables a data type. If you later try to change to a different data type, you will get an error.

For example, if you add a string to a number, in strongly typed languages you will get an error. In Javascript, you simply get a weird answer.

In fact, you can create a variable and assign it a different type of data later if you want.

Strings

Strings are a series of characters. We can create them using double or single quotes. You can also, if you want, break them into two lines of code as done below.

Javascript Code

var a = "random string";

Javascript Code

var a = 
"random string";

Numbers

JavaScript, unlike many other languages, only has one type of number, although they can be written with decimals or without decimals or even with scientific notation.

Javascript Code

var num = 123;

Boolean

A boolean means that a variable or constant is either true or false. These are used for us to test whether a conditional such as if statement is true or false.

Javascript Code

var a = new Boolean(true);
document.write(a);

Arrays

Arrays are used to store multiple values in the same variables. Use either [] or {} to create the name-value pairs.

Javascript Code

var a = ["apple", "orange", "pear"];

We will go into more detail on arrays later. Keep in mind that array indexes start counting at 0 and not 1.

Object

Javascript Code

let person = new Person();

In the above, we have declared a person and his properties. This is an object that you can use as an object just like any OOP language.

Typeof operator

This is used to test the data type of the variable.

Javascript Code

var a = 123;
document.write(typeof a);

Undefined

By default, variables are undefined if you don’t give them any value.

Javascript Code

var a; 
document.write(a);
document.write(typeOf a);

Empty

A variable with no data (“”) is also equal to undefined. This is a legal type.

Javascript Code

var a = "";

Null

Null is a variable that does not exist. Interestingly enough, null is considered an object.

Javascript Code

var a = NULL