<script>
//Create an OBJECT
//The const keyword in JavaScript is a modern way to declare variables
//It is used to declare variables whose values need to remain constant throughout the lifetime of the application.
const person = {
firstname: "John",
lastname: "Doe",
age: 38,
gender: "Male"
};
//or in one line
const person = {firstname: "John", lastname: "Doe", age: 38, gender: "Male"};
//Or using new Ojbect() function to create an object
const car = new Object({brand: "Honda", color: "Blue"};
//Or You can create an object first and then assign value
const employee = {};
emplyee.name = "John Doe";
employee.age = 43;
//Object can be nested - One object can include one or more objects as elements
family = {
father: {name: "John Doe", age: 45, gender: "Male"},
mother: {name: "Jennifer Doe", age: 35, gender: "Female"},
children: {
child1: {name: "kyle Doe", age: 10, gender: "Male"},
child2: {name: "Mary Doe", age: 6, gender: "Female"}
}
}
</script>An object is a collection of key-value pairs (called properties), where keys are strings (or Symbols) and values can be any data type—including functions (called methods).
Objects are fundamental to JavaScript and are used to model real-world entities, organize data, and build complex applications.
- Array: An Array is an object type designed for storing data collections.
const array_name = [item1, item2, ...]; //convert to array to string const fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.toString(); cars.length // Returns the number of elements cars.sort() // Sorts the array //accessing last element const fruits = ["Banana", "Orange", "Apple", "Mango"]; let fruit = fruits[fruits.length - 1]; const fruits = ["Banana", "Orange", "Apple", "Mango"]; let text = "<ul>"; fruits.forEach(myFunction); text += "</ul>"; function myFunction(value) { text += "<li>" + value + "</li>"; }
-
Set: A JavaScript Set is a collection of unique values. const letters = new Set(["a","b","c"]);
- Maps: A JavaScript Map is an object that can store collections of key-value pairs, similar to a dictionary in other programming languages.
// Create an empty Map const fruits = new Map(); // Set Map Values fruits.set("apples", 500); fruits.set("bananas", 300); fruits.set("oranges", 200); // Create a Map const fruits = new Map([ ["apples", 500], ["bananas", 300], ["oranges", 200] ]); // adding a new value fruits.set("mangos", 100); // changing a value fruits.set("apples", 200); // The
get()method gets the value of a key in a Map: fruits.get("apples"); // Returns 500