intro-frontend-course

Lecture 1: JavaScript Objects

Introduction to JavaScript Objects

JavaScript objects are collections of key-value pairs. They are fundamental to JavaScript and are used extensively for storing and manipulating data. Each key in an object is a string (or symbol) and the corresponding value can be any data type, including another object.

Creating Objects

There are several ways to create objects in JavaScript:

  1. Object Literals

Real-World Example: A User Profile

const userProfile = {
  username: 'john_doe',
  email: 'john@example.com',
  age: 25,
  hobbies: ['reading', 'gaming', 'coding']
};
  1. Using the Object Constructor
const userProfile = new Object();
userProfile.username = 'john_doe';
userProfile.email = 'john@example.com';
userProfile.age = 25;
userProfile.hobbies = ['reading', 'gaming', 'coding'];
  1. Using the Object.create Method
const userProfile = Object.create(null);
userProfile.username = 'john_doe';
userProfile.email = 'john@example.com';
userProfile.age = 25;
userProfile.hobbies = ['reading', 'gaming', 'coding'];

Accessing Object Properties

You can access properties using dot notation or bracket notation:

console.log(userProfile.username); // Dot notation
console.log(userProfile['email']); // Bracket notation

Modifying Object Properties

You can add or modify properties directly:

userProfile.age = 26; // Modify existing property
userProfile.location = 'New York'; // Add new property

Deleting Object Properties

Use the delete keyword to remove a property from an object:

delete userProfile.hobbies;

Methods in Objects

Methods are functions stored as properties in objects. They can be defined using function expressions or shorthand syntax in ES6:

Real-World Example: A Shopping Cart

const shoppingCart = {
  items: [],
  addItem(item) {
    this.items.push(item);
  },
  removeItem(itemName) {
    this.items = this.items.filter(item => item.name !== itemName);
  },
  totalItems() {
    return this.items.length;
  }
};

shoppingCart.addItem({ name: 'Laptop', price: 1200 });
shoppingCart.addItem({ name: 'Phone', price: 800 });
console.log(shoppingCart.totalItems()); // 2
shoppingCart.removeItem('Phone');
console.log(shoppingCart.totalItems()); // 1

Using this Keyword

The this keyword refers to the current object within a method:

const userProfile = {
  username: 'john_doe',
  greet() {
    console.log(`Hello, my name is ${this.username}`);
  }
};

userProfile.greet(); // Hello, my name is john_doe

Nested Objects

Objects can contain other objects as properties:

Real-World Example: A Book Library

const library = {
  name: 'City Library',
  location: 'Main Street',
  books: [
    {
      title: '1984',
      author: 'George Orwell',
      year: 1949
    },
    {
      title: 'To Kill a Mockingbird',
      author: 'Harper Lee',
      year: 1960
    }
  ]
};

console.log(library.books[0].title); // 1984

Iterating Over Object Properties

You can use for...in loop or Object.keys method to iterate over object properties:

for (let key in userProfile) {
  console.log(`${key}: ${userProfile[key]}`);
}

Object.keys(userProfile).forEach(key => {
  console.log(`${key}: ${userProfile[key]}`);
});

Object Methods

JavaScript provides several built-in methods for objects:

  1. Object.keys: Returns an array of a given object’s property names.
console.log(Object.keys(userProfile)); // ['username', 'email', 'age', 'location']
  1. Object.values: Returns an array of a given object’s property values.
console.log(Object.values(userProfile)); // ['john_doe', 'john@example.com', 26, 'New York']
  1. Object.entries: Returns an array of a given object’s key-value pairs.
console.log(Object.entries(userProfile)); // [['username', 'john_doe'], ['email', 'john@example.com'], ['age', 26], ['location', 'New York']]
  1. Object.assign: Copies all enumerable properties from one or more source objects to a target object.
const newProfile = Object.assign({}, userProfile);
console.log(newProfile);
  1. Object.freeze: Freezes an object, preventing new properties from being added or existing properties from being removed or modified.
Object.freeze(userProfile);
userProfile.age = 27; // This will not change the age property
console.log(userProfile.age); // 26
  1. Object.seal: Seals an object, preventing new properties from being added, but allowing existing properties to be modified.
Object.seal(userProfile);
userProfile.age = 27; // This will change the age property
delete userProfile.username; // This will not delete the username property
console.log(userProfile.age); // 27
console.log(userProfile.username); // john_doe

Practical Example: Managing a Collection of Movies

const movieCollection = {
  movies: [
    { title: 'Inception', director: 'Christopher Nolan', year: 2010 },
    { title: 'The Matrix', director: 'Lana Wachowski, Lilly Wachowski', year: 1999 }
  ],
  addMovie(movie) {
    this.movies.push(movie);
  },
  removeMovie(title) {
    this.movies = this.movies.filter(movie => movie.title !== title);
  },
  listMovies() {
    this.movies.forEach(movie => {
      console.log(`${movie.title} directed by ${movie.director} (${movie.year})`);
    });
  }
};

movieCollection.addMovie({ title: 'Interstellar', director: 'Christopher Nolan', year: 2014 });
movieCollection.listMovies();
movieCollection.removeMovie('Inception');
movieCollection.listMovies();

Video Resources:

By understanding and mastering JavaScript objects, you can build more complex and powerful applications.