Data Types in JavaScript
JavaScript supports various data types that are used to store different kinds of values. Understanding these data types is essential for writing robust code. Let's explore each data type and how to determine the type of a variable using the 'typeof' operator.
Data Type | Description |
Number | Represents integer or floating point numbers. |
String | Represents a sequence of characters (text). |
Boolean | Represents true or false values. |
undefined | Indicates that the value is not defined. |
null | Represents the absence of a value or null value. |
BigInt | Introduced in ES6, used for large integer values. |
Symbol | Introduced in ES6, represents unique and immutable instances. |
Function | Represents a declared function, including arrow functions. |
Object | Represents a collection of key-value pairs of different data types. |
To find the data type of a variable in JavaScript, we can use the 'typeof' operator, which returns the type of the variable.
var a = 10;
typeof a; //'number'
a = 'Hi';
typeof a; //'string'
a = true;
typeof a; //'boolean'
var b;
typeof b; //'undefined'
a = null;
typeof a; //'object'
a = 12233n;
typeof a; //'bigint'
const sym = Symbol("foo");
typeof sym; //'symbol'
a = () => {console.log('Hi')};
typeof a; //'function'
a = function() {console.log('Hi')};
typeof a; //'function'
a = {key: 'value'};
typeof a; //'object'
a.key; //'value'
a = ['test', 'value'];
typeof a; //'object'
a[0]; //'test'
A function is technically an object, but the 'typeof' operator returns 'function' for functions.
It's important to note that the 'typeof' operator on null also returns 'object.'
Arrays are another data type in JavaScript, and they are of type 'object.'
Arrays and objects share some similarities. In arrays, the keys are numeric values (zero-based index), while objects use string keys to access their elements using the dot notation.
Numbers, Strings, and '+'
The '+' operator behaves differently for numbers and strings. For numbers, it performs addition, while for strings, it concatenates them. Combining strings and numbers results in string concatenation. Remember to use brackets for precise calculations.
String to Number
To convert strings to numbers, JavaScript provides two methods: 'parseInt()' and 'parseFloat()'. 'parseInt()' allows specifying the base as the second parameter, while 'parseFloat()' only accepts one parameter.
Numbers in Different Base Systems
JavaScript allows representing numbers in various number systems by using specific prefixes in their literals. BigInt can be represented in any number system by adding a trailing 'n.'
Prefix | Number System |
0 or 0o or 0O | Octal |
0x or 0X | Hexadecimal |
0b or 0B | Binary |
No prefix | Decimal |
String Declarations
In JavaScript, strings can be declared in three ways:
Single Quotes
Double Quotes
Template Literals: These allow for computed values to be inserted within strings using placeholders (${...}).