It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

LCC: Web Apps Development Essentials

Course by zooboole,

Last Updated on 2024-09-05 14:50:08

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

  1. Create an array called colors with at least five different color names as strings.
  2. Write a function called addColor that takes a color as an argument and adds it to the colors array.
  3. Create an object called car that includes properties: make, model, and year. Also, add a method called describe that logs a description of the car.
  4. Finally, call the describe method on the car object.