Structs in JavaScript

JavaScript doesn't have a dedicated struct keyword like C or C++, but structures can be mimicked using objects. This guide covers how to create data structures akin to structs using JavaScript objects, harnessing prototypes for methods, and incorporating user input to populate these structures.

How to define a struct in JavaScript

In JavaScript, the closest entity to a struct is an object or a class. Here's how you can define a struct-like object:

const Point = { x: 0, y: 0, create: function (x, y) { const newPoint = Object.create(this); newPoint.x = x; newPoint.y = y; return newPoint; } }; const myPoint = Point.create(10, 15);

This pattern uses the Object.create method to instantiate a new object that inherits from the base Point object.

Working with prototypes

Prototypes can be used to define methods for struct-like objects in JavaScript. This is similar to adding functions in structs in languages like C.

function Car(make, model, year) { this.make = make; this.model = model; this.year = year; } Car.prototype.displayInfo = function () { return `${this.make} ${this.model} (${this.year})`; }; const myCar = new Car('Toyota', 'Corolla', 2021); console.log(myCar.displayInfo());

In this example, displayInfo is a method available to all instances of Car.

Incorporating user input

To integrate user input into a JavaScript struct, you can use HTML forms or prompts in a Node.js environment.

For web:

<label for="make">Make:</label> <input type="text" id="make" name="make"> <label for="model">Model:</label> <input type="text" id="model" name="model"> <label for="year">Year:</label> <input type="text" id="year" name="year"> <button onclick="createCar()">Create Car</button> <script> function createCar() { const make = document.getElementById('make').value; const model = document.getElementById('model').value; const year = document.getElementById('year').value; const newCar = new Car(make, model, year); console.log(newCar.displayInfo()); } </script>

For Node.js:

const readline = require('readline').createInterface({ input: process.stdin, output: process.stdout }); readline.question('Enter the make, model, and year of the car:', input => { const [make, model, year] = input.split(' '); const newCar = new Car(make, model, parseInt(year, 10)); console.log(newCar.displayInfo()); readline.close(); });

Handling nested structs

To handle nested structs in JavaScript, you can define objects within objects, similar to nested structs in other languages.

const Author = { name: '', age: 0, create: function (name, age) { const newAuthor = Object.create(this); newAuthor.name = name; newAuthor.age = age; return newAuthor; } }; const Book = { title: '', yearPublished: 0, author: Author.create('', 0), create: function (title, yearPublished, author) { const newBook = Object.create(this); newBook.title = title; newBook.yearPublished = yearPublished; newBook.author = author; return newBook; } }; const roaldDahl = Author.create('Roald Dahl', 76); const matilda = Book.create('Matilda', 1988, roaldDahl);

This structure allows for Book to have an Author, encapsulating the relationship between these entities.

ES6 classes as structs

With the introduction of classes in ES6, struct-like behavior can be more classically represented.

class Rectangle { constructor(height, width) { this.height = height; this.width = width; } area() { return this.height * this.width; } } const myRectangle = new Rectangle(20, 10); console.log(myRectangle.area());

Classes provide a clean and familiar syntax for those accustomed to traditional OOP languages.

Immutable structs with Object.freeze

To create immutable structs in JavaScript, you can use Object.freeze.

const Circle = { radius: 0, create: function (radius) { const newCircle = Object.create(this); newCircle.radius = radius; return Object.freeze(newCircle); } }; const myCircle = Circle.create(5); // myCircle.radius = 10; // This will not work, as the object is frozen

Freezing an object ensures that its properties cannot be changed, which is a key feature of structs in some statically-typed languages.

Conclusion

Struct-like constructs in JavaScript are versatile and can be created to suit a wide range of applications. By using objects, prototypes, and ES6 classes, you can emulate the behavior of structs from other programming languages while leveraging JavaScript's dynamic nature. Integrating user input allows these structures to be interactive and responsive within an application.

Invite only

We're building the next generation of data visualization.