Skip to main content

Variables and Data Types

Variables

After printing out your first "Hello World", it is time to dive deeper into variables and datatypes. When we talk about variables, we usually refer to some construct that can store a value of one kind or another. This is depicted below:

Variables Intro

Here, we can see three variables storing different datatypes such as string, integer and double (or float point).

Creating a variable in JavaScript can easily be done in a two different ways:

let foo = "Hello World";
var bar = 123;

In the code block, we declare three variables foo and bar and immediately assign a value to them. We could also only declare the variables without the initial value assignment, which would simply reduce the statement to let foo;.

note

Notice that there is a difference between let and var when declaring a variable, which we will cover when talking about functions later on.

These two variables can be changed by reassigning a value to them, whereas a constant cannot be changed and thus should have a value upon declaration:

const doe = 123.45;

A reassignment of the constant value doe is therefore not possible! Trying to reassign it anyway using a subsequent doe = 567 will result in a type error. Try it out:

Task:

Declare a constant 'doe' with a value of 5 and try to change it's value in a new line.



Data Types

You have already seen some data types above - to be precise, we used the types String (for the variable foo) and Number (for the variables bar and doe). There exist, however, more datatypes in JavaScript:

Data TypeDescriptionExample
StringA sequence of alphanumerical characters enclosed in single or double quoteslet foo = "Hello World"
NumberA number - these are not enclosed in quotes and can have decimal placeslet bar = 123
ObjectBasically anything - everything in JavaScript is represented as an object and can be stored in a variable (also functions!)let obj = {} (and all other examples contained here)
ArrayA data structure able to store multiple valueslet arr = [1, 'ABC', {}] (note: we can use multiple data types in this structure)
BooleanA binary value being either true or false (representing '1' or '0')let bool = true

What stands out again in all these examples is the absence of a distinct type declaration that you would expect from strongly typed languages such as Java - in JavaScript, there is no need to explicitly state the variable's data type.