JavaScript Data Types
You might be wondering why it’s important to know about data types. There is only one main reason — to gather clean and consistent data for computing in the software application. In programming, data types is an important concept. Understanding data types ensures that data is collected in the preferred format and the value of each property is as expected.
What is a Data Type?
In computer science and computer programming, a data type or simply type is an attribute of data which tells the compiler or interpreter how the programmer intends to use the data.
Our interactions (inputs and outputs) with a program are treated in many languages as a stream of bytes. These bytes represent data that can be interpreted as representing values that we understand. Additionally, within a program, we process this data in various ways such as adding them up or sorting them. This data comes in different forms. Examples include:
- your name — a string of characters
- your age — usually an integer
- the amount of money in your pocket — usually a value measured in your local currency.
A major part of understanding how to design and code programs is centered in understanding the types of data that we want to manipulate and how to manipulate that data.
A data type constrains the values that an expression, such as a variable or a function, might take. To be able to operate on variables, it is important to know something about the type. Therefore, the data type defines which operations can safely be performed to create, transform and use the variable in another computation.
When a programming language requires a variable to only be used in ways that respect its data type, that language is said to be strongly typed. Strongly-typed language enforces the definition of data type, and, cross type operation requires type casting. This is why in strongly-typed languages such as; C, C++, C#, Java, Python , you must define what type of value a variable will hold, and, unless some types are highly compatible you will most likely need to cast (convert) one type to another, otherwise you’ll end up with exception, or worse, unexpected operation result. This prevents errors, because while it is logical to ask the computer to add a float to an integer (1.5 + 5), it is illogical to ask the computer to add a float to a string (1.5 + ‘ClarusWay’).
On the other hand, when a programming language allows a variable of one data type to be used as if it were a value of another data type, the language is said to be weakly (or loosely) typed. Weakly-typed language does not require type definition for variables, and a variable can be assigned and reassigned to a different type of data, and data ranges simply doesn’t matter. Let’s jump into JavaScript here…
Where does JavaScript fit?
According to MDN JavaScript is a loosely typed and dynamic language. Since JavaScript is a loosely typed language; variables in JavaScript are not directly associated with any particular value type. As mentioned above, you don’t have to specify what type of information will be stored in a variable in advance. JavaScript automatically types a variable based on what kind of information you assign to it (e.g., that ''
or " "
to indicate string values).
//variable declaration in JavaScript. Note that data types are not defined during the declaration.
let x = 99; // x is holding a number value
let city = 'Istanbul'; // city is holding a string value
let isExists = true; // isExists is holding a boolean value
In addition, since JavaScript is a dynamic language; any variable can be assigned (and re-assigned) values of all types. In JavaScript dynamic typing, variable type decide by its value after code runs the code at compiler/interpreter. This means if a value of variable is integer then the variable will be an integer and if it’s string then the variable type is also string. But the data type hold by a variable can change later when a different type of data type value assigned to it.
let foo = 99; // foo is now a number
foo = 'Istanbul'; // foo is now a string
foo = true; // foo is now a boolean
Many other languages, like C#, require you to declare a variable’s type, such as int, float, boolean, or String.
// variable declaration in C#. Note that data types should explicitly defined during the declaration.
int x = 99;
string city = 'Istanbul';
boolean isExists = true;
Now, the loosely (weakly)- typed and dynamic features of JavaScript is both a blessing and a curse.
var a = 2 + '4';
console.log(a); //output: '24'console.log('Istanbul' + 71) // output: Istanbul71
console.log(7 + 1 + 'Istanbul' + 71) //output: 8Istanbul71
While JavaScript’s type system gives you a lot of flexibility, it lacks the capability of a strongly typed system to warn you when you are trying to add an int to an object, which protects you from spending hours debugging a type error.
JavaScript Data and Structure Types
The latest ECMAScript standard defines nine types:
All types except objects define immutable values (that is, values which can’t be changed). For example (and unlike in C), Strings are immutable. We refer to values of these types as “primitive values”.
Primitive Data Types:
undefined type:
A variable that has not been assigned a value has the value undefined
. The type is also undefined
. If a variable is declared, but not assigned, then its value is undefined
:
let city; // Value is undefined, type is undefined
Any variable can be emptied, by setting the value to undefined
. The type will also be undefined
.
country = undefined; // Value is undefined, type is undefined
Boolean type:
Boolean represents a logical entity and can have two values: true
and false
. This type is commonly used to store yes/no values: true
means “yes, correct”, and false
means “no, incorrect”. Booleans are best for conditional testing.
String type:
JavaScript’s String
type is used to represent textual data. A string (or a text string) is a series of characters like “ClarusWay Courses”. Each element in the String occupies a position in the String. The first element is at index 0
, the next at index 1
, and so on. The length of a String is the number of elements in it.
Strings are written with quotes. In JavaScript, there are 3 types of quotes.
- Double quotes:
"Hello"
. - Single quotes:
'Hello'
. - Backticks:
`Hello`
.
Double and single quotes are “simple” quotes. There’s practically no difference between them in JavaScript. On the other hand, backticks are “extended functionality” quotes. They allow us to embed variables and expressions into a string by wrapping them in ${…}
, for example:
let name = "ClarusWay";
// embed a variable
alert( `Hello, ${name}!` ); // Hello, ClarusWay! // embed an expression
alert( `the result is ${98 + 1}` ); // the result is 99
Unlike some programming languages (such as C), JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it.
However, it is still possible to create another string based on an operation on the original string. For example:
- A substring of the original by picking individual letters or using
String.substr()
. - A concatenation of two strings using the concatenation operator (
+
) orString.concat()
.
In some languages, there is a special “character” type for a single character. For example, in the C, C# and in Java it is called “char”.
In JavaScript, there is no such type. There’s only one type: string
. A string may consist of zero characters (be empty), one character or many of them.
Number type:
ECMAScript has two built-in numeric types: Number and BigInt
The Number type is a double-precision value (numbers between -(2⁵³ − 1) and 2⁵³ − 1). Numbers can be written with, or without decimals.
let x1 = 99.00; // Written with decimals
let x2 = 99; // Written without decimals
In addition to representing floating-point numbers, the number type has three so-called “special numeric values: +Infinity
, -Infinity
, and NaN
("Not a Number").
Besides regular numbers, there are so-called “special numeric values” which also belong to this data type: Infinity
, -Infinity
and NaN
.
The number type has only one integer with two representations: 0
is represented as both -0
and +0
. (0
is an alias for +0
.) +0 === -0
is true
. But, you are able to notice the difference when you divide by zero:
NaN
represents a computational error. It is a result of an incorrect or an undefined mathematical operation, for instance:
console.log( "not a number" / 2 ); // output: NaN, (because such division is erroneous)
NaN
is sticky. Any further operation on NaN
returns NaN
:
alert( "not a number" / 2 + 5 ); // NaN
So, if there’s a NaN
somewhere in a mathematical expression, it propagates to the whole result.
BigInt type:
BigInt
is a new primitive that provides a way to represent whole numbers larger than 2^53, which is the largest number Javascript can reliably represent with the Number
primitive.
const x = Number.MAX_SAFE_INTEGER;
// ↪ 9007199254740991, this is 1 less than 2^53
const y = x + 1;
// ↪ 9007199254740992, ok, checks out
const z = x + 2
// ↪ 9007199254740992, wait, that’s the same as above!
The BigInt
type is a numeric primitive in JavaScript that can represent integers with arbitrary precision. With BigInt
s, you can safely store and operate on large integers even beyond the safe integer limit for Number
.
A BigInt
is created by appending n
to the end of an integer or by calling the constructor.
console.log(9007199254740995n); // → 9007199254740995n
BigInt("9007199254740995"); // → 9007199254740995n
Symbol type:
A Symbol is a unique and immutable primitive value and may be used as the key of an Object property. In some programming languages, Symbols are called “atoms”.
Structural Root Primitive
null:
The value null
represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations.
The Null type has exactly one value: null.
The special null
value does not belong to any of the types described above. It forms a separate type of its own which contains only the null
value:
let city = null;
In JavaScript, null
is not a “reference to a non-existing object” or a “null pointer” like in some other languages. It’s just a special value which represents “nothing”, “empty” or “value unknown”. The code above states that city
is unknown.
Structural Data Types
objects:
In computer science, an object is a value in memory which is possibly referenced by an identifier. A JavaScript object is a mapping between keys and values. JavaScript objects are written with curly braces {}
. Object properties are written as key:value pairs, separated by commas. Keys are strings and values can be anything.
const person = {
firstName:"Adam",
lastName:"Eve",
age:50,
eyeColor:"brown"
};
The object (person) in the example above has 4 properties: firstName, lastName, age, and eyeColor.
functions:
Functions are regular objects with the additional capability of being callable.
The typeof Operator
You can use the JavaScript typeof
operator to find the type of a JavaScript variable. The typeof
operator returns the type of a variable or an expression. It’s useful when we want to process values of different types differently or just want to do a quick check;
typeof undefined // "undefined"
typeof 0 // "number"
typeof 10n // "bigint"
typeof true // "boolean"
typeof "Istanbul" // "string"
typeof Symbol("id") // "symbol"
typeof Math // "object" (*)
typeof null // "object" (*)
typeof alert // "function" (*)
The last three lines may need additional explanation:
Math
is a built-in object that provides mathematical operations. It serves just as an example of an object.- The result of
typeof null
is"object"
. That’s an officially recognized error intypeof
behavior, coming from the early days of JavaScript and kept for compatibility. Definitely,null
is not an object. It is a special value with a separate type of its own. - The result of
typeof alert
is"function"
, becausealert
is a function. Functions belong to the object type. Buttypeof
treats them differently, returning"function"
. That also comes from the early days of JavaScript. Technically, such behavior isn’t correct, but can be convenient in practice.
Conclusion
Programming languages all have built-in data structures, but these often differ from one language to another. In this article, we have covered the data types and data structures in JavaScript. The are basically 9 data types according to official MDN documentation.
JavaScript is one of the most popular programming language. It is the programming language of the Web. The learning curve may be easy at the beginning but requires attention as you get into code. There are further details about “undefined” and “null” which have custom properties built-in to JavaScript. I am planning to write my next article on this topic. Until then, happy coding mates..