Հայերեն Русский

Deep Dive into Objects in JavaScript

Understanding Objects

In JavaScript, objects are fundamental constructs that represent collections of key-value pairs. These pairs, also known as properties and methods, encapsulate data and functionality related to the object. Objects provide a structured way to manage related data and behavior, making them crucial for building scalable and maintainable applications.

Key Characteristics of Objects:

Creating Objects

Objects can be created in several ways, with object literals being the most common method. An object literal is a comma-separated list of key-value pairs enclosed in curly braces {}.

Example of Creating an Object:

let book = {
    title: "The Great Gatsby",
    author: "F. Scott Fitzgerald",
    year: 1925,
    isAvailable: true
};

In this example, book is an object with properties like title, author, year, and isAvailable.

Accessing and Modifying Object Properties

Properties within an object can be accessed and modified using dot notation or bracket notation.

console.log(book.title);  // Outputs "The Great Gatsby"
book.isAvailable = false;  // Modifies the isAvailable property

Object Methods and 'this'

Methods are functions that are properties of an object. The this keyword in a method refers to the object from which the method is called, providing access to the object’s properties and methods.

Example with Method and this:

let person = {
    firstName: "Alice",
    lastName: "Johnson",
    greet: function() {
        console.log("Hello, " + this.firstName + " " + this.lastName);
    }
};

person.greet();  // Outputs "Hello, Alice Johnson"

In person.greet, this refers to the person object, allowing access to its firstName and lastName properties.

Practical Examples

Let's apply these concepts by creating and using objects in practical scenarios:

  1. Representing a Book:

    let book = {
        title: "1984",
        author: "George Orwell",
        publishYear: 1949,
        getDescription: function() {
            return `${this.title} by ${this.author}, published in ${this.publishYear}`;
        }
    };
    
    console.log(book.getDescription());
    
  2. Modeling a Person:

    let person = {
        name: "John Doe",
        age: 30,
        occupation: "Software Developer",
        introduce: function() {
            console.log(`Hi, I'm ${this.name}, a ${this.age}-year-old ${this.occupation}.`);
        }
    };
    
    person.introduce();
    
  3. Describing a Product:

    let product = {
        name: "Laptop",
        price: 999.99,
        discount: 0.10,
        calculateDiscountPrice: function() {
            return this.price * (1 - this.discount);
        }
    };
    
    console.log("Discounted price:", product.calculateDiscountPrice());
    

These examples showcase how objects in JavaScript can encapsulate related data and behavior, providing a structured and intuitive way to represent complex entities in code. By using objects, developers can create more organized, readable, and maintainable programs.

Arrays and Array Methods in JavaScript

Introduction to Arrays

Arrays in JavaScript are used to store ordered collections of items, which can be of any data type, including numbers, strings, objects, or even other arrays. Arrays are indexed collections, starting from index 0 for the first element, index 1 for the second, and so on.

Creating and Accessing Array Elements:

To create an array, you use square brackets [], with elements separated by commas. You access elements in an array by specifying the index in square brackets.

let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // Outputs "Apple"
console.log(fruits[2]); // Outputs "Cherry"

Common Array Methods

Arrays come with built-in methods that facilitate manipulation and querying of the array contents.

Using Array Methods

These array methods can be used to process and manipulate data within arrays, serving various purposes from transformation to aggregation.

Hands-on Exercise

Students should apply these array methods to perform common tasks:

  1. Data Transformation with map: Convert an array of numbers to an array of their square roots.

    let numbers = [4, 9, 16];
    let roots = numbers.map(Math.sqrt); // [2, 3, 4]
    
  2. Data Filtering with filter: Extract numbers greater than a certain value from an array.

    let filteredNumbers = numbers.filter(x => x > 5); // [9, 16]
    
  3. Accumulating Values with reduce: Calculate the total of all numbers in an array.

    let total = numbers.reduce((sum, current) => sum + current, 0); // 29
    
  4. Searching and Sorting: Find elements in an array or sort them based on certain criteria using find, some, every, or sort.

    let found = numbers.find(x => x > 10); // 16
    numbers.sort((a, b) => a - b); // Sorts numbers in ascending order
    

Through these exercises, students will gain hands-on experience with JavaScript array methods, learning how to effectively manipulate and process array data. This practice reinforces their understanding of arrays and their

Introduction to DOM Manipulation

What is the DOM?

The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page structure as a tree of objects, allowing scripts to access and manipulate the document’s content, structure, and styles. Through the DOM, JavaScript can add, remove, and modify elements and attributes, change styles, respond to user events, and more, enabling dynamic and interactive web experiences.

Selecting Elements

To manipulate the DOM, you first need to select the elements you want to work with. JavaScript provides several methods to select elements from the DOM:

Manipulating the DOM

After selecting elements, you can manipulate the DOM in various ways:

Interactive DOM Exercise

Let's engage in hands-on exercises to practice DOM manipulation:

  1. Select and Modify Elements: Select elements on a webpage and modify their content, style, or other properties. For example, change the text and color of a heading element.

  2. Create a Dynamic List: Build a simple interactive list where users can add and remove items. Use prompt to get user input for new items and add them to the list displayed on the webpage.

     let ulElement = document.createElement('ul');
     document.body.appendChild(ulElement);
    
     function addItem() {
         let itemText = prompt('Enter item text');
         if (itemText) {
             let liElement = document.createElement('li');
             liElement.innerText = itemText;
             ulElement.appendChild(liElement);
         }
     }
    
     function removeItem() {
         if (ulElement.hasChildNodes()) {
             ulElement.removeChild(ulElement.lastChild);
         }
     }
    
  3. Respond to User Events: Add buttons to the webpage that call addItem and removeItem functions when clicked, allowing the user to interact with the list dynamically.

In these exercises, students will learn how to select and manipulate DOM elements, create interactive content, and respond to user events, gaining practical skills in dynamic web page manipulation and enhancing their understanding of how JavaScript interacts with the DOM.