Learn JS in 30 Days – Day 8

Learn JS in 30 Days – Day 8

Over the past seven days, we’ve covered JavaScript’s basic syntax, variables and data types, operators and expressions, conditional statements, loops, function basics, and scope with variable hoisting. Today we’ll…


This content originally appeared on DEV Community and was authored by Tony Chase

Learn JS in 30 Days - Day 8

Over the past seven days, we've covered JavaScript's basic syntax, variables and data types, operators and expressions, conditional statements, loops, function basics, and scope with variable hoisting. Today we'll learn object basics, which is one of the most important data structures in JavaScript. Objects are a core concept in JavaScript - almost all JavaScript values are objects or can be treated as objects.

📚 Today's Learning Goals

  • Master object creation and access methods
  • Understand object properties and methods
  • Learn object iteration and manipulation
  • Understand object literal syntax and best practices

🏗️ Object Creation

Objects are collections of key-value pairs that can be created in multiple ways.

1. Object Literal (Recommended)

// Basic object literal
let person = {
  name: "John Doe",
  age: 25,
  city: "New York",
  isStudent: true,
};

console.log(person);
// { name: "John Doe", age: 25, city: "New York", isStudent: true }

2. new Object() Constructor

// Using constructor to create object
let car = new Object();
car.brand = "Toyota";
car.model = "Camry";
car.year = 2023;
car.color = "White";

console.log(car);
// { brand: "Toyota", model: "Camry", year: 2023, color: "White" }

3. Object.create() Method

// Using Object.create to create object
let animal = {
  type: "Mammal",
  speak: function () {
    return "Making sound";
  },
};

let dog = Object.create(animal);
dog.name = "Buddy";
dog.breed = "Golden Retriever";

console.log(dog);
console.log(dog.type); // "Mammal" (inherited from animal)

🔑 Object Property Access

Dot Notation

let student = {
  name: "Jane Smith",
  age: 20,
  subjects: ["Math", "English", "Physics"],
  address: {
    city: "Los Angeles",
    district: "Downtown",
  },
};

// Access basic properties
console.log(student.name); // "Jane Smith"
console.log(student.age); // 20

// Access nested objects
console.log(student.address.city); // "Los Angeles"
console.log(student.address.district); // "Downtown"

// Access array properties
console.log(student.subjects[0]); // "Math"

Bracket Notation

let product = {
  "product-name": "Laptop",
  "product-id": "LAPTOP001",
  price: 5999,
  "in-stock": true,
};

// Bracket notation - suitable for property names with special characters
console.log(product["product-name"]); // "Laptop"
console.log(product["product-id"]); // "LAPTOP001"

// Dynamic property access
let propertyName = "price";
console.log(product[propertyName]); // 5999

// Both methods can access regular properties
console.log(product.price); // 5999
console.log(product["price"]); // 5999

✏️ Object Property Modification and Addition

let user = {
  name: "Bob Johnson",
  age: 30,
};

// Modify existing property
user.age = 31;
console.log(user.age); // 31

// Add new properties
user.email = "bob@example.com";
user.city = "Chicago";
console.log(user);
// { name: "Bob Johnson", age: 31, email: "bob@example.com", city: "Chicago" }

// Using brackets to add properties
user["phone"] = "555-0123";
user["is-active"] = true;
console.log(user["phone"]); // "555-0123"

🗑️ Object Property Deletion

let employee = {
  id: 1001,
  name: "Alice Brown",
  department: "Engineering",
  salary: 8000,
  bonus: 2000,
};

console.log("Before deletion:", employee);
// { id: 1001, name: "Alice Brown", department: "Engineering", salary: 8000, bonus: 2000 }

// Delete property
delete employee.bonus;
console.log("After deletion:", employee);
// { id: 1001, name: "Alice Brown", department: "Engineering", salary: 8000 }

// Check if property exists
console.log("bonus" in employee); // false
console.log("salary" in employee); // true

🔍 Object Property Detection

let book = {
  title: "JavaScript: The Definitive Guide",
  author: "David Flanagan",
  pages: 1096,
  published: 2020,
};

// Check if property exists
console.log("title" in book); // true
console.log("publisher" in book); // false

// Check if property value is not undefined
console.log(book.title !== undefined); // true
console.log(book.publisher !== undefined); // false

// hasOwnProperty method - only checks object's own properties
console.log(book.hasOwnProperty("title")); // true
console.log(book.hasOwnProperty("toString")); // false (toString is inherited)

🔄 Object Iteration

for...in Loop

let person = {
  name: "Charlie Wilson",
  age: 28,
  occupation: "Designer",
  skills: ["Photoshop", "Illustrator", "Figma"],
};

// Iterate through all enumerable properties
for (let key in person) {
  console.log(`${key}: ${person[key]}`);
}
// Output:
// name: Charlie Wilson
// age: 28
// occupation: Designer
// skills: Photoshop,Illustrator,Figma

Object.keys() Method

let car = {
  brand: "BMW",
  model: "X5",
  year: 2023,
  color: "Black",
};

// Get all keys of the object
let keys = Object.keys(car);
console.log(keys); // ["brand", "model", "year", "color"]

// Iterate through key array
keys.forEach((key) => {
  console.log(`${key}: ${car[key]}`);
});

Object.values() Method

let product = {
  id: "PROD001",
  name: "Smartphone",
  price: 3999,
  inStock: true,
};

// Get all values of the object
let values = Object.values(product);
console.log(values); // ["PROD001", "Smartphone", 3999, true]

// Iterate through value array
values.forEach((value) => {
  console.log(value);
});

Object.entries() Method

let student = {
  name: "David Lee",
  grade: "Junior",
  gpa: 3.8,
  major: "Computer Science",
};

// Get key-value pair arrays of the object
let entries = Object.entries(student);
console.log(entries);
// [["name", "David Lee"], ["grade", "Junior"], ["gpa", 3.8], ["major", "Computer Science"]]

// Iterate through key-value pairs
entries.forEach(([key, value]) => {
  console.log(`${key}: ${value}`);
});

🎯 Object Methods

Objects can contain functions as properties, which are called methods.

Basic Method Definition

let calculator = {
  result: 0,

  // Method definition
  add: function (num) {
    this.result += num;
    return this;
  },

  subtract: function (num) {
    this.result -= num;
    return this;
  },

  multiply: function (num) {
    this.result *= num;
    return this;
  },

  divide: function (num) {
    if (num !== 0) {
      this.result /= num;
    } else {
      console.log("Error: Cannot divide by zero");
    }
    return this;
  },

  getResult: function () {
    return this.result;
  },

  reset: function () {
    this.result = 0;
    return this;
  },
};

// Using the calculator
calculator.add(10).multiply(2).subtract(5);
console.log(calculator.getResult()); // 15

calculator.reset();
console.log(calculator.getResult()); // 0

ES6 Shorthand Methods

let user = {
  firstName: "Emily",
  lastName: "Davis",

  // ES6 shorthand method
  getFullName() {
    return `${this.firstName} ${this.lastName}`;
  },

  greet() {
    return `Hello, I'm ${this.getFullName()}`;
  },

  updateName(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    return this;
  },
};

console.log(user.getFullName()); // "Emily Davis"
console.log(user.greet()); // "Hello, I'm Emily Davis"

user.updateName("Sarah", "Miller");
console.log(user.getFullName()); // "Sarah Miller"

🏷️ Object Property Descriptors

View Property Descriptors

let config = {
  apiUrl: "https://api.example.com",
  timeout: 5000,
};

// View descriptor of a single property
console.log(Object.getOwnPropertyDescriptor(config, "apiUrl"));
// { value: "https://api.example.com", writable: true, enumerable: true, configurable: true }

// View descriptors of all properties
console.log(Object.getOwnPropertyDescriptors(config));

Create Properties with Descriptors

let settings = {};

// Create read-only property
Object.defineProperty(settings, "version", {
  value: "1.0.0",
  writable: false,
  enumerable: true,
  configurable: false,
});

// Create non-enumerable property
Object.defineProperty(settings, "secret", {
  value: "secret-key-123",
  enumerable: false,
  configurable: true,
});

console.log(settings.version); // "1.0.0"
console.log(settings.secret); // "secret-key-123"

// Try to modify read-only property
settings.version = "2.0.0"; // Silently fails
console.log(settings.version); // Still "1.0.0"

// Iterate properties - secret won't appear
for (let key in settings) {
  console.log(key); // Only outputs "version"
}

🎯 Practice Exercises

Exercise 1: Student Management System

// Create student objects
let students = [
  {
    id: 1,
    name: "John Smith",
    age: 20,
    grade: "Freshman",
    subjects: ["Math", "English", "Physics"],
    scores: {
      math: 85,
      english: 78,
      physics: 92,
    },

    // Calculate average score
    getAverage() {
      let sum = this.scores.math + this.scores.english + this.scores.physics;
      return (sum / 3).toFixed(2);
    },

    // Get grade level
    getGrade() {
      let avg = parseFloat(this.getAverage());
      if (avg >= 90) return "A";
      if (avg >= 80) return "B";
      if (avg >= 70) return "C";
      if (avg >= 60) return "D";
      return "F";
    },

    // Update score
    updateScore(subject, score) {
      if (this.scores.hasOwnProperty(subject)) {
        this.scores[subject] = score;
        return true;
      }
      return false;
    },
  },

  {
    id: 2,
    name: "Jane Doe",
    age: 21,
    grade: "Sophomore",
    subjects: ["Math", "English", "Chemistry"],
    scores: {
      math: 92,
      english: 88,
      chemistry: 85,
    },

    getAverage() {
      let sum = this.scores.math + this.scores.english + this.scores.chemistry;
      return (sum / 3).toFixed(2);
    },

    getGrade() {
      let avg = parseFloat(this.getAverage());
      if (avg >= 90) return "A";
      if (avg >= 80) return "B";
      if (avg >= 70) return "C";
      if (avg >= 60) return "D";
      return "F";
    },

    updateScore(subject, score) {
      if (this.scores.hasOwnProperty(subject)) {
        this.scores[subject] = score;
        return true;
      }
      return false;
    },
  },
];

// Student management functionality
let studentManager = {
  // Find student
  findStudent(id) {
    return students.find((student) => student.id === id);
  },

  // Add student
  addStudent(studentData) {
    let newId = Math.max(...students.map((s) => s.id)) + 1;
    let newStudent = {
      id: newId,
      ...studentData,
      getAverage() {
        let sum = Object.values(this.scores).reduce((a, b) => a + b, 0);
        return (sum / Object.keys(this.scores).length).toFixed(2);
      },
      getGrade() {
        let avg = parseFloat(this.getAverage());
        if (avg >= 90) return "A";
        if (avg >= 80) return "B";
        if (avg >= 70) return "C";
        if (avg >= 60) return "D";
        return "F";
      },
      updateScore(subject, score) {
        if (this.scores.hasOwnProperty(subject)) {
          this.scores[subject] = score;
          return true;
        }
        return false;
      },
    };
    students.push(newStudent);
    return newStudent;
  },

  // Get all student information
  getAllStudents() {
    return students.map((student) => ({
      id: student.id,
      name: student.name,
      age: student.age,
      grade: student.grade,
      average: student.getAverage(),
      grade: student.getGrade(),
    }));
  },

  // Get class average
  getClassAverage() {
    let totalSum = 0;
    let totalCount = 0;

    students.forEach((student) => {
      Object.values(student.scores).forEach((score) => {
        totalSum += score;
        totalCount++;
      });
    });

    return (totalSum / totalCount).toFixed(2);
  },
};

// Test student management system
console.log("=== Student Management System Test ===");

// Display all students
console.log("All students:", studentManager.getAllStudents());

// Find specific student
let student1 = studentManager.findStudent(1);
console.log("Student 1 info:", student1);
console.log("Student 1 average:", student1.getAverage());
console.log("Student 1 grade:", student1.getGrade());

// Update student score
student1.updateScore("math", 95);
console.log("Updated student 1 average:", student1.getAverage());

// Add new student
let newStudent = studentManager.addStudent({
  name: "Bob Johnson",
  age: 19,
  grade: "Freshman",
  subjects: ["Math", "English", "Biology"],
  scores: {
    math: 88,
    english: 82,
    biology: 90,
  },
});
console.log("New student added:", newStudent);

// Class average
console.log("Class average:", studentManager.getClassAverage());

Exercise 2: Library Management System

// Book object
let library = {
  books: [],

  // Add book
  addBook(bookInfo) {
    let book = {
      id: this.generateId(),
      title: bookInfo.title,
      author: bookInfo.author,
      isbn: bookInfo.isbn,
      publishedYear: bookInfo.publishedYear,
      genre: bookInfo.genre,
      pages: bookInfo.pages,
      available: true,
      borrowedBy: null,
      borrowedDate: null,

      // Borrow book
      borrow(userName) {
        if (this.available) {
          this.available = false;
          this.borrowedBy = userName;
          this.borrowedDate = new Date().toISOString().split("T")[0];
          return true;
        }
        return false;
      },

      // Return book
      return() {
        if (!this.available) {
          this.available = true;
          this.borrowedBy = null;
          this.borrowedDate = null;
          return true;
        }
        return false;
      },

      // Get book information
      getInfo() {
        return {
          id: this.id,
          title: this.title,
          author: this.author,
          available: this.available,
          borrowedBy: this.borrowedBy,
          borrowedDate: this.borrowedDate,
        };
      },
    };

    this.books.push(book);
    return book;
  },

  // Generate unique ID
  generateId() {
    return this.books.length > 0
      ? Math.max(...this.books.map((b) => b.id)) + 1
      : 1;
  },

  // Find book
  findBook(id) {
    return this.books.find((book) => book.id === id);
  },

  // Search by title
  searchByTitle(title) {
    return this.books.filter((book) =>
      book.title.toLowerCase().includes(title.toLowerCase())
    );
  },

  // Search by author
  searchByAuthor(author) {
    return this.books.filter((book) =>
      book.author.toLowerCase().includes(author.toLowerCase())
    );
  },

  // Get available books
  getAvailableBooks() {
    return this.books.filter((book) => book.available);
  },

  // Get borrowed books
  getBorrowedBooks() {
    return this.books.filter((book) => !book.available);
  },

  // Get book statistics
  getStatistics() {
    return {
      totalBooks: this.books.length,
      availableBooks: this.getAvailableBooks().length,
      borrowedBooks: this.getBorrowedBooks().length,
      genres: [...new Set(this.books.map((book) => book.genre))],
    };
  },
};

// Test library management system
console.log("=== Library Management System Test ===");

// Add books
library.addBook({
  title: "JavaScript: The Definitive Guide",
  author: "David Flanagan",
  isbn: "978-1491952023",
  publishedYear: 2020,
  genre: "Programming",
  pages: 1096,
});

library.addBook({
  title: "You Don't Know JS",
  author: "Kyle Simpson",
  isbn: "978-1491924464",
  publishedYear: 2015,
  genre: "Programming",
  pages: 278,
});

library.addBook({
  title: "The Three-Body Problem",
  author: "Liu Cixin",
  isbn: "978-7229030933",
  publishedYear: 2008,
  genre: "Science Fiction",
  pages: 302,
});

// Display all books
console.log(
  "All books:",
  library.books.map((book) => book.getInfo())
);

// Search books
console.log("Search 'JavaScript':", library.searchByTitle("JavaScript"));
console.log("Search author 'Liu Cixin':", library.searchByAuthor("Liu Cixin"));

// Borrow book
let book1 = library.findBook(1);
if (book1) {
  console.log("Borrow result:", book1.borrow("John Smith"));
  console.log("After borrowing:", book1.getInfo());
}

// Get statistics
console.log("Library statistics:", library.getStatistics());

// Display available books
console.log(
  "Available books:",
  library.getAvailableBooks().map((book) => book.getInfo())
);

// Return book
if (book1) {
  console.log("Return result:", book1.return());
  console.log("After returning:", book1.getInfo());
}

Exercise 3: Shopping Cart System

// Shopping cart object
let shoppingCart = {
  items: [],

  // Add item
  addItem(product) {
    let existingItem = this.items.find((item) => item.id === product.id);

    if (existingItem) {
      existingItem.quantity += product.quantity || 1;
    } else {
      this.items.push({
        id: product.id,
        name: product.name,
        price: product.price,
        quantity: product.quantity || 1,
        category: product.category,
      });
    }

    return this;
  },

  // Remove item
  removeItem(productId) {
    this.items = this.items.filter((item) => item.id !== productId);
    return this;
  },

  // Update item quantity
  updateQuantity(productId, quantity) {
    let item = this.items.find((item) => item.id === productId);
    if (item) {
      if (quantity <= 0) {
        this.removeItem(productId);
      } else {
        item.quantity = quantity;
      }
    }
    return this;
  },

  // Clear cart
  clear() {
    this.items = [];
    return this;
  },

  // Calculate total
  getTotal() {
    return this.items.reduce(
      (total, item) => total + item.price * item.quantity,
      0
    );
  },

  // Calculate item count
  getItemCount() {
    return this.items.reduce((count, item) => count + item.quantity, 0);
  },

  // Group by category
  getItemsByCategory() {
    let categories = {};
    this.items.forEach((item) => {
      if (!categories[item.category]) {
        categories[item.category] = [];
      }
      categories[item.category].push(item);
    });
    return categories;
  },

  // Apply discount
  applyDiscount(discountPercent) {
    let discount = this.getTotal() * (discountPercent / 100);
    return this.getTotal() - discount;
  },

  // Get cart summary
  getSummary() {
    return {
      itemCount: this.getItemCount(),
      totalAmount: this.getTotal(),
      categories: Object.keys(this.getItemsByCategory()),
      items: this.items.map((item) => ({
        name: item.name,
        quantity: item.quantity,
        subtotal: item.price * item.quantity,
      })),
    };
  },
};

// Test shopping cart system
console.log("=== Shopping Cart System Test ===");

// Add items
shoppingCart
  .addItem({
    id: 1,
    name: "Laptop",
    price: 5999,
    category: "Electronics",
  })
  .addItem({
    id: 2,
    name: "Mouse",
    price: 99,
    quantity: 2,
    category: "Electronics",
  })
  .addItem({
    id: 3,
    name: "Keyboard",
    price: 299,
    category: "Electronics",
  })
  .addItem({
    id: 4,
    name: "Coffee",
    price: 25,
    quantity: 3,
    category: "Food",
  });

console.log("Cart contents:", shoppingCart.items);
console.log("Cart summary:", shoppingCart.getSummary());

// Update item quantity
shoppingCart.updateQuantity(2, 1);
console.log("After updating mouse quantity:", shoppingCart.getSummary());

// View by category
console.log("Grouped by category:", shoppingCart.getItemsByCategory());

// Calculate discounted price
console.log("Original price:", shoppingCart.getTotal());
console.log("Price with 10% discount:", shoppingCart.applyDiscount(10));

// Remove item
shoppingCart.removeItem(4);
console.log("After removing coffee:", shoppingCart.getSummary());

// Clear cart
shoppingCart.clear();
console.log("After clearing:", shoppingCart.getSummary());

🔍 Today's Key Points Summary

  1. Object Creation: Three ways - object literal, constructor, Object.create()
  2. Property Access: Dot notation and bracket notation usage scenarios
  3. Property Operations: Methods for adding, modifying, deleting, and detecting properties
  4. Object Iteration: for...in, Object.keys(), Object.values(), Object.entries()
  5. Object Methods: Defining and using functions as object properties
  6. Property Descriptors: Controlling property characteristics like writability and enumerability

📚 Tomorrow's Preview

Tomorrow we'll learn about arrays in detail, including:

  • Array creation and basic operations
  • Array methods for adding, removing, modifying, and querying
  • Array iteration and transformation methods
  • Advanced array operations

đź’ˇ Learning Tips

  1. Practice object operations: Practice various object operations through real projects
  2. Understand the this keyword: Master how this points in object methods
  3. Choose appropriate iteration methods: Select the most suitable iteration method based on needs
  4. Pay attention to property naming: Follow good property naming conventions

That's the end of Day 8's learning content.


This content originally appeared on DEV Community and was authored by Tony Chase


Print Share Comment Cite Upload Translate Updates
APA

Tony Chase | Sciencx (2025-10-17T03:32:43+00:00) Learn JS in 30 Days – Day 8. Retrieved from https://www.scien.cx/2025/10/17/learn-js-in-30-days-day-8/

MLA
" » Learn JS in 30 Days – Day 8." Tony Chase | Sciencx - Friday October 17, 2025, https://www.scien.cx/2025/10/17/learn-js-in-30-days-day-8/
HARVARD
Tony Chase | Sciencx Friday October 17, 2025 » Learn JS in 30 Days – Day 8., viewed ,<https://www.scien.cx/2025/10/17/learn-js-in-30-days-day-8/>
VANCOUVER
Tony Chase | Sciencx - » Learn JS in 30 Days – Day 8. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/10/17/learn-js-in-30-days-day-8/
CHICAGO
" » Learn JS in 30 Days – Day 8." Tony Chase | Sciencx - Accessed . https://www.scien.cx/2025/10/17/learn-js-in-30-days-day-8/
IEEE
" » Learn JS in 30 Days – Day 8." Tony Chase | Sciencx [Online]. Available: https://www.scien.cx/2025/10/17/learn-js-in-30-days-day-8/. [Accessed: ]
rf:citation
» Learn JS in 30 Days – Day 8 | Tony Chase | Sciencx | https://www.scien.cx/2025/10/17/learn-js-in-30-days-day-8/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.