Section 2.2: Data Types
Tutorial 2.2.2: Non-Primitive Data Types (Objects, Arrays, and Functions)
Non-Primitive Data Types in JavaScript
In JavaScript, non-primitive data types, such as objects, arrays, and functions, allow for more complex data structures and behaviors. Unlike primitives, non-primitive types are mutable and can hold multiple values or properties.
1. Objects
Objects are key-value pairs that can represent more complex data.
- Syntax:
let person = {
name: "Alice",
age: 25,
isStudent: true,
};- Accessing Properties:
- Dot notation:
console.log(person.name); // "Alice"- Bracket notation:
console.log(person["age"]); // 25- Adding/Updating Properties:
person.city = "New York";
person.age = 26;
console.log(person);- Deleting Properties:
delete person.isStudent;
console.log(person);2. Arrays
Arrays are ordered collections of elements, which can be of any type.
- Syntax:
let fruits = ["apple", "banana", "cherry"];- Accessing Elements:
console.log(fruits[0]); // "apple"- Adding Elements:
fruits.push("orange");
console.log(fruits); // ["apple", "banana", "cherry", "orange"]- Removing Elements:
fruits.pop(); // Removes the last element
fruits.shift(); // Removes the first element
console.log(fruits);- Iterating Over Arrays:
for (let fruit of fruits) {
console.log(fruit);
}3. Functions
Functions are blocks of code designed to perform specific tasks. They are reusable and can take inputs (parameters) and return outputs.
- Function Declaration:
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // "Hello, Alice!"- Function Expression:
const add = function (a, b) {
return a + b;
};
console.log(add(3, 5)); // 8- Arrow Functions (ES6):
const multiply = (a, b) => a * b;
console.log(multiply(4, 7)); // 28Comparing Primitives and Non-Primitives
- Primitives hold a single value and are immutable.
- Non-primitives hold collections or behaviors and are mutable.
Exercise
- Create an object
carwith propertiesmake,model, andyear. - Add a new property
colorto the object. - Create an array
colorswith at least three color names. Add a new color and remove the first color. - Write a function
sumthat takes two numbers as arguments and returns their sum.
Example:
let car = { make: "Toyota", model: "Corolla", year: 2020 };
car.color = "blue";
console.log(car);
let colors = ["red", "green", "blue"];
colors.push("yellow");
colors.shift();
console.log(colors);
const sum = (a, b) => a + b;
console.log(sum(10, 15)); // 25