#002 JavaScript with Dimos: Data Types
Hey there 👋 I am Dimos, a senior software engineer and software architect at arconsis. From time to time, I publish articles into the series “JavaScript with Dimos”, where I am trying to analyze a JavaScript topic and to focus on the core concepts of JavaScript.
In the chapter “JavaScript’s Grammar” we will take a look at JavaScript’s basic grammar, variable declarations and data types.
Chapter’s Posts Roadmap
- Variables and Constants
- Data Types (This article)
This is the second article of this chapter which focuses on built-in data structures available in JavaScript.
What is a data type?
Data structures are built-in in all programming languages, but often these differ from one language to another.
The data type is a classification that specifies which type of value a variable has in our code.
Dynamic typing
JavaScript is a loosely typed and dynamic language. Variables in JavaScript are not directly associated with any specific value type, and each variable can be assigned (and re-assigned) values of all types. For example:
let foo = 42; // foo is now a "number"
foo = 'bar'; // foo is now a "string"
foo = true; // foo is now a "boolean"
JavaScript types
There are two types of data types in JavaScript.
- Primitive data type (immutable values)
- Boolean type
- Number type
- String type
- Undefined type
- Null type
- BigInt type
- Symbol type (added in ES6) - Objects (reference) data type
Primitive data types are immutable, which means that values can not be changed and are always copied “as whole value”. On the other hand, objects used as key-value pairs of collection which are stored and copied “by reference”.
typeof Operator
The typeof
operator inspects the data type of its given operand, and always returns one of the following values as string:
- “boolean”
- “number”
- “bigint”
- “string”
- “undefined”
- “symbol”
- “object”
- “function”
As we can see, typeof
operator returns all built-in JavaScript’s data types apart from null
. We will take a closer look below which value is returned when we apply typeof
operator on a null. Also, we can notice that it returns "function"
as another new value, as “function” is a top-level built-in type in JavaScript.
Boolean Type
It represents logical entities which can have one of these two values: true
or false
. If we use typeof
to inspect variables of that type, it will return "boolean"
as string value. For example:
const isOrderValid = true;
typeof isOrderValid; // "boolean"const isOrderCreated = false;
typeof isOrderCreated; // "boolean"
Boolean primitives and Boolean objects
We can use Boolean constructor to create a new Boolean
object, which is just an object wrapper for a boolean value. To call the constructor, we must provide a value as an argument that will be converted to a boolean value.
The Boolean object has false as initial value, if the value is absented or +0
, -0
, null
, false
, NaN
, undefined
, or the empty string (""
) (these values are considered as “falsy”). While, the rest values, including any object, an empty array ([]
), or the string "false"
, have as initial value true.
We can use constructor via the two following ways:
new Boolean(true) // constructor function
Boolean(true) // non-constructor functiontypeof new Boolean(true); // object
typeof Boolean(true); // boolean
JavaScript distinguishes between Boolean objects and primitive boolean values.
Boolean literals (true / false) and values created by the non-constructor Boolean function (without using the new keyword) are primitive strings as type coercion (implicit conversion) is performed when called as a function. Although, the values created using constructor Number function (via new keyword) are objects. That’s why we rarely want to use the Boolean constructor at all.
Be careful, we should not confuse the primitiveBoolean
valuestrue
andfalse
with thetrue
andfalse
values of theBoolean
object. Any boolean object is evaluated to true when passed to a conditional statement.
const x = new Boolean(false); // constructor function
const y = Boolean(false); // non-constructor functionif (x) {
// code block is executed
console.log("enters if statement, using function constructor");
}
if (y) {
// code block is not executed
console.log("enters if statement using function");
}
if (false) {
// code block is not executed
console.log("enters if statement using literal");
}
As we can above, any Boolean object is evaluated to true
when passed to a conditional statement, as the problem is that we’ve created an object wrapper around the false
value, but objects themselves are "truthy".
If we want to use a Boolean object, then we should use it in a non-constructor function (without using the new keyword).
Hence, we should avoid using a
Boolean
object to convert a non-boolean value to a boolean value. To perform this task, instead, we should useBoolean
as a function (without using the new keyword), or a double NOT operator:
var x = Boolean(expression); // use this...
var x = !!(expression); // ...or this
var x = new Boolean(expression); // don't use this!
Number Type
It represents represents integer and floating numbers. The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value. Values outside of the range from Number.MIN_VALUE
to Number.MAX_VALUE
are automatically converted to either +Infinity
or -Infinity
If we use typeof
to inspect variables of that type, it will return "number"
. For example:
const num1 = 9; // literal
typeof num1; // "number"const num2 = 9.633; // literal
typeof num2; // "number"const num3 = 9e6; // literal
typeof num3; // "number"
Number primitives and Number objects
We can use Number constructor to create a new Number object, which is just an object wrapper for a number value. We can use constructor via the following two ways:
const x = new Number(3); // constructor function
const y = Number(3); // non-constructor functiontypeof new Number(3); // object
typeof Number(3); // number
typeof 3; // numbernew Number(3) === 3; // false
Number(3) === 3; // true
3 === 3; // true
JavaScript distinguishes between Number objects and primitive number values.
Number literals and values created by the non-constructor Number function (without using the new keyword) are primitive strings as type coercion (implicit conversion) is performed when called as a function. Although, the values created using constructor Number function (via new keyword) are objects. That’s why we rarely want to use the Number constructor at all.
String Type
It represents some text data. We can create strings using single or double quotes surrounding one or more characters. If we use typeof
to inspect variables of that type, it will return "string"
. For example:
const str1 = 'foo';
typeof str1; // "string"const str2 = "bar";
typeof str2; // "string"const str3 = `The string values are ${str1} and ${str2}`;
typeof str3; // "string"
String primitives and String objects
We can use String constructor to create a new String
object, which is just an object wrapper for a string value. We can use constructor via the following two ways:
new String(str); // constructor function
String(str); // non-constructor functiontypeof String('foo'); // string
typeof new String('foo'); // object
JavaScript distinguishes between String objects and primitive string values.
String literals (create by double or single quotes) and strings returned from String using the non-constructor function (without using the new keyword) are primitive strings as type coercion (implicit conversion) is performed when called as a function. Although, the values created using constructor function (via new keyword) are objects. That’s why we rarely want to use the String constructor at all.
Undefined Type
It represents a variable which has been declared but has not been assigned with any value. If we use typeof
to inspect variables of that type, it will return "undefined"
. For example:
let str;
console.log(str); // undefined
typeof str; // "undefined"
Null Type
It is a special value that represents empty or unknown value. Be careful, null is “buggy” when used with the typeof
operator, as if we use typeof
to inspect variables of that type will return "object"
. For example:
let str = null;
console.log(str); // null
typeof str; // "object"
BigInt Type
If we need bigger number then, we should use BigInt as data type (was introduced in the newer version of JavaScript). If we use typeof
to inspect variables of that type, it will return "bigint"
. For example:
const bigNum1 = BigInt(Number.MAX_SAFE_INTEGER);
// 9007199254740991n
typeof bigNum1; // "bigint"
Symbol Type
It has been introduced in JavaScript ES6 version and is an immutable primitive value that is unique, and can be used to create unique identifiers for objects. Symbols are always unique. As a result, even if we create many symbols with the same description, the values will be different.
If we use typeof
to inspect variables of that type, it will return "symbol"
. For example:
let symbol1 = Symbol("Test")
let symbol2 = Symbol("Test")
console.log(symbol1 === symbol2) // returns "false"
typeof symbol1; // "symbol"
typeof symbol2; // "symbol"
Object Type
It is a is a non-primitive data-type which is key-value and allows us to store collections of data. If we use typeof
to inspect variables of that type, it will return "object"
. For example:
const user = {
firstName: 'Dimos',
lastName: 'Botsaris',
age: 33
};
typeof user; //"object"
We will take a deep dive into JavaScript Objects in next tutorials.
Data Type Conversions
Type conversion means casting from one data type to another. In JavaScript we can use 2 kinds of type conversion:
- Implicit Conversion — automatic conversion via compiler (coercion)
- Explicit Conversion — manual conversion
Implicit Conversion (coercion)
It is the automatic values casting from one data type to another (such as strings to numbers)
const num = 1;
const str = '3';
const bool = true;const result1 = num + str;
console.log(result1) // output: "31"
const result2 = str + bool;
console.log(result2); // output: "3true"
const result3 = str - '2';
console.log(result3); // output: 1
In the above example, JavaScript has implicitly casted the 1 from a number into a string, resulting in a string of "31"
. If we want to have a sum as number (4) as result we should to explicitly cast str to number via Number
constructor. For example:
const num = 1;
const str = '3';const result = num + Number(str);
console.log(result); // output: 4
Explicit Conversion
In JavaScript, we can also convert one data type to another manually via explicit conversion using constructors like String, Number.
- Convert to String Explicitly
let result = String(123);
console.log(result); // output: "123"result = String(1 + 2);
console.log(result); // output: "3"result = String(false);
console.log(result); // "false"result = String(undefined);
console.log(result); // "undefined"result = String(null);
console.log(result); // "null"
- Convert to Number Explicitly
let result = Number("12");
console.log(result); // output: 12result = Number("12") + 1;
console.log(result); // output: 13result = Number(true);
console.log(result); // output: 1
result = Number(false);
console.log(result); // output: 0result = Number(null);
console.log(result); // output: 0
result = Number(' ')
console.log(result); // output: 0result = Number('hello world');
console.log(result); // output: NaN
result = Number(undefined);
console.log(result); // output: NaN
result = Number(NaN);
console.log(result); // output: NaN
- Convert to Boolean Explicitly
let result = Boolean(0);
console.log(result); // output: false
result = Boolean(undefined);
console.log(result); // output: false
result = Boolean('');
console.log(result); // output: false
result = Boolean(null);
console.log(result); // output: false
result = Boolean(NaN);
console.log(result); // output: falseresult = Boolean(1);
console.log(result); // output: trueresult = Boolean("true");
console.log(result); // output: trueresult = Boolean("0");
console.log(result); // output: trueresult = Boolean("false");
console.log(result); // output: trueresult = Boolean("hello");
console.log(result); // output: trueresult = Boolean({});
console.log(result); // output: trueresult = Boolean([]);
console.log(result); // output: true
These are all we need to know about data types and type casting in JavaScript. Meanwhile, please feel free to post any questions, comments, or feedback in the comment section below.
Follow on Twitter here!
Follow on Github here!