Data Types in JavaScript

Data Types in JavaScript

This article explains data types in JavaScript.

YouTube Video

Data Types in JavaScript

JavaScript has data types for classifying values, which can be broadly divided into primitive types and object types. Data types determine what kind of data is stored in a variable and influence how it can be manipulated.

Primitive Types

Primitive types are simple data types that represent a single value. JavaScript has the following 7 primitive types.

number

1let num = 42;
2let pi = 3.14;
3
4console.log("Value of num:", num);
5console.log("Value of pi:", pi);
  • number is a type used for handling numerical values, including integers and floating-point numbers (decimals). Handling values that exceed certain limits results in Infinity or NaN (Not-a-Number).
1// Decimal calculations
2console.log(0.1 + 0.2 === 0.3); // false
3console.log(0.1 + 0.2); // 0.30000000000000004
4
5// Calculations with large numbers
6console.log(9007199254740991 + 1); // correct value
7console.log(9007199254740991 + 2); // incorrect value
  • In JavaScript, numbers are represented as floating-point numbers. As a result, certain decimals (especially those that cannot be precisely represented in binary) may not be accurately expressed.
  • When precise calculations are required, such as for monetary values, it is necessary to avoid such rounding errors. For example, you can use BigInt or adjust the number of decimal places with toFixed().

string

1let greeting = "Hello, world!";
2let char = 'A';
3const message = `"${greeting}" in JavaScript`;
4
5console.log("Value of greeting:", greeting);
6console.log("Value of char:", char);
7console.log("Value of message:", message);
  • string is a data type used for handling text, representing a sequence of characters. It is represented by enclosing text in single quotes (') or double quotes ("). From ES6 onwards, template literals allow easy embedding of variables using backticks (). To embed a variable, use the ${} syntax.

boolean

1let isAvailable = true;
2let hasError = false;
3
4console.log("Value of isAvailable:", isAvailable);
5console.log("Value of hasError:", hasError);
  • boolean represents a logical value and can only have two values: true or false. It is used as the result of conditional expressions or as a flag.

null

1let result = null;
2
3console.log("Value of result:", result);
  • null is a data type that explicitly indicates 'no value.'. null is set by developers to indicate an intentional emptiness.

undefined

1let score;
2let subject = undefined;
3
4console.log("Value of score:", score);     // undefined
5console.log("Value of subject:", subject);
  • undefined is a data type that means 'undefined.'. undefined is automatically assigned when a variable is declared but not assigned a value.

bigint

1let bigIntValue = 9007199254740991n;
2let anotherBigInt = 123456789012345678901234567890n;
3
4console.log("Value of bigIntValue:", bigIntValue);
5console.log("Value of anotherBigInt:", anotherBigInt);
  • bigint is a data type for handling large integers. bigint allows accurate representation of large integers that cannot be represented by the number type. bigint literals are represented by appending n to the end of a number.
  • bigint is a type for handling integers of arbitrary size, with no range limitations. However, bigint and number cannot be directly operated on together, so caution is required.

Symbol

1let sym1 = Symbol('id');
2let sym2 = Symbol('id');
3
4console.log("sym1 === sym2:", sym1 === sym2); // false
  • Symbol is a data type used to create unique identifiers. It is created using Symbol() and can be used as a property of an object. Unlike other primitive types, Symbol has unique values, so even with the same content, it is treated as a different Symbol.

Object Types

Object types are data structures that can store multiple values. An object is a collection of key-value pairs and can have properties and methods.

Object

1let person = {
2    name: "John",
3    age: 30,
4    isEmployee: true
5};
6console.log(person.name); // John
  • Object is a collection of properties (key-value pairs) that can store various types of data. Objects are represented by curly braces {}, and each property is connected by : between the key and value.

Array

1let numbers = [10, 20, 30];
2console.log(numbers[0]); // 10
3console.log(numbers[1]); // 20
4console.log(numbers[2]); // 30
5console.log(numbers[3]); // undefined
  • Array is a list that holds multiple values in an ordered manner. Arrays are represented by square brackets [], and values are separated by commas ,. Each element is accessed using an index that starts at 0.

Function

1function greet(name) {
2    return "Hello, " + name;
3}
4console.log(greet("Alice")); // Hello, Alice
  • Functions are a type of object and reusable blocks of code. Functions can be defined using the function keyword.

Other Object Types

  • JavaScript also has built-in object types such as Date, RegExp, Map, and Set. These handle data according to specific use cases.

Type Conversion

Implicit and explicit type conversions are frequently performed in JavaScript.

Implicit Type Conversion

  • JavaScript may automatically convert types when performing operations between different types.
1let result = 5 + "5"; // "55" (the number is converted to a string)
2
3console.log(result);
  • In this example, the number 5 is implicitly converted to a string, resulting in the string "55".

Explicit Type Conversion

  • Developers can also perform type conversions explicitly.
1let num = "123";
2let convertedNum = Number(num); // Converts "123" to the number 123
3
4console.log(typeof num);
5console.log(typeof convertedNum);
  • In this example, the Number() function is used to explicitly convert the string "123" into the number 123.

Type Checking

In JavaScript, you can use the typeof operator to check the data type of a variable.

 1// Output: The type of 42 is: number
 2console.log('The type of 42             is:', typeof 42);
 3
 4// Output: The type of 42 is: bigint
 5console.log('The type of 42n            is:', typeof 42n);
 6
 7// Output: The type of "hello" is: string
 8console.log('The type of "hello"        is:', typeof "hello");
 9
10// Output: The type of true is: boolean
11console.log('The type of true           is:', typeof true);
12
13// Output: The type of undefined is: undefined
14console.log('The type of undefined      is:', typeof undefined);
15
16// Output: The type of null is: object
17console.log('The type of null           is:', typeof null);
18
19// Output: The type of Symbol() is: symbol
20console.log('The type of Symbol()       is:', typeof Symbol());
21
22// Output: The type of {} is: object
23console.log('The type of {}             is:', typeof {});
24
25// Output: The type of function () {} is: function
26console.log('The type of function () {} is:', typeof function () {});

Conclusion

  • Primitive types include number, string, boolean, null, undefined, and symbol.
  • Object types include Object, Array, Function, among others.
  • Since both automatic and explicit type conversions occur, it's important to understand the proper usage of data types.

You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.

YouTube Video