Every programming languages have a built-in data structure. but they differ from one language to another. JavaScript is dynamic and loosely types language.
There are two types of data structure in JavaScript -
- Primitive data type
- String
- Number
- BigInt
- Boolean
- Undefined
- Null
- Symbol
Non-primitive data type
- Object
- Array
- RegExp
What is Dynamic typing?
The property of a language where type checks are performed mostly at run time. In dynamic typing languages like JavaScript, the interpreter assign the data type to the variable on run time base on variable value.
let random = "Hello World" // random is a string
random = true // random is now a boolean
random = 43 // random is now a number
1. Primitive data type
String
JavaScript String type is used to represent textual data
. JavaScript string type is a set of elements
of zero or more 16-bit
unsigned integers values. and the maximum length up to we can use is 2^53 -1
elements. 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.
There are two ways to create a string in JavaScript-
- By string literal
The string literal is created using double quotes.
let foo = "Hello World!";
- By string Object
In this, the new keyword is used to create an instance of the string.
let foo = new String("Hello World!");
Finding the length of string and retrieving a specific element
We can use the length
property to find the length of the string.
let foo = "Hello World!"
console.log(foo.length) // output will be 12
We can retrieve a particular element from the string by using [ ]
. for retrieving the first elements we use the 0
index for the second 1
and so on.
let foo = "String method"
console.log(foo[0]) // output will be "S"
String Methods
1. charAt( )
The charAt( )
at method returns the character at a specific index in a string. As we have seen above the first character is at the 0th
index and the second at the 1st
index and so on. We can find the last index of the string using string.length - 1
.
let foo = "Hello World!"
foo.charAt(2) // output will be l
2. charCodeAt( )
The charCodeAt( )
method returns the Unicode of the character at the specified index in a string. we can use charCodeAt( )
along with lenght
property to get Unicode of last character. you can learn more about Unicode here.
let language = "JavaScript";
language.charCodeAt(2) // output will be 118
3. concat( )
This method is used for combining two or more strings. we can also use +
to combine strings. but concat
does not change the existing strings, it returns a new string.
#syntax
string.concat(string1, string2, string3, ....., stringX)
#example
let str1 = "Learning "
let str2 = "JavaScript "
let str3 = "Happy Coding!"
let result = str1.concat(str2,str3) // output will be 'Learning JavaScript Happy Coding!'
4. indexOf( )
The indexOf()
method returns the position of the first occurrence of a specified value in a string. indexOf()
returns -1 if the value is not found.
#syntax
string.indexOf(searchvalue, start)
#example
let str = 'Learning JavaScript Happy Coding!'
str.indexOf("J") // output will be 10
5. lastIndexOf( )
The lastIndexOf()
method returns the position of the last occurrence of a specified value in a string. lastIndexOf()
searches the string from the end
to the beginning, but returns the index s from the beginning, starting at position 0. lastIndexOf() returns -1 if the value is not found.
#syntax
string.lastIndexOf(searchvalue, start)
#example
let str = 'Learning JavaScript Happy Coding!'
str.lastIndexOf("Happy") //output will be 20
6. search( )
We use the search
method for searching specific values inside a string. In the search method, we can also use the RegExp
to search for the values. If the searched value is not found then it will return -1
.
#syntax
string.search(searchvalue)
#example
let str = 'Learning JavaScript Happy Blogging!'
str.search("Happy") // output will be 20
7. match( )
The match()
method searches a string for a match against a regular expression, and returns the matches, as an Array object. If a match is not found then this method will return null
. you can learn more about RegExp here.
#syntax
string.match(regexp)
#example
let str = 'Learning JavaScript Happy Blogging!'
str.match(/app/gi) // output will be ['app']
8. replace( )
In this method, we can search for the specific string or regular expression and if a search is found then it will replace the searched string with the string you have specified to be changed and returns a new string. replace
method does not change the original string.
#syntax
string.replace(searchvalue, newvalue)
#example
let str = 'Learning JavaScript Happy Blogging!'
str.replace("Blogging!", "Coding!") // output will be 'Learning JavaScript Happy Coding!'
console.log(str) // output will be 'Learning JavaScript Happy Blogging!'
9. substr( )
This method is very useful when we want to extract a particular part of the string.
string.substr(start, length)
start
value is the value from where you want to extract the string you can also pass negative values to get a string from end.
length
value is the number of characters you want to extract. It's an optional value.
if you do not pass any value inside substr
method it will return the whole string.
#syntax
string.substr(start, length)
#example
let str = 'Learning JavaScript Happy Blogging!'
str.substr(1,7) // output will be 'earning'
#extracting characters with negative index
str.substr(-9) // output will be 'Blogging!'
10. substring( )
The substring()
method extracts characters, between indices (positions), from a string, and returns the substring. string.substring(start, end)
, start
is the starting position of the extraction and end
is the ending position. If we do not pass the ending position then It will extract till the end. and if start is greater than end then it will swap them. example str.substring(7,2)
will become str.substring(2,7)
.
#syntax
string.substring(start, end)
#example
let str = 'Learning JavaScript Happy Blogging!'
str.substring(9,19) // output will be 'JavaScript'
11. slice( )
This method is similar to the substring
method. slice
method accepts two parameters start
and end
. the start is the starting position of the string you want to extract and end is the ending position of extraction of the string. and it will return extracted part in the new string.
#syntax
string.slice(start, end)
#example
let str = 'Learning JavaScript slice method'
str.slice(15,30) // output will be 'ript slice meth'
12. toLowerCase( )
The toLowerCase()
method converts a string to lowercase letters.
#syntax
str.toLowerCase( );
#example
let str = "JavaScript";
str.toLowerCase(); // output will be 'javascript'
13. toUpperCase( )
The toUpperCase()
method converts a string to uppercase letters.
#syntax
str.toUpperCase( );
#example
let str = "JavaScript";
str.toUpperCase(); // output will be 'JAVASCRIPT'
14. toString( )
The toString()
methods return the value of the string. and by using this method we can convert numbers to strings.
#syntax
string.toString()
#example
let str = 'Hello';
str.toString() // output will be 'Hello'
let num =10;
let str = num.toString();
console.log(str); // output will be '10'
15. trim( )
The trim()
method is used to remove the whitespace from the string. It removes the whitespace from both sides of the string. and it does not change the original string. trim
method has a very useful use-case when taking input from the user. suppose the user types password and entered whitespace then by using the trim method we can remove whitespaces.
#syntax
string.trim()
#example
let str = " Data types in JavaScript "
str.trim() // output will be 'Data types in JavaScript'
16. split( )
The split()
method is used to split the string into an array of substrings and returns a new array. split method does not change the original string. If an empty string (" ")
is used as the separator, the string is split between each character.
#syntax
string.split(separator, limit)
#example
let str = "Hello How are you?"
const arr = str.split(" ")
console.log(arr) // output will be ['Hello', 'How', 'are', 'you?']
#passing limit value as well
let str = "Hello How are you?"
const arr = str.split(" ",2)
console.log(arr) // output will be ) ['Hello', 'How']
Number
In JavaScript, the maximum safe integer is( 2^53 - 1 )
. The largest positive representable number. The minimum safe integer in JavaScript ( -(2^53 - 1) )
. The largest positive representable number.
let number = 10;
# Number() constructor
let number = new Number(value);
Number methods
1. isFinite( )
The isFinite()
method checks whether a value is finite number or not. isFinite
will return true if the value is type of Number, otherwise it returns false.
isFinite()
does not convert the values to a Number, and will not return true for any value that is not of the type Number.
#syntax
Number.isFinite(value)
#example
let number = 10;
console.log(isFinite(number)); // output will be true
let x = (0/0)
console.log(isFinite(x)) // output will be false
let y = 'hello'
console.log(isFinite(y)) // output will be false
2. isInteger( )
The isInteger()
method checks whether the value is a number or not. If the value is a number then it will return true if not then returns false.
#syntax
Number.isInteger(value)
#example
Number.isInteger(10) // output will be true
Number.isInteger("hello") // output will be false
3. parseFloat( )
The parseFloat()
method parses a string argument and converts it into a floating-point number. It returns NaN if the first character of a given value cannot be converted to a number.
#syntax
Number.parseFloat(string)
#example
let str = "25.30";
console.log(Number.parseFloat(str)); // output will be 25.3
let str2 = "String";
console.log(Number.parseFloat(str2)); // output will be NaN
4. parseInt( )
The parseInt()
method parses a string argument and converts it into an integer number. With a string argument, we can also provide a radix argument to specify the type of numeral system to be used.
#syntax
Number.parseInt(string, radix)
#example
let str = "25.25";
console.log(Number.parseInt(str)); // output will be 25
5. toExponential( )
The toExponential()
method converts a number into an exponential notation.
#syntax
Number.toExponential(x)
#example
let number = 8.3425;
let expNumber = number.toExponential(3) // output will be '8.342e+0'
6. toFixed( )
The toFixed()
method returns the string that represents a number with exact digits after a decimal point.
#syntax
Number.toFixed(x)
#example
let number = 16.2364;
let fixedNumber = number.toFixed();
console.log(fixedNumber); // output will be 16
7. toPrecision( )
The toPrecision()
method formats a number to a specified length.
#syntax
Number.toPrecision(x)
#example
let number = 12.7653;
let precisedNumber = number.toPrecision(2);
console.log(precisedNumber); // output will be 13
8. toString( )
The toString()
method converts the number in the string.
#syntax
Number.toString(radix)
#example
let number = 12;
let str = number.toString();
console.log(str); // output will be '12'
BigInt
BigInt is a special type of number in JavaScript which supports integers of arbitrary length. There are two ways to create BigInt
the first one is appending n
at the end of the number or with the BigInt
function which creates BigInt from a string.
#creating BigInt
let bigint = 489247842814234906957n;
let bigint = BigInt("489247842814234906957")
Boolean
JavaScript Boolean has two states true
or false
. we can use a Boolean function for comparison.
Boolean(20>15) // true
Boolean Methods
1. toSource( )
The toSource()
method returns a string representing the source code of the object.
function Boolean() {
[native code]
}
2. toString( )
The toString
method returns the boolean value as a string.
#syntax
Boolean.toString()
#example
let state = true;
state.toString(); // 'true'
3. valueOf( )
The valueOf()
method returns the primitive value of a boolean.
#syntax
Boolean.valueOf()
#example
let bool = true;
bool.valueOf(); // true
Undefined
The undefined
has only one value which is undefined. When we declare a variable but do not initialize them then the default value for the variable will be undefined.
let numbers;
console.log(numbers); // undefined
console.log(typeof(numbers)); // undefined
Null
The null
has only one value: null
. In JavaScript null is a empty object.
let person = null;
console.log(typeof(person)); // object
Symbol
Symbol is a built-in object whose constructor returns a symbol
.
- A Symbol() method always returns a unique value.
- A symbol value may be used as an identifier for object properties.
- Symbols are immutable, just like numbers or strings.
- Symbols cannot be typecasted to primitive data types.
Don't use the
new
operator withSymbol
. it will give youTypeError
.let symbol = new Symbol();
// TypeError
#creating symbol
let symbol1 = Symbol()
let symbol2 = Symbol("person")
symbol1 === symbol2 // false
Symbol Methods
1. Symbol.for( )
The Symbol.for(key)
method searches for existing symbols in a runtime-wide symbol registry with the given key and returns it if found. Otherwise, a new symbol gets created in the global symbol registry with this key.
#syntax
Symbol.for(key)
let person = Symbol("foo");
let name = Symbol("foo");
console.log(person === name) // false
let person = Symbol.for("foo");
let name = Symbol.for("foo");
console.log(person === name) //true
2. Symbol.keyFor( )
The Symbol.keyFor()
method uses the global symbol registry to look up the key for the symbol. So it doesn't work for non-global symbols. If the symbol is not global, it won't be able to find it and return undefined.
#syntax
Symbol.keyFor(symbol);
let globalSymbol = Symbol.for("foo");
console.log(Symbol.keyFor(globalSymbol)); // "foo"
let localSymbol = Symbol("foo");
console.log(Symbol.keyFor(localSymbol)); // undefined
3. Symbol.toString( )
The Symbol.toString()
method returns a string representation of an object.
#syntax
Symbol().toString();
let symbol = Symbol("foo");
console.log(symbol.toString(symbol)); // 'Symbol(foo)'
2. Non-primitive data type
The non-primitive data structure is a type of data structure that can store data of more than one type.
Object
The Object class represents one of JavaScript's data types. In object data stored in the form of key: value
pairs. we can create an object using the Object
constructor or an object initializer
.
#using Object( ) constructor
let person = new Object();
person.name = 'Deepak';
#using an object initializer
let person={
name: 'Deepak'
}
Some Object Methods 1. Object.assign( )
The Object.assign()
method copies all the properties from one or more source object to the target object. and it returns the modified object.
#syntax
Object.assign(target,...source);
let person ={name: 'Deepak' ,age: 21};
let address = {city: 'Mumbai'};
const details = Object.assign(person,address);
console.log(details); // {name: 'Deepak', age: 21, city: 'Mumbai'}
Object cloning
Object cloning refers to the creation of an exact copy of an object. It does not change the original object.
let address = {city: 'Mumbai'}
const copyAddress = Object.assign({},address);
console.log(copyAddress); // {city: 'Mumbai'}
2. Object.create( )
This method is used to create a new object with the specified prototype object and properties.
#syntax
Object.create(proto)
Object.create(proto, propertiesObject)
let person ={
isBlogger: false,
printIntroduction(){
console.log(`My name is ${this.name}. Am I blogger? ${this.isBlogger}`)
}
}
const me = Object.create(person); // creating new object `me`
me.name = 'Deepak'; // "name" is a property set on "me", but not on "person"
me.isBlogger = true; // inherited property
me.printIntroduction(); // "My name is Deepak. Am I blogger? true"
3. Object.defineProperties( )
The Object.defineProperties()
method defines new or modifies existing properties directly on an object, returning the object.
#syntax
Object.defineProperties(obj, props)
let obj = {};
Object.defineProperties(obj, {
info: {
value: 21,
}
});
console.log(obj.info); // 21
4. Object.entries( )
The Object.entries()
method is used to return an array of a given object's own enumerable property [key, value] pairs. The ordering of the properties is the same as that given by looping over the property values of the object manually.
#syntax
Object.entries(obj)
let number = {1: '12', 2: '14', 3: '16'};
console.log(Object.entries(number)[2]); // ['3', '16']
5. Object.freeze( )
The Object.freeze()
method freezes an object that prevents new properties from being added to it. This method prevents the modification of existing property, attributes, and values.
#syntax
Object.freeze(obj)
const obj = {
value: 21
};
const obj2 = Object.freeze(obj);
obj2.value = 33;
console.log(obj2.value); // Throws an error in strict mode
6. Object.is( )
The Object.is()
method determines whether two values are the same value.
#syntax
Object.is(value1, value2);
Object.is(13,13); // true
Object.is('foo','bar') // false
Array
The Array class in JavaScript is a global object that is used in the construction of arrays; which are high-level, list-like objects. An array can have more than one value.
indexing of array starts from 0
. we can access the last element of an array by array.length - 1
.
#creating array
let numbers = [1, 2, 3, 4, 5, 6]
console.log(numbers.length) // 6
typeof(numbers) // 'object'
Useful Array Methods
1. some()
The some()
method is used to checks whether at least one element in the array passes the test implemented by the provided function. it returns true
if at least one element matches otherwise it will return false
.
#syntax
array.some(callback_function(element, index, array) { ...}, thisArg);
let emojis = [π», π½, π€‘, π©, π€‘, π½, π©, π€‘];
let emoji = (element) => element === π»;
console.log(numbers.some(emoji)); // true
2. every()
The every()
method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
#syntax
every(function callbackFn(element, index, array) { ... }, thisArg)
let emojis = [π», π½, π€‘, π©, π€‘, π½, π©, π€‘];
let emoji = (element) => element === π»;
console.log(numbers.every(emoji)); // false
3. reduce()
The reduce()
method executes a user-supplied βreducerβ callback function on each element of the array, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
Reducer Function
- Accumulator: It accumulates the return values of the array.
- Current Value: Current element is the current value.
- Current Index: The index of the current element is the value of the current index.
- Source array: The array defined by the user for implementing reduce() method.
#syntax
arr.reduce(callback(accumulator, currentValue, currentIndex, array), initialValue)
let array = [1, 2, 3, 4]
let reducer = (previousValue, currentValue) => previousValue + currentValue;
console.log(array.reduce(reducer)); // 10
Image source: MDN Web Docs
4. map()
The map()
method creates a new array
populated with the results of calling a provided function on every element in the calling array.
#syntax
map(function callbackFn(element, index, array) { ... }, thisArg)
let array = [1, 2, 3, 4, 5];
let cubeOfArray = array.map(item => item * item * item);
console.log(cubeOfArray); // [1, 8, 27, 64, 125]
5. flat()
The flat()
method is an inbuilt array method that flattens a given array into a newly created one-dimensional array. It concatenates all the elements of the given multidimensional array and flats up to the specified depth.
#syntax
flat(depth)
let numbers = [1, 2, 3, 4, [7, 8, 9, 10, 12]];
console.log(numbers.flat()); // [1, 2, 3, 4, 7, 8, 9, 10, 12]
let numbers = [1, 2, 3, 4, 5, [ [ [ 6, 7, 8, 9, 10] ] ]];
console.log(numbers.flat(2)); // [1, 2, 3, 4, 5, [ 6, 7, 8, 9, 10] ]
6. filter( )
The filter()
method creates a new array with all elements that satisfied the condition by the provided function.
#syntax
filter(function callbackFn(element, index, array) { ... }, thisArg)
let numbers = [2, 3, 5, 7, 8, 12, 14, 17, 20];
let result = numbers.filter(item => item % 2 ===0);
console.log(result); // [2, 8, 12, 14, 20]
7. forEach()
The JavaScript array forEach()
method is used to invoke the specified function once for each array element.
#syntax
forEach(function callbackFn(element, index, array) { ... }, thisArg)
let numbers = [1, 2, 3, 4, 5, 6];
numbers.forEach(item => console.log(item)); // 1 2 3 4 5 6
8. findIndex()
The findIndex()
method returns the index
of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1
, indicating that no element passed the test.
#syntax
findIndex(function callbackFn(element, index, array) { ... }, thisArg)
let numbers = [2, 5, 7, 12, 8, 15, 20];
let isLargeNumber = (item) => item > 15;
console.log(numbers.findIndex(isLargeNumber)); // 6
9. find()
The find()
method returns the first element of the given array that satisfies the provided function condition. If no condition matches then it will return undefined
.
#syntax
find(function callbackFn(element, index, array) { ... }, thisArg)
let emojis = [π», π½, π€‘, π©, π€‘, π½, π©, π»];
let emoji = emojis.find((element) => element === π»);
console.log(emoji) // π»
10. sort()
The sort()
method is used for sorting purposes. If we apply the sort()
method on an array it will sort an array in some order and return a new array. By default sort() method sort an array in ascending order.
#syntax
sort(function compareFn(firstEl, secondEl) { ... })
let names = ['colt', 'andrei', 'andrew', 'stephen', 'brad', 'maximillian'];
names.sort();
console.log(names) // ['andrei', 'andrew', 'brad', 'colt', 'maximillian', 'stephen']
11. concat()
The concat()
method is used to merge two or more arrays. This method does not change the existing arrays but instead returns a new array.
#syntax
concat(value0, value1, ... , valueN)
let num1 = [1, 2, 3, 4, 5];
let num2 = [6, 7, 8, 9, 10];
let result = num1.concat(num2);
console.log(result); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
12. fill()
The fill()
method fills the elements of the given array with the specified static values. This method modifies the original array. It returns undefined if no element satisfies the condition.
#syntax
fill(value, start, end)
value
Value to fill the array with. (Note all elements in the array will be this exact value.)
start
Optional
Start index, default 0.
end
Optional
End index, default arr.length.
let emojis = [π», π½, π€‘, π©, π€‘, π½, π©];
// fill withπ»from position 2 until position 7
console.log(emojis.fill(π», 2, 7)); // [π», π½, π», π», π», π», π»]
13. includes()
The includes()
method determines whether an array includes a certain value among its entries, returning true
or false
as appropriate.
#syntax
includes(searchElement, fromIndex)
let emojis = [π», π½, π€‘, π©, π€‘, π½, π©];
console.log(emojis.includes(π€‘)); // true
14. reverse()
The reverse()
method changes the sequence of elements of the given array and returns the reverse sequence. In other words, the array's last
element becomes first
and the first
element becomes the last
. This method also made the changes in the original array.
#syntax
reverse()
let emojis = [π», π©, π», π½, π€‘, π½, π©];
let reversed = emojis.reverse();
console.log(reversed); // [π©, π½, π€‘, π½, π», π©, π»]
15. flatMap()
The flatMap()
method is a combination of flat()
and map()
methods. This method initially maps each array element through a mapping function, then flattens up the array with a depth value of 1
.
#syntax
flatMap(function callbackFn(currentValue, index, array) { ... }, thisArg)
let number = [2, 4, 6, 8, 9];
number.flatMap(itme => [item ** 2]); // [4, 16, 36, 64, 81]
RegExp
The RegExp
object is used for matching text with a pattern.
Two ways to create RegExp
- literal notation
The literal notation's parameters are enclosed between slashes and do not use quotation marks.
let re = /ab+c/i; // literal notation
- constructor function
The constructor function's parameters are not enclosed between slashes but do use quotation marks.
let re = new RegExp('ab+c', 'i') // constructor with string pattern as first argument
RegExp Flags
- i
With this flag, the search is case-insensitive: no difference between A
and a
(see the example below).
let str = "We will, we will rock you";
str.match(/we/gi); // ['We', index: 0, input: 'We will, we will rock you', groups: undefined]
- g
With this flag the search looks for all matches, without it β only the first match is returned.
let str = "We will, we will rock you";
str.match(/we/gi); // ['We', 'we']
- m
Multiline mode (covered in the chapter Multiline mode of anchors ^ $, flag "m"
).
let regex = new RegExp('foo', 'm');
console.log(regex.multiline); // true
- s
Enables βdotallβ mode, which allows a dot . to match newline character \n.
let regex1 = new RegExp('foo', 's');
console.log(regex1.dotAll); // true
- u
Enables full Unicode support. The flag enables the correct processing of surrogate pairs.
let regex = new RegExp('\u{71}', 'u');
console.log(regex.unicode); // true
- y
βStickyβ mode: searching at the exact position in the text.
let str = '#foo#';
let regex = /foo/y;
regex.lastIndex = 1;
regex.test(str); // true
Conclusion
This article is all about JavaScript Datatypes in-depth. we can create empty objects withnull
and undefined
.Knowing the data types of any programming language is the first step towards the learning path of the language.
Content Reference: MDN Web Docs, Javatpoint.
Thank you for reading. π
If you enjoyed this article or found it helpful, give it a thumbs-up. π
Let's Connect. π