How to use Objects In Javascript
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' }
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