Day 18: Working with Arrays and Objects
Arrays
An array is a collection of items stored at contiguous memory locations. In JavaScript, arrays are used to store multiple values in a single variable. They can hold any type of data, including numbers, strings, and even other arrays.
Creating an Array
You can create an array using square brackets []
:
let fruits = ['apple', 'banana', 'cherry'];
Accessing Array Elements
You can access elements in an array using their index (starting from 0):
console.log(fruits[0]); // Output: apple
console.log(fruits[1]); // Output: banana
Array Methods
Some common methods to manipulate arrays include:
- push(): Adds an item to the end of the array.
- pop(): Removes the last item from the array.
- shift(): Removes the first item from the array.
- unshift(): Adds an item to the beginning of the array.
fruits.push('orange'); // Adds 'orange' to the end
console.log(fruits); // Output: ['apple', 'banana', 'cherry', 'orange']
Objects
An object is a collection of key-value pairs. It is used to store data in a structured way. Each key is a string (or Symbol) and the value can be of any data type.
Creating an Object
You can create an object using curly braces {}
:
let person = {
name: 'John',
age: 30,
job: 'developer'
};
Accessing Object Properties
You can access properties using dot notation or bracket notation:
console.log(person.name); // Output: John
console.log(person['age']); // Output: 30
Object Methods
You can also define functions as methods within an object:
person.greet = function() {
console.log('Hello, my name is ' + this.name);
};
person.greet(); // Output: Hello, my name is John
Summary
- Arrays are used for ordered collections of items.
- Objects are used for storing data in key-value pairs.
Assignment 18
- Create an array called
colors
with at least five different color names as strings. - Write a function called
addColor
that takes a color as an argument and adds it to thecolors
array. - Create an object called
car
that includes properties:make
,model
, andyear
. Also, add a method calleddescribe
that logs a description of the car. - Finally, call the
describe
method on thecar
object.