Skip to main content

Part 10: Working with APIs in JavaScript

  Working with APIs in JavaScript Outline: 1. Introduction to APIs: 1.1 Definition of APIs: Explanation of what an API (Application Programming Interface) is. Understanding the role of APIs in web development. Types of APIs:  RESTful APIs, SOAP APIs, etc. 1.2 Importance of APIs in Web Development: How APIs facilitate communication between different software systems. Use cases of APIs in modern web development. Examples of popular APIs and their impact. 2. Making API Requests: 2.1 HTTP Methods: Overview of common HTTP methods: GET, POST, PUT, DELETE. Explanation of when to use each HTTP method. 2.2 Fetch API: Introduction to the Fetch API in JavaScript. Making simple GET requests with Fetch. Handling responses from Fetch requests. 2.3 Sending Data in API Requests: Using POST requests to send data to the server. Handling different types of data (JSON, form data) in API requests. 3. Handling API Responses: 3.1 Parsing JSON: Importance of JSON (JavaScript Object Notation) in API responses.

Learning JavaScript Step by Step - Part 7: Objects

Part 7: Objects in JavaScript



What Are Objects?

Objects in JavaScript are collections of key-value pairs. They're used to represent entities with properties and behaviors. Here's how you create an object:
let person = {
    name: "Alice",
    age: 30,
    isStudent: false
};
1. Curly braces {} define an object.
2. Each property is a key-value pair separated by a colon.

Accessing Object Properties

You can access object properties using dot notation or bracket notation:
console.log(person.name); // Output: "Alice"
console.log(person["age"]); // Output: 30

Modifying Object Properties

To change the value of an object property, simply assign a new value to it:
person.age = 31;
console.log(person.age); // Output: 31

Adding and Deleting Properties

You can add new properties to an object or delete existing ones as needed:
person.country = "USA"; // Adding a new property
delete person.isStudent; // Deleting an existing property
console.log(person);
// Output: { name: 'Alice', age: 31, country: 'USA' }

Objects as Data Structures

Objects are versatile data structures. They can store various data types, including arrays and even other objects. This flexibility makes them suitable for representing complex data models and structures.

To find a property in an object

To find a property in an object in JavaScript, you can use a few different methods. Here are some common ways to do so:

1. Dot Notation:

You can access an object's property using dot notation by specifying the property name after the object.
const person = {
    name: "Alice",
    age: 30,
};

const name = person.name;
console.log(name); // Output: "Alice"

2. Bracket Notation:

Bracket notation allows you to access object properties using a string that represents the property name. This can be useful when the property name is stored in a variable.
const person = {
    name: "Bob",
    age: 25,
  };
 
  const propertyName = "name";
  const propertyValue = person[propertyName];
  console.log(propertyValue); // Output: "Bob"

3. hasOwnProperty Method:

You can use the hasOwnProperty method to check if an object has a specific property. This method returns true if the object has the property and false if it doesn't.
const person = {
    name: "Carol",
    age: 35,
  };
 
  const hasName = person.hasOwnProperty("name");
  console.log(hasName); // Output: true

4. in Operator:

The in operator checks if an object has a specific property and returns true if it does.
const person = {
    name: "David",
    age: 40,
  };
 
  const hasName = "name" in person;
  console.log(hasName); // Output: true

5. Using a Ternary Operator:

You can use a ternary operator to check if a property exists and provide a default value if it doesn't.
const person = {
    age: 22,
  };
 
  const name = person.name ? person.name : "Unknown";
  console.log(name); // Output: "Unknown"

How to loop through properties of an object?

You can loop through the properties of an object in JavaScript using various methods. The choice of method depends on your specific requirements and the level of control you need over the iteration process. Here are some common ways to loop through object properties:

1. For...In Loop:

The for...in loop allows you to iterate through the enumerable properties of an object.
const person = {
    name: "Alice",
    age: 30,
};

for (let key in person) {
    console.log(key + ": " + person[key]);
}
// Output:
// name: Alice
// age: 30
This loop iterates through all enumerable properties of the person object and logs the property names and values.

2. Object.keys() Method:

The Object.keys() method returns an array of the object's own enumerable property names, which you can then loop through using a for...of loop.
const person = {
    name: "Bob",
    age: 25,
};

const keys = Object.keys(person);
console.log(keys);
// Output: [ 'name', 'age' ]
// Using for of to loop through keys array
for (let key of keys) {
    console.log(key + ": " + person[key]);
}
// Output:
// name: Bob
// age: 25
This approach is useful when you want to iterate through an object's own properties, excluding properties inherited from the prototype chain.

3. Object.entries() Method:

The Object.entries() method returns an array of the object's own enumerable property [key, value] pairs, which you can loop through.
const person = {
    name: "Carol",
    age: 35,
};

for (let [key, value] of Object.entries(person)) {
    console.log(key + ": " + value);
}
// Output:
// name: Carol
// age: 35
This method is suitable when you need to access both the property names and their corresponding values.

4. Object.getOwnPropertyNames() Method:

The Object.getOwnPropertyNames() method returns an array of all property names, including non-enumerable ones.
const person = {
    name: "David",
    age: 40,
};

const propertyNames = Object.getOwnPropertyNames(person);

for (let propertyName of propertyNames) {
    console.log(propertyName + ": " + person[propertyName]);
}
// Output:
// name: David
// age: 40
This method is useful when you need to access all properties, including non-enumerable ones.
Remember to choose the method that best suits your use case, taking into consideration the need to include or exclude inherited properties and the specific properties you want to access.

How to add a method to an object in JavaScript?

You can add a method to an object in JavaScript by defining a function and assigning it as a property of the object. Here's how you can add a method to an object:
// Define an object
const person = {
    name: "Alice",
    age: 30,
};

// Add a method to the object
person.greet = function () {
    console.log(`Hello, my name is ${this.name}
    and I am ${this.age} years old.`);
};

// Call the method
person.greet();
// Output: Hello, my name is Alice
// and I am 30 years old.
In this example:
1. We define an object named person with properties name and age.
2. We add a method named greet to the object by assigning it a function that logs a greeting message using the object's properties.
3. We call the greet method using person.greet(), which results in the method being executed.
It's important to note that when you define a method in an object, you can access the object's properties and other methods using the this keyword within the method. This allows you to work with the object's own data.
You can also add methods directly to an object at the time of defining:
const person = {
    name: "Alice",
    age: 30,
    greet: function () {
        console.log(`Hello, my name is ${this.name}
      and I am ${this.age} years old.`);
    },
};

person.greet();
You can also add methods directly to an object using ES6 object method shorthand:
const person = {
    name: "Alice",
    age: 30,
    greet() {
        console.log(`Hello, my name is ${this.name}
      and I am ${this.age} years old.`);
    },
};

person.greet();
This shorthand syntax makes it even more concise to define methods as properties of an object.

This keyword in JavaScript

In JavaScript, the this keyword is a reference to the current object. It is used within object methods and functions to access the properties and methods of the object to which they belong. The primary purposes of using the this keyword in objects are as follows:

1. Accessing Object Properties:

When a method is called within an object, you can use this to refer to the object itself and access its properties. This allows you to work with the data specific to that object.

const person = {
    name: "Alice",
    age: 30,
    greet: function () {
      console.log(`Hello, my name is ${this.name}
      and I am ${this.age} years old.`);
    },
  };
 
  person.greet();
  // Output: "Hello, my name is Alice
  // and I am 30 years old."

2. Referring to the Current Object:

When you have multiple instances of an object, the this keyword helps distinguish which object you're working with. It ensures that each object accesses its own properties and methods.
const person1 = {
    name: "Alice",
    age: 30,
};

const person2 = {
    name: "Bob",
    age: 25,
};

function greet() {
    console.log(`Hello, my name is ${this.name}
    and I am ${this.age} years old.`);
}

// assigning greet function to person1 object
person1.greet = greet;
// assigning greet function to person2 object
person2.greet = greet;

person1.greet();
// Output: "Hello, my name is Alice
// and I am 30 years old."
person2.greet();
// Output: "Hello, my name is Bob
// and I am 25 years old."
In the above example we created two objects person1 and person2, then assigned greet function to each object. We used this keyword to distinguish which object we are working with when accessing the objects properties. 

3. Creating Reusable Code:

The this keyword allows you to create more reusable and generic code. By using this, you can create methods and functions that work with the data of the specific object that calls them.
function greet() {
    console.log(`Hello, my name is ${this.name}
    and I am ${this.age} years old.`);
  }
 
  const person1 = {
    name: "Alice",
    age: 30,
    greet: greet,
  };
 
  const person2 = {
    name: "Bob",
    age: 25,
    greet: greet,
  };
 
  person1.greet();
  // Output: "Hello, my name is Alice
  // and I am 30 years old."
  person2.greet();
  // Output: "Hello, my name is Bob
  // and I am 25 years old."
The this keyword allows for dynamic and context-aware code, making it an essential part of object-oriented programming in JavaScript. It ensures that objects can interact with their own data and methods, enabling code reusability and flexibility.

How to create an object in JavaScript using new keyword?

In JavaScript, you can create objects using the new keyword in combination with a constructor function. A constructor function is a regular JavaScript function that is used to create and initialize objects. Here's how you can create an object using the new keyword and a constructor function:
1. Create a Constructor Function:
Define a function that will serve as the constructor for your object. This function typically starts with a capital letter to indicate that it's a constructor.
function Person(name, age) {
    this.name = name;
    this.age = age;
  }
2. Create an Object Using the Constructor:
Use the new keyword to create an instance of the object. When you invoke the constructor with new, it creates a new object and sets the properties and methods defined within the constructor.
const person1 = new Person("Alice", 30);
const person2 = new Person("Bob", 25);
3. Access Object Properties:
You can access the properties of the newly created object using dot notation.
console.log(person1.name); // Output: "Alice"
console.log(person2.age);  // Output: 25
The new keyword creates a new object, sets the value of this to the new object within the constructor, and allows you to initialize object properties. This is a common pattern in JavaScript for creating custom objects and is often referred to as "constructor-based object creation."
Here's a complete example of creating and using objects with a constructor function:
function Person(name, age) {
    this.name = name;
    this.age = age;
  }
 
  const person1 = new Person("Alice", 30);
  const person2 = new Person("Bob", 25);
 
  console.log(person1.name); // Output: "Alice"
  console.log(person2.age);  // Output: 25
Constructor functions are a fundamental way to create objects in JavaScript, and they can include methods and properties to initialize and work with object instances.

How to create an object using the new Object()?

In JavaScript, you can create an object using the new Object() syntax, which is another way to create objects in addition to constructor functions. Here's how you can create an object using this method:
1. Using new Object():
You can create an empty object using the new Object() constructor.
let person = new Object();
2. Adding Properties and Values:
After creating an empty object, you can add properties and values to it using dot notation or bracket notation.
// dot notation
person.name = "Alice";
person.age = 30;

// bracket notation
person[name] = "Alice";
person[age] = 30;
Alternatively, you can add properties during object creation by passing an object literal to the new Object() constructor.
let person = new Object({
    name: "Alice",
    age: 30,
});
console.log(person);
// Output: { name: 'Alice', age: 30 }
3. Accessing Object Properties:
You can access the properties of the object using dot notation.
console.log(person.name); // Output: "Alice"
console.log(person.age);  // Output: 30
Here's a complete example of creating an object using the new Object() syntax:
let person = new Object();
person.name = "Alice";
person.age = 30;

console.log(person.name); // Output: "Alice"
console.log(person.age);  // Output: 30
This method is useful when you need to create objects dynamically and add properties as needed. However, for more complex objects or when creating multiple objects of the same structure, using constructor functions or object literals may be more convenient.

Example of complex object

Here's an example of an object in JavaScript that contains various data types, including variables, another object, an array, and a function:
const complexObject = {
    name: "John",
    age: 35,
    address: {
        street: "123 Main St",
        city: "Exampleville",
        postalCode: "ABCDE",
    },
    hobbies: ["Reading", "Hiking", "Cooking"],
    sayHello: function () {
        console.log(`Hello, my name is ${this.name},
                    and I'm ${this.age} years old.`);
    },
};
// showing a complex object in console
console.log(complexObject);
// Output: {
//   name: 'John',
//   age: 35,
//   address: { street: '123 Main St', city: 'Exampleville',
                postalCode: 'ABCDE' },
//   hobbies: [ 'Reading', 'Hiking', 'Cooking' ],
//   sayHello: [Function: sayHello]
// }

// Accessing properties and invoking the function
console.log(complexObject.name);                  
// Output: "John"
console.log(complexObject.address.city);            
// Output: "Exampleville"
console.log(complexObject.hobbies[0]);              
// Output: "Reading"
complexObject.sayHello();                          
// Output: "Hello, my name is John, and I'm 35 years old."
In the above example:
1. complexObject is an object that contains:name and age as variables.
2. address as an embedded object with its own properties.
3. hobbies as an array of strings.
4. sayHello as a function that logs a greeting using the object's properties.
You can access the properties and invoke the function using dot notation. This demonstrates how you can create complex objects with a mix of data types and behaviors in JavaScript.

Getters and Setters in JavaScript

Getters and setters are special methods in JavaScript used to control access to an object's properties. They allow you to define the behavior of reading (getting) and writing (setting) property values. Getters and setters are used to add an extra layer of control, validation, and encapsulation to an object's properties. They are particularly useful when you want to perform actions or checks when reading or assigning values to properties.
Here's how to use getters and setters in JavaScript:
Using Getters:
A getter is a method that gets the value of a specific property when that property is accessed. It is defined using the get keyword followed by a function. Getters are used to retrieve the value of a property, possibly after some computation or validation.
const person = {
    firstName: "John",
    lastName: "Doe",
    get fullName() {
      return `${this.firstName} ${this.lastName}`;
    },
  };
 
  console.log(person.fullName);
  // Output: "John Doe"
In the above example, the fullName getter retrieves and returns the full name of the person object by concatenating the firstName and lastName properties.
Using Setters:
A setter is a method that sets the value of a specific property when that property is assigned a new value. It is defined using the set keyword followed by a function. Setters are used to validate or modify the value of a property when it is being assigned.
const temperature = {
    _celsius: 0,
    // Note the underscore (_) convention for private properties

    get celsius() {
        return this._celsius;
    },

    set celsius(value) {
        if (value < -273.15) {
            console.error("That's below absolute zero!");
        } else {
            this._celsius = value;
        }
    },
};

temperature.celsius = 25; // Setting the temperature in Celsius
console.log(temperature.celsius); // Output: 25

// Attempting to set an invalid temperature
temperature.celsius = -300;
// Output: "That's below absolute zero!"
console.log(temperature.celsius); // Output: 25 (unchanged)
In the above example, the celsius setter ensures that the assigned value is not below absolute zero, and it logs an error message if an invalid value is provided.
Why Use Getters and Setters:
1. Encapsulation and Data Validation: Getters and setters allow you to encapsulate and control access to object properties. They enable you to perform data validation and ensure that property values remain within certain constraints.
2. Computed Properties: Getters enable you to compute property values on-the-fly, making it easier to maintain consistency in your data.
3. Backward Compatibility: You can introduce getters and setters to existing objects without changing the property access syntax for clients that use those objects.
4. Code Maintainability: Getters and setters improve code readability and make it easier to add additional behavior to property access in the future.
Overall, getters and setters are valuable tools in object-oriented programming for enhancing the control and functionality of object properties in your JavaScript code.

Prototypes in JavaScript

In JavaScript, you can add properties or methods to a constructor function or its prototype after the constructor function has been created. This is a common practice to extend the functionality of objects created from that constructor. To achieve this, you can work with the prototype chain. Let's explore how this is done:
Adding Properties or Methods to a Constructor Function:
To add properties or methods directly to the constructor function, you can simply assign them to the function itself. Here's an example of adding a method to a constructor function:
function Person(name, age) {
    this.name = name;
    this.age = age;
}

// Adding a method to the constructor function
Person.prototype.greet = function () {
    console.log(`Hello, my name is ${this.name},
                and I'm ${this.age} years old.`);
};

const person1 = new Person("Alice", 30);
console.log(person1);
// Output: Person { name: 'Alice', age: 30 }
// If you open the prototype of Person object in console
// you will see the greet function under prototype
person1.greet();
// Output: "Hello, my name is Alice, and I'm 30 years old."
In the above example, we added the greet method to the Person constructor function, and instances of Person can now call this method.
Working with Object Prototypes:
In JavaScript, each object has a prototype, which is an object that acts as a template for the object. When you access a property or method on an object, if the object itself doesn't have that property or method, JavaScript looks up the prototype chain to find it in the object's prototype.
For constructor functions, the prototype is accessible via the prototype property of the constructor. You can add properties or methods to this prototype, and they will be available to all objects created from that constructor.
function Animal(name) {
    this.name = name;
}

// Adding a method to the prototype
Animal.prototype.sayHello = function () {
    console.log(`Hello, I'm ${this.name}.`);
};

const dog = new Animal("Buddy");
const cat = new Animal("Whiskers");

dog.sayHello(); // Output: "Hello, I'm Buddy."
cat.sayHello(); // Output: "Hello, I'm Whiskers."
In the above example, the sayHello method is added to the prototype of the Animal constructor, making it available to all instances created from it.
Object prototypes are essential in JavaScript as they allow you to share methods and properties across multiple objects, which promotes code reuse and more efficient memory usage. You can add, modify, or extend prototypes to add common behavior to objects created from constructor functions.

Built-in Objects in JavaScript

Math Object:

The Math object in JavaScript is a built-in object that provides a collection of mathematical constants and functions, allowing you to perform various mathematical operations in your code. It does not require instantiation, and its methods and properties are accessed directly through the Math object.
Here are some common use cases for the Math object and how you can use it in JavaScript:
1. Math Constants:
The Math object provides several mathematical constants, including Math.PI (Ï€) and Math.E (Euler's number).
const circumference = 2 * Math.PI * radius;
2. Math Methods:
Math offers a wide range of mathematical methods for performing operations like rounding, exponentiation, trigonometry, and more. Some common methods include Math.round(), Math.ceil(), Math.floor(), Math.trunc(), Math.pow(), Math.sqrt(), Math.sin(), Math.cos(), and Math.random().
Math.round():
The Math.round() method rounds a number to the nearest integer. If the fractional part is equal to or greater than 0.5, it rounds up; otherwise, it rounds down.
let roundedNumber = Math.round(4.7);
console.log(roundedNumber); // Output: 5
roundedNumber = Math.round(4.2);
console.log(roundedNumber); // Output: 4
Math.ceil():
The Math.ceil() method always rounds a number up to the nearest integer, regardless of the fractional part.
const ceilNumber = Math.ceil(4.1);
console.log(ceilNumber); // Output: 5
Math.floor():
The Math.floor() method always rounds a number down to the nearest integer, ignoring the fractional part.
const floorNumber = Math.floor(4.9);
console.log(floorNumber); // Output: 4
Math.trunc():
The Math.trunc() method simply removes the decimal part of a number and returns the integer part. It effectively truncates the number toward zero.
const truncatedNumber = Math.trunc(4.7);
console.log(truncatedNumber); // Output: 4
You can use these methods whenever you need to manipulate or format numbers in your JavaScript code. Here are some practical examples:
const num1 = 4.7;
const num2 = 4.1;

const roundedNum1 = Math.round(num1);  // 5
const roundedNum2 = Math.round(num2);  // 4

const ceilNum1 = Math.ceil(num1);      // 5
const ceilNum2 = Math.ceil(num2);      // 5

const floorNum1 = Math.floor(num1);    // 4
const floorNum2 = Math.floor(num2);    // 4

const truncatedNum1 = Math.trunc(num1);  // 4
const truncatedNum2 = Math.trunc(num2);  // 4
These methods are useful for various applications, such as formatting decimal numbers for display, converting floating-point numbers to integers, or performing rounding operations in mathematical calculations.
Math.random()
The Math.random() method in JavaScript is used to generate a pseudo-random floating-point number between 0 (inclusive) and 1 (exclusive). This method is often used to generate random numbers for various purposes, such as simulations, games, or selecting random elements from a collection.
Here's how you use the Math.random() method in JavaScript:
const randomValue = Math.random();
console.log(randomValue);
// Output: 0.12115498986928719
The Math.random() method generates a random number in the range [0, 1), meaning it can produce values between 0 (inclusive) and just below 1 (exclusive). This value is typically a decimal number.

To get random integer numbers between min (inclusive) and max (exclusive):

To generate random integer numbers between 0 and 10 (exclusive) in JavaScript, you can use the Math.random() method along with Math.floor(). Here's an example of how to do it:
const min = 0; // Minimum value (inclusive)
const max = 10; // Maximum value (exclusive)
const randomInteger = Math.floor(Math.random() * (max - min) + min);

console.log(randomInteger);
// Output: 3
In the above code:
1. min is set to 0, which is the minimum value (inclusive).
2. max is set to 10, which is the maximum value (exclusive). Since Math.random() generates a number between 0 (inclusive) and 1 (exclusive), we need to set the maximum value to 10 to ensure that we get random numbers from 0 to 9.
3. Math.random() generates a random decimal number between 0 (inclusive) and 1 (exclusive).
4. Math.floor() rounds down the decimal number to the nearest integer, effectively converting it to an integer.
The result of randomInteger will be a random integer between 0 and 9, inclusive of 0 and exclusive of 10.

To get random integer numbers between min (inclusive) and max (inclusive):

If you want to generate random numbers between a minimum value (inclusive) and a maximum value (inclusive), you can use the following code:
function getRandomIntInclusive(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

const min = 1; // Minimum value (inclusive)
const max = 10; // Maximum value (inclusive)

const randomInteger = getRandomIntInclusive(min, max);

console.log(randomInteger);
In this code:
1. min is set to the minimum value you want (inclusive).
2. max is set to the maximum value you want (inclusive).
3. The getRandomIntInclusive function takes min and max as parameters.
4. Math.ceil(min) ensures that the minimum value is rounded up to the nearest integer.
5. Math.floor(max) ensures that the maximum value is rounded down to the nearest integer.
6. (max - min + 1) calculates the range of values, and Math.random() generates a random number between 0 (inclusive) and 1 (exclusive).
7. Math.floor() is used to round down the decimal number to the nearest integer.
8. The result is a random integer between min and max, inclusive of both min and max.
This code will generate random integers within the specified range, inclusive of both the minimum and maximum values.

Date Object:

In JavaScript, the Date object is used to work with dates and times. It provides a way to create, manipulate, and format date and time values. Here's an overview of the Date object and how to use it in JavaScript:
Creating a Date Object:
You can create a Date object in several ways:
1. Creating a Current Date and Time:
To create a Date object that represents the current date and time, simply call the Date constructor without any arguments:
const currentDate = new Date();
console.log(currentDate);
// Output: 2023-10-28T16:32:58.990Z
2. Creating a Date for a Specific Moment:
You can also create a Date object for a specific moment by passing a date string, a timestamp, or individual date and time components as arguments to the Date constructor:
// Using a date string
const specificDate = new Date("2023-10-25T12:00:00");
console.log(specificDate);
// Output: 2023-10-25T18:00:00.000Z

// Using a timestamp (milliseconds since January 1, 1970)
const specificTime = new Date(1635145200000);
console.log(specificTime);
// Output: 2021-10-25T07:00:00.000Z

// Using individual components (year, month, day, hour,
// minute, second, millisecond)
const customDate = new Date(2023, 9, 25, 12, 0, 0, 0);
console.log(customDate);
// Output: 2023-10-25T18:00:00.000Z
Please note that month number starts with 0 and ends with 11. So number 0 is Jan and 11 is Dec. Similarly week days starts with 0 and ends with 6, so number 0 is Sunday and number 6 is Saturday.
Getting Date and Time Components:
Once you have a Date object, you can extract various date and time components from it, such as the year, month, day, hour, minute, second, and millisecond:
const date = new Date();
console.log(date);
// Output: 2023-10-28T17:08:42.861Z
const year = date.getFullYear();
console.log(year);
// Output: 2023
const month = date.getMonth();
console.log(month);
// Output: 9
// Month is zero-based (0 = January, 11 = December)
const day = date.getDate();
console.log(day);
// Output 28
const hour = date.getHours();
console.log(hour);
// Output 11
const minute = date.getMinutes();
console.log(minute);
// Output 8
const second = date.getSeconds();
console.log(second);
// Output 42
const millisecond = date.getMilliseconds();
console.log(millisecond);
// Output 861
Formatting Dates:
To format a Date object as a string, you can use various methods like toDateString(), toTimeString(), and toLocaleString(). You can also format dates using external libraries like date-fns, moment.js, or the Intl.DateTimeFormat object for more advanced formatting.
const date = new Date();

console.log(date.toDateString());
// Output: Sat Oct 28 2023
console.log(date.toTimeString());
// Output: 11:15:42 GMT-0600 (Mountain Daylight Time)
console.log(date.toLocaleString());
// Output: 10/28/2023, 11:15:42 AM
Manipulating Dates:
The Date object allows you to perform various date and time manipulations. You can add or subtract time intervals using methods like setFullYear(), setMonth(), setDate(), and setHours(), among others:
const date = new Date();

date.setFullYear(2024);
date.setMonth(0); // January (0-based)
date.setDate(1);
date.setHours(15);
date.setMinutes(30);
date.setSeconds(0);

console.log(date.toLocaleString());
// Output: 1/1/2024, 3:30:00 PM
Comparing Dates:
You can compare Date objects to determine their relative order using standard comparison operators, like <, <=, >, and >=. This is useful for date comparisons in various scenarios.
const today = new Date();
console.log(today);
// Output: 2023-10-28T17:33:04.690Z

const yesterday = new Date(today);
yesterday.setDate(today.getDate() - 1);
console.log(yesterday);
// Output: 2023-10-27T17:33:04.690Z

if (yesterday < today) {
    console.log("Yesterday is before today.");
}
// Output: Yesterday is before today.
The Date object is a powerful tool for working with dates and times in JavaScript, and it provides numerous methods and capabilities to handle various date-related tasks in your applications.

Knowledge Check:

Here are 10 multiple-choice questions to test your knowledge about objects in JavaScript:
Question 1: What is an object in JavaScript?
A) A primitive data type 
B) A collection of key-value pairs 
C) A function 
D) A loop construct
Show Answer

Answer: B) A collection of key-value pairs
Explanation: In JavaScript, an object is a composite data type that represents a collection of key-value pairs. Each key is a string (or symbol in modern JavaScript), and its associated value can be of any data type.


Question 2: How do you access a property of an object in JavaScript?
A) Using square brackets 
B) Using parentheses 
C) Using the dot notation 
D) Using colons
Show Answer

Answer: A) Using square brackets and C) Using the dot notation Explanation: In JavaScript, you can access an object's property using both square brackets (object['property']) and the dot notation (object.property). Both methods are commonly used for property access in JavaScript.


Question 3: Which of the following is not a way to create an object in JavaScript?
A) Object literals
B) Constructor functions
C) createObject method
D) Object.create() method
Show Answer

Answer: C) createObject method
Explanation: While you can create objects using object literals, constructor functions, and the Object.create() method, there is no built-in createObject method for creating objects in JavaScript.


Question 4: What is the purpose of a constructor function in JavaScript?
A) To create and initialize objects
B) To perform mathematical calculations
C) To declare global variables
D) To create loops
Show Answer

Answer: A) To create and initialize objects
Explanation: Constructor functions are used to create and initialize objects with predefined properties and behaviors.


Question 5: Which keyword is used to access the current instance of an object within its methods?
A) this
B) self
C) object
D) current
Show Answer

Answer: A) this
Explanation: The this keyword is used to refer to the current instance of the object within its methods.


Question 6: What is an object prototype in JavaScript?
A) A template for creating new objects
B) A mathematical concept
C) A loop construct
D) A data type
Show Answer

Answer: A) A template for creating new objects
Explanation: An object prototype in JavaScript is a template that defines the structure and behavior of objects created from a constructor function. It allows objects to inherit properties and methods.


Question 7: How can you add a property to an object prototype in JavaScript?
A) Using the extends keyword
B) Using the prototype property
C) Using the new keyword
D) Using the super keyword
Show Answer

Answer: B) Using the prototype property
Explanation: You can add properties and methods to an object's prototype using the prototype property of its constructor function.


Question 8: What is the primary purpose of getters and setters in JavaScript objects?
A) To perform mathematical calculations
B) To control access to object properties
C) To create loops
D) To declare global variables
Show Answer

Answer: B) To control access to object properties
Explanation: Getters and setters are used to control and add an extra layer of behavior when getting or setting object properties.


Question 9: Which operator is used to access object properties?
A) +
B) =
C) .
D) ::
Show Answer

Answer: C) .
Explanation: The dot (.) operator is used to access object properties.


Question 10: What is an object literal in JavaScript?
A) A string that represents an object
B) A mathematical formula
C) A pattern for creating objects
D) A syntax for defining objects directly in code
Show Answer

Answer: D) A syntax for defining objects directly in code
Explanation: An object literal is a way to define and create objects directly in JavaScript code using curly braces {}.


These questions and answers should help you understand key concepts related to objects in JavaScript.

Comments

Popular posts from this blog

Part 9: Asynchronous Programming in JavaScript

Part 9: Asynchronous Programming in JavaScript Outline: 1. Introduction to Asynchronous Programming Definition of Asynchronous Programming Importance in Web Development Comparison with Synchronous Programming 2. Understanding JavaScript's Single-Threaded Model  Brief Explanation of JavaScript's Event Loop How Asynchronous Operations Fit into a Single Thread 3. Callbacks Explanation of Callback Functions Common Use Cases Callback Hell and Its Challenges 4. Promises Introduction to Promises as a Better Alternative to Callbacks Promise States: Pending, Fulfilled, Rejected Chaining Promises for Sequential Asynchronous Operations Error Handling with Promises 5. Async/Await Introduction to Async/Await as a Syntactic Sugar for Promises Writing Asynchronous Code in a Synchronous Style Error Handling with Async/Await 6. Event Listeners Asynchronous Nature of Event Listeners Handling User Interactions Asynchronously Examples of Asynchronous Event Handling 7. Timers and In

Part 8:What is DOM Manipulation in JavaScript?

What is DOM Manipulation in JavaScript? Welcome to Part 8 of our JavaScript Step by Step series! In this part, we will find out, what is DOM Manipulation in JavaScript? DOM (Document Object Model) manipulation using JavaScript is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. What is the DOM? The DOM is a tree-like structure that represents the HTML of a web page. Each element in the HTML document is represented as a node in the DOM tree. These nodes are organized in a hierarchical structure, with the document itself at the root and the HTML elements as its branches and leaves. Here's a simple example of the DOM tree structure for a basic HTML document: <! DOCTYPE html > < html > < head >         < title > My Web Page </ title > </ head > < body >         < h1 > Hello, World! </ h1 >         < p > This is a paragraph. </ p > &

Learning JavaScript Step by Step - Part 6: Arrays

Part 6: Arrays in JavaScript Welcome back to our JavaScript learning journey! In this part, we'll dive into one of the essential data structures: arrays. These are fundamental building blocks in JavaScript that enable you to work with collections of data and create more complex data structures. Creating Arrays An array is a collection of values, which can be of any data type, stored in a single variable. There are two methods of creating arrays in JavaScript: Method 1: Using Array Literals In this method, you directly list the elements you want to include within the array.This is the most common and convenient way to create an array. You define the array by enclosing a list of values inside square brackets []. Example: / Creating an array of numbers let numbers = [ 1 , 2 , 3 , 4 , 5 ] ; // Creating an array of strings let fruits = [ " apple " , " banana " , " cherry " ] ; // Creating an array of mixed data types let mixedArray = [ 1 , &quo

Learn JavaScript Step by Step Part 4 Control Flow

Part 4: Control Flow in JavaScript Welcome to the next part of our JavaScript journey! In this segment, we'll explore control flow in JavaScript. Control flow allows you to make decisions in your code and execute specific blocks of code based on conditions. It's a fundamental concept in programming. At the end of this blog you will get a quiz to test your understanding of this topic. Let's dive in! Conditional Statements: Making Decisions Conditional statements are used to make decisions in your code. They allow your program to take different actions depending on whether a certain condition is true or false. 1. If Statement:  The if statement is the most basic conditional statement. It executes a block of code if a specified condition evaluates to true. let age = 18 ; if (age >= 18 ) {     console . log ( " You are an adult. " ) ; } If you run the code in VS Code, the output will be: Output: You are an adult. 2. Else Statement:  You can use the else stateme

Learn JavaScript Step by Step Part 5 Functions

Part 5: Functions in JavaScript In this part, we'll dive into the exciting world of functions in JavaScript. Functions are like superpowers for your code. They allow you to encapsulate reusable pieces of logic, making your code more organized, efficient, and easier to maintain. We'll explore what functions are, how to declare them, and how to use them effectively. What Is a Function? Imagine a function as a mini-program within your program. It's a self-contained block of code that performs a specific task or calculation. Functions are designed to be reusable, so you can call them whenever you need that specific task done without writing the same code over and over. Declaring a Function: To declare a function, you use the function keyword followed by a name for your function. Here's a simple function that adds two numbers: function addNumbers ( a , b ) {     let result = a + b ;     return result ; } function: The keyword that tells JavaScript you're creating