DeveloperBreeze

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)); // 28

Comparing Primitives and Non-Primitives

  • Primitives hold a single value and are immutable.
  • Non-primitives hold collections or behaviors and are mutable.

Exercise

  1. Create an object car with properties make, model, and year.
  2. Add a new property color to the object.
  3. Create an array colors with at least three color names. Add a new color and remove the first color.
  4. Write a function sum that 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

Continue Reading

Handpicked posts just for you — based on your current read.

JavaScript Tutorial for Absolute Beginners

Create a new HTML file where you’ll write your JavaScript code. Save it as index.html.

Sep 02, 2024 Tutorial

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!