Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to work with Structs in JavaScript?
In this tutorial, let us discuss how to work with structs in JavaScript.
What is a struct? A struct is the short name of the data structure. The structure creates multiple values of different types in a single variable. We can use a struct to generate records.
JavaScript doesn't have built-in struct support like C or C++. However, we can simulate struct-like behavior using JavaScript objects and constructor functions. Let us see the methods to create a structure.
Using the String split() Method
We can create a struct constructor dynamically by parsing a comma-separated string of property names.
Syntax
function createStruct(keys) {
if (!keys) return null;
const kArr = keys.split(', ');
const kCount = kArr.length;
function createConstructor() {
for (let i = 0; i < kCount; i++)
this[kArr[i]] = arguments[i];
}
return createConstructor;
}
Example
The program below creates object structures using the string split approach:
<html>
<body>
<h2>Working with struct using <i>string split</i></h2>
<div id="output1"></div>
<script>
function createStruct(keys) {
if (!keys) return null;
const kArr = keys.split(', ');
const kCount = kArr.length;
function createConstructor() {
for (let i = 0; i < kCount; i++)
this[kArr[i]] = arguments[i];
}
return createConstructor;
}
// Simple struct
const User = new createStruct("id, name");
const egan = new User(1, 'Egan');
let output = "<b>Simple Struct:</b><br>";
output += JSON.stringify(egan) + "<br><br>";
output += "<b>name = </b>" + egan.name + "<br>";
output += "<b>id = </b>" + egan.id + "<br><br>";
// Struct with array
const UserMult = new createStruct("id, name, colors");
const anna = new UserMult(2, 'Anna', ['Blue', 'Grey']);
output += "<b>Struct with Array:</b><br>";
output += JSON.stringify(anna) + "<br><br>";
output += "<b>first color = </b>" + anna.colors[0] + "<br>";
output += "<b>second color = </b>" + anna.colors[1] + "<br><br>";
// Nested struct
const Job = new createStruct('position, location');
const jobData = new Job('Developer', 'USA');
const Employee = new createStruct('id, name, job');
const grace = new Employee(3, 'Grace', jobData);
output += "<b>Nested Struct:</b><br>";
output += JSON.stringify(grace) + "<br><br>";
output += "<b>position = </b>" + grace.job.position + "<br>";
output += "<b>location = </b>" + grace.job.location + "<br>";
document.getElementById('output1').innerHTML = output;
</script>
</body>
</html>
Simple Struct:
{"id":1,"name":"Egan"}
name = Egan
id = 1
Struct with Array:
{"id":2,"name":"Anna","colors":["Blue","Grey"]}
first color = Blue
second color = Grey
Nested Struct:
{"id":3,"name":"Grace","job":{"position":"Developer","location":"USA"}}
position = Developer
location = USA
Using Constructor Functions with 'this'
A simpler approach is to create constructor functions directly using the this keyword.
Syntax
function StructName(param1, param2) {
this.property1 = param1;
this.property2 = param2;
}
Example
The program below creates structures using constructor functions:
<html>
<body>
<h2>Working with struct using <i>'this'</i> keyword</h2>
<div id="output2"></div>
<script>
function Movie(rating, review) {
this.rating = rating;
this.review = review;
}
function Book(title, author, pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
// Create movie instances
var movies = [
new Movie(5, 'Excellent'),
new Movie(3, 'Average'),
new Movie(1, 'Poor')
];
// Create book instance
var book = new Book('JavaScript Guide', 'John Doe', 300);
let output = "<b>Movie Structs:</b><br><br>";
movies.forEach((movie, index) => {
output += `Movie ${index + 1}: Rating = <b>${movie.rating}</b>, Review = <b>${movie.review}</b><br>`;
});
output += "<br><b>Book Struct:</b><br><br>";
output += JSON.stringify(book) + "<br><br>";
output += `Title = <b>${book.title}</b><br>`;
output += `Author = <b>${book.author}</b><br>`;
output += `Pages = <b>${book.pages}</b><br>`;
document.getElementById('output2').innerHTML = output;
</script>
</body>
</html>
Movie Structs:
Movie 1: Rating = 5, Review = Excellent
Movie 2: Rating = 3, Review = Average
Movie 3: Rating = 1, Review = Poor
Book Struct:
{"title":"JavaScript Guide","author":"John Doe","pages":300}
Title = JavaScript Guide
Author = John Doe
Pages = 300
Comparison
| Method | Flexibility | Simplicity | Use Case |
|---|---|---|---|
| String Split | High | Complex | Dynamic struct creation |
| Constructor Function | Medium | Simple | Fixed struct definition |
Conclusion
JavaScript simulates structs using objects and constructor functions. The string split method offers dynamic flexibility, while constructor functions provide simplicity and clarity for most use cases.
