An object is a collection of properties, and each property is associated with a name (key) and a value.
Key Characteristics
let person = {
name: "Alice",
age: 25,
isStudent: true,
greet: function() {
console.log("Hello, " + this.name);
}
};
console.log(person.name); // Output: Alice
person.greet(); // Output: Hello, Alice
Accessing Object Properties
Key Methods for Object Manipulation:
Nested Objects:
let car = {
make: "Toyota",
model: "Corolla",
engine: {
type: "V4",
horsepower: 130
}
};
console.log(car.engine.horsepower); // Output: 130
Arrays are special objects designed to store sequences of values. They are a type of list-like object and are one of the most common data structures.
Key Characteristics:
let colors = ["Red", "Green", "Blue"];
console.log(colors[1]); // Output: Green
// Adding a new element
colors.push("Yellow");
console.log(colors); // Output: ["Red", "Green", "Blue", "Yellow"]
Array Methods
Multidimensional Arrays:
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[1][2]); // Output: 6
Functions are a type of object that can be invoked to perform an action. In JavaScript, functions are first-class citizens, which means they can be treated as data.
Key Characteristics:
function greet(name) {
return "Hello, " + name;
}
let message = greet("Alice");
console.log(message); // Output: Hello, Alice
Functions as Values
let add = function(a, b) {
return a + b;
};
console.log(add(5, 3)); // Output: 8
Anonymous Functions and Arrow Functions
let multiply = (x, y) => x * y;
console.log(multiply(4, 5)); // Output: 20
The Date object is used to work with dates and times in JavaScript.
let now = new Date();
console.log(now); // Output: Current date and time
// Specific date
let birthday = new Date('1990-05-15');
console.log(birthday); // Output: Tue May 15 1990