Camkode
Camkode

Working with Arrays and Objects in JavaScript

Posted by Kosal

Working with Arrays and Objects in JavaScript

Arrays and objects in JavaScript is fundamental for managing and manipulating data. Here's an overview:

Arrays:

Arrays are ordered collections of values, allowing storage of multiple items under a single variable name. They are defined using square brackets [].

Creating Arrays:

// Creating an empty array
let myArray = []

// Initializing an array with values
let numbers = [1, 2, 3, 4, 5]
let mixedArray = [1, 'two', true, { key: 'value' }]

Accessing and Modifying Array Elements:

// Accessing elements
console.log(numbers[0]) // Output: 1
console.log(mixedArray[2]) // Output: true

// Modifying elements
numbers[2] = 10 // Changing the third element to 10

Useful Array Methods:

JavaScript provides numerous built-in methods to work with arrays:

  • push(): Adds elements to the end of an array.
  • pop(): Removes the last element from an array.
  • shift(): Removes the first element from an array.
  • unshift(): Adds elements to the beginning of an array.
  • splice(): Adds or removes elements from a specific position in an array.

Objects:

Objects are collections of key-value pairs, and they're defined using curly braces {}.

Creating Objects:

// Creating an empty object
let myObj = {}

// Initializing an object with properties
let user = {
  name: 'Kosal',
  age: 30,
  isStudent: false,
}

Accessing and Modifying Object Properties:

// Accessing properties
console.log(user.name) // Output: Kosal
console.log(user['age']) // Output: 30

// Modifying properties
user.age = 35 // Changing the age to 35
user['isStudent'] = true // Changing isStudent to true

Useful Object Operations:

Objects have methods and operations to work with their properties:

  • Object.keys(): Returns an array of an object's keys.
  • Object.values(): Returns an array of an object's values.
  • Object.entries(): Returns an array of an object's key-value pairs.

Arrays of Objects:

You can have arrays that contain objects, creating more complex data structures.

let users = [
  { name: 'Sakni', age: 25 },
  { name: 'Bora', age: 30 },
  { name: 'Kosal', age: 35 },
]

console.log(users[1].name) // Output: Bora

// Loop through the array and output the values.
for (let user of users) {
  console.log(`Name: ${user.name}, Age: ${user.age}`)
}

Output:

Bora
Name: Sakni, Age: 25
Name: Bora, Age: 30
Name: Kosal, Age: 35

Understanding arrays and objects and how to manipulate them is crucial in JavaScript for storing and organizing data efficiently.