Module 2: Variables, Data Types, Type Casting, and Comments
Complex Types: Arrays and Objects (Basic Usage)
Besides primitive types, JavaScript has complex data types, primarily Objects.
Objects: An object is a collection of key-value pairs (properties). Properties can be strings, numbers, booleans, functions, or even other objects.
// Object literal syntax let person = { firstName: "John", lastName: "Doe", age: 30, isStudent: false, greet: function() { // A method (function property) console.log("Hello, my name is " + this.firstName); } }; console.log(person.firstName); // Accessing property: "John" person.age = 31; // Modifying property person.greet(); // Calling a method: "Hello, my name is John"
Arrays: An array is a special type of object used to store an ordered list of values. Array elements can be of any data type.
// Array literal syntax let colors = ["red", "green", "blue"]; let mixedArray = [10, "apple", true, null]; console.log(colors[0]); // Accessing element by index: "red" colors[1] = "yellow"; // Modifying element colors.push("purple"); // Adding element to the end console.log(colors.length); // Getting the number of elements: 4 // Iterating through an array for (let i = 0; i < colors.length; i++) { console.log(colors[i]); }
Both objects and arrays are reference types, meaning when you assign them to another variable, you are copying a reference to the original object/array in memory, not the object/array itself.