Previously, when I needed to store a number of related variables, I would create a class like this:
function Item(id, speaker, country) {
this.id = id;
this.speaker = speaker;
this.country = country;
}
var myItems = [new Item(1, 'john', 'au'), new Item(2, 'mary', 'us')];
However, I’m wondering if this is the best practice. Are there other, more efficient ways to simulate a struct in JavaScript?
I’ve worked with JavaScript for years, and honestly, when it comes to simulating a javascript struct
, I often keep things simple.
Instead of creating a class, you can just use plain objects:
const myItems = [
{ id: 1, speaker: 'john', country: 'au' },
{ id: 2, speaker: 'mary', country: 'us' }
];
Why does this work?
Simplicity – Objects are lightweight, no need for constructors.
Performance – Less memory overhead, since you skip the extra prototype layers.
Readability – Anyone reading your code can instantly understand what’s going on.
For most use cases where you just need to group related values - that’s all a javascript struct
really is - plain objects get the job done beautifully.
Building on Emma’s point, I’ve seen cases where using just objects is fine - but if you want more structure or plan to attach methods, I recommend using ES6 classes for your javascript struct
.
Here’s how you can upgrade that:
class Item {
constructor(id, speaker, country) {
this.id = id;
this.speaker = speaker;
this.country = country;
}
describe() {
return `${this.speaker} from ${this.country}`;
}
}
const myItems = [
new Item(1, 'john', 'au'),
new Item(2, 'mary', 'us')
];
Why does this help?
Encapsulation – You can wrap logic inside the class, making the data and behavior live together.
Structure – Makes it clear what shape each javascript struct
instance should have.
Extendability – You can subclass or extend later if your app grows.
If you think your code will evolve beyond simple data holding, classes set you up nicely.
I really like where Rashmi took that, and here’s another enhancement: if you care about immutability — making sure your javascript struct
stays fixed once created — you can lock it down using Object.freeze()
.
Example:
const myItems = [
Object.freeze({ id: 1, speaker: 'john', country: 'au' }),
Object.freeze({ id: 2, speaker: 'mary', country: 'us' })
];
Why bother?
Immutability – Prevents accidental changes, great for state management or when working with Redux-style patterns.
Predictability – Frozen objects reduce side effects, which can lead to fewer bugs.
Optimization – Some JS engines can better optimize immutable data.
So if you want your javascript struct
to behave like a true, never-changing record, freezing your plain objects is a smart move.