Structs in JavaScript

Our example demonstrates creating and using structs, which are typed collections of fields in JavaScript.

// Define a person class with name and age fields.
class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}

// Function to create a new Person with a given name and a default age.
function newPerson(name) {
    // Create a new person object
    let p = new Person(name, 42);
    // Swift is garbage collected, so returning this reference is fine.
    return p;
}

// Example usage
console.log(new Person("Bob", 20));

// You can name the fields when initializing an object.
console.log(new Person("Alice", 30));

// Omitted fields will be undefined.
console.log(new Person("Fred"));

// Creating a new person object using the factory function.
console.log(newPerson("Jon"));

// Access object properties using dot notation.
let s = new Person("Sean", 50);
console.log(s.name);

// Working with object references.
let sp = s;
console.log(sp.age);

// Object properties are mutable.
sp.age = 51;
console.log(sp.age);

// Example of an anonymous object.
let dog = {
    name: "Rex",
    isGood: true
};
console.log(dog);

To run the code, simply save it in a .js file and use Node.js or any JavaScript runtime environment to execute it.

$ node structs_example.js
{
  name: 'Bob',
  age: 20
}
{
  name: 'Alice',
  age: 30
}
{
  name: 'Fred',
  age: 42 // Default age when not provided
}
{
  name: 'Jon',
  age: 42
}
Sean
50
51
{
  name: 'Rex',
  isGood: true
}

Next example: Methods.