How to work with Structs in JavaScript ?
Structs are typically found in languages like C, C++, and similar, and they provide a way to organize related data items under one name. Typically JavaScript does not have built-in support for structs, but you can achieve similar functionality using objects. Objects in JavaScript are dynamic collections of key-value pairs, where keys are strings (or Symbols) and values can be any data.
Table of Content
- Using Objects
- Using ES6 Classes
- Using String Split()
- Using the ‘this’ Keyword in Class
- Using the ‘this’ Keyword in Object
Using Objects
To create a struct-like object using plain objects, you define an object literal with properties representing the fields of the struct. Each property is defined as a key-value pair, where the key is the name of the property and the value is the corresponding data.
Example: Explanation of Structs in JavaScript Using Objects.
const person = {
name: 'John Doe',
age: 30,
occupation: 'Engineer',
city: 'New York'
};
// Accessing properties
console.log("Name:", person.name);
// Modifying properties
person.age = 35;
// Adding new properties
person.country = 'USA';
// Deleting existing value
delete person.city
// Final output
console.log('Person', person);
Output
Name: John Doe Person { name: 'John Doe', age: 35, occupation: 'Engineer', country: 'USA' }
Using ES6 Classes
To create a struct-like object using ES6 classes, you define a class using the class keyword, followed by the class name. Inside the class, you define a constructor method to initialize the object’s properties and methods. After defining, you can create instances of the class using the new keyword. You can access and manipulate the properties of it using dot notation.
Example: Explanation of Structs in JavaScript Using ES6 Classes.
class Person {
constructor(name, age, occupation) {
this.name = name;
this.age = age;
this.occupation = occupation;
}
// Method to display person's details
displayDetails() {
console.log(`Name: ${this.name}, Age: ${this.age},
Occupation: ${this.occupation}`);
}
}
// Creating an instance of Person
const person1 = new Person('John Doe', 30, 'Engineer');
const person2 = new Person('Jane Smith', 25, 'Doctor');
// Accessing properties
console.log("Name:", person1.name);
console.log("Age:", person2.age);
// Updating properties
person1.name = 'Ram';
person2.age = 45;
// Calling method to display details
person1.displayDetails();
person2.displayDetails();
Output
Name: John Doe Age: 25 Name: Ram, Age: 30, Occupation: Engineer Name: Jane Smith, Age: 45, Occupation: Doctor
Using String Split()
To create a struct-like behavior in JavaScript, Start with structured data as a string. Then use split() to break the string into parts. After that assign parts to object properties for a struct-like object.
Example: Explanation of Structs in JavaScript Using String Split().
// Define a string representing structured data
const personData = "John,Doe,30";
// Split the string into an array
const dataArray = personData.split(',');
// Create a struct-like object using an object literal
const person = {
firstName: dataArray[0],
lastName: dataArray[1],
age: Number(dataArray[2])
};
console.log(person);
Output
{ firstName: 'John', lastName: 'Doe', age: 30 }
Using the ‘this’ Keyword in Class
In a class in JavaScript, the ‘this’ keyword refers to the current instance of the class. It typically refers to the class that is currently being constructed by a constructor function.
Example: Explanation of Structs in JavaScript Using the ‘this’ Keyword in Class.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}
and I am ${this.age} years old.`);
}
}
const john = new Person('John', 30);
john.greet();
Output
Hello, my name is John and I am 30 years old.
Using the ‘this’ Keyword in Object
The ‘this’ keyword in JavaScript refers to the current object context within which the code is executed. It typically refers to the object on which a method is called.
Example: Explanation of Structs in JavaScript Using the ‘this’ Keyword in Object.
const person = {
name: 'John',
greet: function () {
console.log('Hello, my name is ' + this.name);
}
};
person.greet();
Output
Hello, my name is John