Wednesday, September 18, 2024

Object Data Types in JavaScript



Like any other programming language, JavaScript supports multiple data types. Understanding these types and the different operations you can perform on them is essential to coding effectively with JavaScript.


JavaScript Data Types

The data types supported by JavaScript fall into two categories: primitive and object types. After introducing some key concepts about typing in JavaScript and an overview of primitive data types in the last post, I introduce object data types in this post.


Object Data Types

Object types are containers that hold collections of values of primitive types or more complex entities composed of object types. Object types are mutable and are referenced by identifiers. There are eight object types in JavaScript, which I present in the two tables below. 


In the first table, I briefly describe the type, the mechanism to create it, some main methods you can apply to it, an example, and the result of its execution.


In the second table, I resume the way you can iterate over these types with some examples. Let’s note that I consider only the types that we iterate over. I will exclude the others that are not naturally iterable.


Object Data Types in JavaScript: Creating and Main Methods

Type

Description

Creating

Main Methods

Code Snippet

Object

- Container for multiple values

- Collection of key-value pairs

- Objects can have methods


- Using object literal:

let obj = {key1:value1, key2:value2, ...};


- Using Object constructor:

let obj = new Object();

obj.key1 = value1;

obj.key2= value2;

...


- Using a class:

class ObjClass {

constructor(val1, val2, ..) {

this.property1 = val1;

this.property2 = val2;

...

}

}

let myObj = new ObjClass(value1, value2, ...);


- Add or update a property:

obj.property = value


- Delete a property:

delete obj.property;


- Copy an object’s properties to another:

Object.assign();


let employee = {

firstName: 'Marie',

lastName: 'Hitman',

email:"marie@gmail.com",

age: 26,

salary:5000,

getSalary: function() {

return this.salary + '$';

}

};

console.log(employee.firstName);

console.log(employee.email);

console.log(employee['lastName']);

console.log(employee['age']);

console.log(employee.getSalary());


Array

- Ordered collection of elements accessible using indexes

- Dynamically sized



- Using literals:

let myArray = [elem1, elem2, ...];  


- Using Array constructor:

let myArray = new Array(elem1, elem2, ...);  


- From a set:

let myArray = Array.from(mySet);

Access an element with an index: let element = myArray[index];


Add an element:

myArray.push(element);


Remove an element from the beginning:

myArray.shift();


Remove an element from the end:

myArray.pop();


Update an element:

myArray[index] = newElement


let nums = [45, 23, -80, 12];


let result = [];

nums.forEach((num) => {

result.push(num ** 4);

});


console.log('Quadruples of each element in :', nums, 'are', result);

Function

Block of code to perform a specific task

- Using function definition:

function myFunction(p1, ..,pn){

//code of the function

}


function applyExpArray(arr, n) {


let result = [];

arr.forEach((num) => {

result.push(num ** n);

});

return result;

}


let arr = [45, 23, -80, 12];

console.log(applyExpArray(arr, 2));


Date

One moment in time

- Using Date constructor with or without parameter:

let myDate = new Date(dateString);

let now = new Date();


- Get date component (year, month, day, etc.):

myDate.getFullYear(), ..


- Set date component (year, month, day, etc.):

myDate.setFullYear(myYear); ..

let myDate = new Date("04.04.2020");

console.log(myDate);

console.log("Year:", myDate.getFullYear());

console.log("Month:", myDate.getMonth());

console.log("Day:", myDate.getDate());

Map

- Collection of key-value pairs

- Keys should be unique

- Keys can be of any type

- Using Map constructor:

let map = new Map();


- Add a new key-value pair: set(key, value)


- Get the value associated to the key: get(key)


- Remove the key-value pair: delete(key)


- Check if a key exists: has(key)


- Remove all key-value pairs: clear()


- Get the number of the key-value pairs: size


let personMap = new Map();

personMap.set(100, 'Marie');

personMap.set(200, 'Bob');

personMap.set(300, 'Jack');

console.log(personMap.get(100));

console.log(personMap.get(300));

console.log(personMap.has(400));

console.log(personMap.size);

Set

Unordered collection of elements where each element is unique

- Using Set constructor:

let mySet = new Set([elem1, elem2,..]);


- From an array:

let myArray = [elem1, elem2,..];

let mySet = new Set(myArray);

- Add a new element: add(element)


- Check if an element exists: has(element)


- Remove an element:

delete(element)


- Remove all elements: clear()


- Get the number of elements: size


let carSet = new Set(['BMW', 'Ferrari', 'Toyota', 'Porsche']);

let index = 1;

for (let car of carSet) {

console.log('Car' + index + ':', car);

index++;

}

console.log('Size of carSet:', carSet.size);

carSet.clear();

console.log('Size of carSet:', carSet.size);

WeakMap

- Similar to Map

- A Key must be an object.

- A Key is weakly referenced: it is garbage collected and its entry will be removed, when there is no reference to it.


- Using WeakMap constructor:

let weakMap = new WeakMap();

- set(key, value)

- get(key)

- delete(key)

- has(key)

let key1 = {id: 100};

let key2 = {id: 200};

let p1 = {name: 'Marie Hitman', age: 26};

let p2 = {name: 'John Wayne', age: 40};

let personMap = new WeakMap();

personMap.set(key1, p1);

personMap.set(key2, p2);

console.log(personMap.get(key1));

console.log(personMap.get(key1).name);

console.log(personMap.get(key2).age);



WeakSet

- Similar to Set

- An element must be an object

- An element is weakly referenced


- Using WeakSet constructor:

let weakSet = new WeakSet();

- add(element)

- has(element)

- delete(element)

let perWeakSet = new WeakSet();

let person1 = { firstName: 'Joe', firstName: 'Doe'};

let person2 = { firstName: 'Marie', firstName: 'Hitman'};

perWeakSet.add(person1);

perWeakSet.add(person2);

console.log(perWeakSet.has(person1));

perWeakSet.delete(person1);

console.log(perWeakSet.has(person1));

console.log(perWeakSet.has(person2));





Object Data Types in JavaScript: Iteration

Type

Iterating Over

Code Snippet

Code Output

Object

- Iterate over keys using for...in loop:

for (let key in myObj) {

console.log(key + ': ' + myObj[key]);

}


- Iterate over Object.keys() using forEach:

let keys = Object.keys(myObj);

keys.forEach(key => {

console.log(key + ': ' + myObj[key]);

});


- Iterate over Object.entries() using forEach:

let entries = Object.entries(myObj);

entries.forEach(([key, value]) => {

console.log(key + ': ' + value);

});


for (let key in employee){

console.log(key, "=", employee[key])

}


firstName = Marie

lastName = Hitman

email = marie@email.com

age = 26

salary = 5000

getSalary = Æ’ () {

return this.salary + '$';

}

Array

- Using for loop:

for (let i = 0; i < myArray.length; i++) {

console.log(myArray[i]);

}


- Using for...of loop:

for (let value of myArray) {

console.log(value);

}


- Using forEach method:

myArray.forEach(function(value) {

console.log(value);

});


- Using map method:

myArray.map(value => { console.log(value); });


- Using for...in Loop:

for (let index in myArray) {

console.log(myArray[index]);

}

for (let num of nums) {

console.log('Double of:', num, 'is', num*2);

}

for (let index in nums) {

console.log('Element', nums[index], 'is at the index:', index);

}

Double of: 45 is 90

Double of: 23 is 46

Double of: -80 is -160

Double of: 12 is 24

Element 45 is at the index: 0

Element 23 is at the index: 1

Element -80 is at the index: 2

Element 12 is at the index: 3

Map

- Iterating over keys using for..of loop:

for (let key of myMap.keys()) {

console.log(key);

}


- Iterating over values using for..of loop:

for (let value of myMap.values()) {

console.log(value);

}


- Iterating over entries using for..of loop:

for (let [key, value] of myMap.entries()) {

console.log(key, value);

}


- Iterating over keys and entries using forEach:

myMap.forEach((value, key) => {

console.log(key, value);

});

for (let value of personMap.values()) {

console.log(value);

}


personMap.forEach((value, key) => {

console.log(key + ':', value);

});

Marie

Bob

Jack

100: Marie

200: Bob

300: Jack

Set

- Using for..of loop:

for (let item of setName) {

console.log(item);

}


- Using forEach:

setName.forEach((value) => {

console.log(value);

});

let citySet = new Set(['Vienna', 'Salzburg', 'Graz', 'Klagenfurt', 'Innsbruck']);


citySet.forEach((city) => {

console.log(city);

});


Vienna

Salzburg

Graz

Klagenfurt

Innsbruck

Primitive Types in JavaScript


 

Key Concepts

Like any other programming language, JavaScript supports multiple data types. Understanding these types and the different operations you can perform on them is essential to coding effectively with JavaScript.


JavaScript Data Types

The data types supported by JavaScript fall into two categories, primitive and object types. In this post, I provide an overview of primitive types and introduce object data types in the next post.


Dynamic Typing

JavaScript is a dynamically typed language. Dynamic typing means that the type of a variable is known at runtime, but not at compile time. Therefore, you do not need to declare the type of your variables. The language interpreter will extract the type of a variable from the value assigned to it at the runtime. This feature makes writing code more flexible, but less error-tolerant. Some errors may only be detected at runtime and not early at compile time.


Primitive Data Types

Primitive data types are the basic blocks for data representation and handling. They are built-in in most programming languages and used to construct more complex data structures. Primitive types are immutable. In other words, their values cannot be changed. There are seven primitive data types in JavaScript, which I present in the second table below with a brief description and examples.


Type Checking

JavaScript provides the ‘typeof’ operator to check the type of a variable.


Type Conversion

JavaScript supports implicit and explicit type conversion, which I explain in the following table.


Type Conversion in JavaScript

Conversion

Definition

Code snippet

Code Output

Implicit

Converting types when necessary

let str = '12' + 8;

console.log(str);

console.log(typeof(str));

128

string

Explicit

Converting types using functions

let num = Number('475');

console.log(num);

console.log(typeof(num));

475

number


Primitive Types

Here is a summary of the primitive types with examples in JavaScript.


Primitive Types in JavaScript

Type

Description

Example

Code Snippet

Code Output

Checking

Checking Output

Number

integer and float numbers

18, 45.5

let exp = 18 * 3 + 45.5;

console.log('exp:', exp);

exp: 99.5

console.log(typeof(18));

number

BigInt

large integers

9007199254740991n

let expBI = 9007199254740991n / 30n;

console.log('expBI:', expBI);

expBI: 300239975158033n

console.log(typeof(9007199254740991n));

bigint

String

sequence of characters

"nice", 'life'

let str1 = "Hello";

let german_str1 = str1.replaceAll("e", "a");

let str2 = "World!";

let german_str2 = str2.replaceAll("o", "e")

.replaceAll("r", "").replaceAll("d", "t")

console.log(german_str1 + " " + german_str2);

Hallo Welt!

console.log(typeof("nice"));

string

Boolean

logical values ‘true’ and ‘false’

true

let found = false;

let c = "b";

let str = "beautiful dream";

if (str.indexOf(c)>-1){

found = true;

}

if (found){

console.log(c, "is found in", str);

}

b is found in beautiful dream

console.log(typeof(true));

boolean

Undefined

a declared variable to which no value is assigned

let item;

let item;

if (item == undefined){

console.log(item);

}

undefined

console.log(typeof(undefined));

undefined

Null

no value is provided

let item = null;

let item = null;

if (item){

console.log(item);

} else {

console.log("Your item is null");

}

Your item is null

console.log(typeof(null));

object

Symbol

unique and immutable identifier

let item = Symbol("name");

const sym1 = Symbol();

const sym2 = Symbol("name");

const sym3 = Symbol("name");

console.log(sym1 === sym2);

console.log(sym2 === sym3);

false

false

console.log(typeof(Symbol("name")));

symbol

Blog Posts

Enhancing Performance of Java-Web Applications

Applications built with a Java back-end, a relational database (such as Oracle or MySQL), and a JavaScript-based front-end form a common and...