JavaScript Objects and Their Methods

JavaScript Objects and Their Methods

String Objects

Creating string objects in JavaScript can be done in multiple ways:

// Primitive string
let text1 = "hello";
console.log(typeof text1); // Output: string

// String object
let text2 = new String("hello");
console.log(typeof text2); // Output: object

// Template literals (ES6)
let text3 = `This is a
multi-line string`;

Common string methods include:

// ES6 template literals with variable substitution
let firstName = "John";
let years = 30;
let greeting = `${firstName} is ${years} years old`;
console.log(greeting); // Output: John is 30 years old

// Understanding slice() vs substring()
let sample = "abcdefghij";

// slice() - negative indices count from end
console.log(sample.slice(1, 5));    // Output: bcde
console.log(sample.slice(-5, -1));  // Output: fghi
console.log(sample.slice(3, 1));    // Output: "" (empty string)

// substring() - no negative indices
console.log(sample.substring(1, 5)); // Output: bcde
console.log(sample.substring(5, 1)); // Output: bcde (swapped)
console.log(sample.substring(-2, 5)); // Output: abcde (negative treated as 0)

Array Objects

Arrays can be created in several ways:

// Empty array
let fruits = [];

// Array with elements
let colors = ["red", "green", "blue"];

// Array constructor
let numbers = new Array(1, 2, 3, 4, 5);

// Array with specific length
let emptyItems = new Array(5);

console.log(fruits.length); // Output: 0
console.log(colors.length); // Output: 3
console.log(numbers.length); // Output: 5
console.log(emptyItems.length); // Output: 5

// Sparse arrays
let sparse = [1, 2, 3];
sparse[10] = "last";
console.log(sparse); // [1, 2, 3, empty × 7, "last"]
console.log(sparse.length); // Output: 11

Array traversal methods:

// Traditional for loop
let scores = [85, 92, 78, 96, 88];
for (let i = 0; i < scores.length; i++) {
  console.log(`Score ${i}: ${scores[i]}`);
}

// For...of loop (recommended)
for (const score of scores) {
  console.log(`Score: ${score}`);
}

// For...in loop (not recommended for arrays)
for (const index in scores) {
  console.log(`Index ${index}: ${scores[index]}`);
}

Common array methods:

Sorting Arrays

// Default sort (lexicographical)
let names = ["Zoe", "Amy", "Charlie", "David"];
names.sort();
console.log(names); // Output: ["Amy", "Charlie", "David", "Zoe"]

// Numeric sort
let values = [42, 17, 8, 99, 23, 5];
values.sort((a, b) => a - b);
console.log(values); // Output: [5, 8, 17, 23, 42, 99]

// Mixed array sort
let mixed = [10, "2", 8, "1", 3];
mixed.sort((a, b) => a - b);
console.log(mixed); // Output: [1, 3, 8, 10, "2"]

Splicing Arrays

// Remove elements
let animals = ["dog", "cat", "elephant", "lion", "tiger"];
let removed = animals.splice(1, 2); // Remove 2 elements starting at index 1
console.log(removed); // Output: ["cat", "elephant"]
console.log(animals); // Output: ["dog", "lion", "tiger"]

// Replace elements
let pets = ["dog", "cat", "fish", "bird"];
pets.splice(2, 1, "hamster", "rabbit"); // Replace 1 element with 2 new ones
console.log(pets); // Output: ["dog", "cat", "hamster", "rabbit", "bird"]

// Insert without removing
let fruits = ["apple", "banana", "cherry"];
fruits.splice(1, 0, "orange", "kiwi"); // Insert at index 1 without removing
console.log(fruits); // Output: ["apple", "orange", "kiwi", "banana", "cherry"]

Stack Operations

// push() - add to end
let stack = [];
stack.push("first");
stack.push("second");
console.log(stack); // Output: ["first", "second"]

// pop() - remove from end
let last = stack.pop();
console.log(last); // Output: "second"
console.log(stack); // Output: ["first"]

// unshift() - add to beginning
let queue = [];
queue.unshift("first");
queue.unshift("second");
console.log(queue); // Output: ["second", "first"]

// shift() - remove from beginning
let first = queue.shift();
console.log(first); // Output: "second"
console.log(queue); // Output: ["first"]

Iteration Methods

// forEach()
let numbers = [1, 2, 3, 4, 5];
numbers.forEach((value, index, array) => {
  console.log(`Value: ${value}, Index: ${index}, Array: ${array}`);
});

// map()
let doubled = numbers.map(value => value * 2);
console.log(doubled); // Output: [2, 4, 6, 8, 10]

Date Objects

Date objects can be created in several ways:

// Current date and time
let now = new Date();
console.log(now.toString()); // Current date as string
console.log(now.toISOString()); // ISO format string

// Date string
let fromString = new Date("2023-05-15T14:30:00");
console.log(fromString.toLocaleString()); // Localized date string

// Timestamp
let fromTimestamp = new Date(0); // Unix epoch
console.log(fromTimestamp.toLocaleString()); // January 1, 1970

// Individual components
let customDate = new Date(2023, 4, 15, 14, 30, 0, 0); // Month is 0-indexed
console.log(customDate.toLocaleString()); // May 15, 2023 2:30:00 PM

Math Object

The Math object provides mathematical constants and functions:

// Constants
console.log(Math.PI); // Output: 3.141592653589793
console.log(Math.E); // Output: 2.718281828459045

// Methods
console.log(Math.round(4.5)); // Output: 5
console.log(Math.floor(4.7)); // Output: 4
console.log(Math.ceil(4.2)); // Output: 5
console.log(Math.abs(-5)); // Output: 5
console.log(Math.max(3, 7, 2, 9)); // Output: 9
console.log(Math.min(3, 7, 2, 9)); // Output: 2
console.log(Math.random()); // Random number between 0 and 1
console.log(Math.pow(2, 3)); // Output: 8

JSON Object

JSON (JavaScript Object Notation) is used for data interchange:

RegExp Objects

Regular expressions are used for pattern matching in strings:

Common regex patterns:

Function Objects

Functions in JavaScript can be defined in several ways:

 a / b;
console.log(divide(10, 2)); // Output: 5

// Immediately Invoked Function Expression (IIFE)
(function() {
  console.log("This runs immediately!");
})();

// Function with rest parameters
function sum(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}

console.log(sum(1, 2, 3, 4, 5)); // Output: 15

Variable scope and lifecycle:

Understanding function execution context:

Tags: javascript programming web development Objects Methods

Posted on Tue, 28 Jul 2026 17:08:44 +0000 by fme