Getting Started

Table of Content

Table of Content

Table of Content

Objects and Arrays

Objects and arrays are fundamental data structures in JavaScript. Objects store data in key-value pairs, while arrays hold ordered collections of values.

Objects in JavaScript

An object is a collection of properties, where each property is a key-value pair.

Creating an Object

An object can be created using curly braces {} with key-value pairs inside.

let person = {
  name: "Alice",
  age: 30,
  isStudent: false
};

Accessing Object Properties

Properties can be accessed using dot notation or bracket notation.

console.log(person.name); // Outputs: Alice
console.log(person["age"]); // Outputs: 30

Modifying Object Properties

Properties can be changed or added dynamically.

person.age = 31; // Modify existing property
person.city = "New York"; // Add new property
  
console.log(person);

Deleting Object Properties

The delete keyword removes a property from an object.

delete person.isStudent;
console.log(person);

Checking Property Existence

The in operator checks if a property exists.

console.log("age" in person); // true
console.log("salary" in person); // false

Iterating Over Objects

Objects can be looped through using for...in.

for (let key in person) {
  console.log(key + ": " + person[key]);
}

Adding and Removing Elements

push(value) adds an element to the end.

pop() removes the last element.

unshift(value) adds an element to the beginning.

shift() removes the first element.

fruits.push("Mango");
fruits.pop();
fruits.unshift("Strawberry");
fruits.shift();
  
console.log(fruits);

Nested Objects and Arrays

Objects can contain arrays, and arrays can contain objects.

let student = {
  name: "Emily",
  grades: [90, 85, 88]
};
  
console.log(student.grades[1]); // Outputs: 85
let employees = [
  { name: "Alice", position: "Developer" },
  { name: "Bob", position: "Designer" }
];
  
console.log(employees[0].name); // Outputs: Alice

Conclusion

Objects and arrays are crucial for managing and structuring data in JavaScript. The next section will focus on ES6+ features, which introduce new syntax and functionalities to improve JavaScript development.

Get Template for free

Get Template for free

Get Template for free