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

Discover more amazing content handpicked just for you

Tutorial
javascript

Comparison and Logical Operators

// AND operator
console.log(true && true); // true
console.log(true && false); // false

// OR operator
console.log(false || true); // true
console.log(false || false); // false

// NOT operator
console.log(!true); // false
console.log(!false); // true

Use comparison and logical operators together for complex conditions.

Dec 11, 2024
Read More
Tutorial
javascript

Arithmetic Operators

  • Be cautious to avoid unexpected results.
  console.log(5 + "5"); // "55"
  console.log(5 - "2"); // 3 (string "2" is coerced to number)

Dec 11, 2024
Read More
Tutorial
javascript

Primitive Data Types

  let age = 30; // Integer
  let price = 19.99; // Float
  console.log(age + price); // 49.99
  • Special values:
  • Infinity: Result of dividing by zero.

Dec 11, 2024
Read More
Tutorial
javascript

Variables and Constants

Variables can be declared without assigning a value. Uninitialized variables are undefined.

Example:

Dec 10, 2024
Read More
Tutorial
javascript

Hello World and Comments

  • Begin with //.
  • Example:
     // This is a single-line comment
     console.log("Hello, World!"); // Outputting to the console

Dec 10, 2024
Read More
Tutorial
javascript css +1

How to Create a Chrome Extension for Automating Tweets on X (Twitter)

Create a new folder for your project, and within it, create the following files:

- manifest.json
- background.js
- content.js
- popup.html
- popup.js

Dec 10, 2024
Read More
Tutorial
javascript

Easy JavaScript Tutorial for Beginners

console.log("Hello, world!");

JavaScript supports several data types:

Sep 18, 2024
Read More
Tutorial
javascript

JavaScript Tutorial for Absolute Beginners

let x = 5;
let y = 3;

console.log(x + y); // Addition
console.log(x - y); // Subtraction
console.log(x * y); // Multiplication
console.log(x / y); // Division
console.log(x % y); // Modulus (remainder)
let a = 10;
let b = 5;

console.log(a > b);  // Greater than
console.log(a < b);  // Less than
console.log(a == b); // Equal to
console.log(a != b); // Not equal to

Sep 02, 2024
Read More
Tutorial
javascript

Creating a Dropdown Menu with JavaScript

In this script:

  • We use `querySelector` to select the dropdown toggle link and the dropdown menu.
  • We add an event listener to toggle the display of the dropdown menu when the "Services" link is clicked.
  • We add a second event listener to close the dropdown menu if the user clicks outside of it.

Sep 02, 2024
Read More
Tutorial
javascript

Understanding JavaScript Classes

Static methods and properties belong to the class itself, rather than to instances of the class. They are often used for utility functions that are related to the class but don't need to operate on instances of the class.

class MathUtils {
  static add(a, b) {
    return a + b;
  }
}

console.log(MathUtils.add(5, 3)); // Output: 8

Sep 02, 2024
Read More
Tutorial
javascript

Asynchronous JavaScript: A Beginner's Guide

Creating a Promise:

const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("Data fetched");
    }, 2000);
});

console.log("Start");
promise.then((message) => {
    console.log(message);
});
console.log("End");

Aug 30, 2024
Read More
Tutorial
javascript

Understanding the DOM in JavaScript: A Comprehensive Guide

The DOM provides methods to navigate between nodes, which is useful for finding related elements.

Navigating Between Nodes:

Aug 30, 2024
Read More
Tutorial
javascript

JavaScript DSA (Data Structures and Algorithms) Tutorial: A Beginner's Guide

  • Searching Algorithms
  • Sorting Algorithms
  • Recursive Algorithms
  • Dynamic Programming
  • Greedy Algorithms
  • Backtracking

JavaScript is a versatile language often used for web development. However, it is also capable of handling complex algorithms and data structures. Learning DSA in JavaScript can help you become a better problem solver and enhance your understanding of how to write efficient code.

Aug 30, 2024
Read More
Tutorial
javascript

Understanding call, apply, and bind in JavaScript

In this example, greet is called with person as the this value, and 'Hello' and '!' as arguments. The this inside the greet function refers to person.

The apply method is similar to call, but it takes an array of arguments instead of passing them individually.

Aug 30, 2024
Read More
Cheatsheet
solidity

Solidity Cheatsheet

- address: Holds a 20-byte Ethereum address

- bytes1, bytes32: Fixed-size byte arrays

Aug 22, 2024
Read More
Cheatsheet
javascript

JavaScript Utility Libraries Cheatsheet

Ramda is a functional programming library for JavaScript developers, designed for better code composition and function handling.

<table>
  <tr>
    <th>Function</th>
    <th>Description</th>
    <th>Example</th>
  </tr>
  <tr>
    <td><code>R.compose(...functions)
    Composes functions from right to left.
    R.compose(Math.abs, R.add(1))(-5) => 4
  
  
    R.curry(fn)
    Returns a curried version of the provided function.
    R.curry((a, b) => a + b)(1)(2) => 3
  
  
    R.filter(predicate, list)
    Returns a new list containing only the elements that satisfy the predicate.
    R.filter(x => x % 2 === 0, [1, 2, 3, 4]) => [2, 4]
  
  
    R.map(fn, list)
    Applies the function to each element of the list.
    R.map(x => x * 2, [1, 2, 3]) => [2, 4, 6]
  
  
    R.reduce(reducer, initialValue, list)
    Reduces the list to a single value using the reducer function.
    R.reduce(R.add, 0, [1, 2, 3]) => 6
  

Aug 21, 2024
Read More
Code
javascript

JavaScript Sort Array of Objects by Property

No preview available for this content.

Jan 26, 2024
Read More
Code
java

Calculate Factorial

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!