JavaScript is a versatile programming language primarily used for client-side web development. It's known for its ability to create dynamic and interactive web pages. It is a powerful language with a wide range of applications beyond web development, including server-side programming (with Node.js), mobile app development (with frameworks like React Native), and even desktop application development.
JavaScript objects are one of the fundamental data types, allowing us to store collections of key-value pairs.
Example:
// Define an object representing a person
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
isStudent: false,
address: {
street: "123 Main St",
city: "Anytown",
state: "CA"
},
// Method to get the full name of the person
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
// Accessing properties of the object
console.log("First Name:", person.firstName); // Output: "John"
console.log("Last Name:", person["lastName"]); // Another way to access properties
console.log("Age:", person.age); // Output: 30
// Nested object access
console.log("Street:", person.address.street); // Output: "123 Main St"
console.log("City:", person.address.city); // Output: "Anytown"
// Calling a method of the object
console.log("Full Name:", person.fullName()); // Output: "John Doe"
// Adding a new property to the object
person.gender = "Male";
console.log("Gender:", person.gender); // Output: "Male"
Explanation:
- We define an object `person` with various properties such as `firstName`, `lastName`, `age`, `isStudent`, and `address`.
- The `address` property is another nested object containing `street`, `city`, and `state`.
- There's also a method `fullName` defined within the object to get the full name of the person by concatenating the `firstName` and `lastName`.
- We access properties using dot notation (`object.property`) or bracket notation (`object["property"]`).
- We can also add new properties to the object dynamically, such as `gender`.
Code Compiler Link: https://app.singhteekam.in/codecompiler/