Mastering Static Methods of Arrays and Objects in JavaScript

Title: Mastering Static Methods of Arrays and Objects in JavaScript

Static methods in JavaScript like Array.from, Object.entries, and others are incredibly useful β€” but often misunderstood or underused. This article will walk through what these methods are, how they work, and when they can make your code cleaner and more expressive. Let’s look at practical, real-life scenarios where they shine.

🧱 1. Array.from() β€” Create Arrays from Anything

Array.from() is a static method that creates a new array instance from an array-like or iterable object.

πŸ“¦ Use Case: Converting NodeList from the DOM

const buttons = document.querySelectorAll("button");
// querySelectorAll returns a NodeList, not a real array
// Convert NodeList to a true array so we can use array methods like forEach
const buttonArray = Array.from(buttons);

// Disable all buttons on the page
buttonArray.forEach(btn => btn.disabled = true);

This is perfect when you want to manipulate DOM elements with array methods.

πŸ” More Examples:

// From string
Array.from("foo"); // ['f', 'o', 'o']

// From Set
let s = new Set(["foo", window]);
Array.from(s); // ['foo', window]

// Doubling values
Array.from([1, 2, 3], x => x * 2); // [2, 4, 6]

// Creating a range of numbers
Array.from({ length: 5 }, (_, i) => i + 1); // [1, 2, 3, 4, 5]

πŸ›  Real-Life: Game Initialization

// Creating score tracking for 10 players
// Array.from with { length: 10 } creates an array of 10 empty slots
// The second argument () => 0 fills each slot with 0 (initial score)
// This is useful for initializing default values like scores, states, or empty strings
const scores = Array.from({ length: 10 }, () => 0);

console.log(scores); // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

πŸ”‘ 2. Object.entries() β€” Get Key-Value Pairs

Returns an array of [key, value] pairs from an object’s enumerable properties.

πŸ“¦ Use Case: Displaying User Settings

const userSettings = { darkMode: true, fontSize: 'large', language: 'en' };

// Object.entries returns an array of [key, value] pairs:
// [['darkMode', true], ['fontSize', 'large'], ['language', 'en']]
// Use a for...of loop with destructuring to access each key and value
for (const [key, value] of Object.entries(userSettings)) {
  console.log(`${key}: ${value}`);
  // Could be used to apply settings dynamically
}

πŸ” 3. Object.fromEntries() β€” Convert Back to Object

The inverse of Object.entries(). Useful when transforming objects.

πŸ“¦ Use Case: Filtering keys

const raw = { username: 'john', password: '1234', isAdmin: false };

// Step 1: Convert the object into an array of [key, value] pairs
const entries = Object.entries(raw);
// entries = [
//   ['username', 'john'],
//   ['password', '1234'],
//   ['isAdmin', false]
// ]

// Step 2: Filter out the entry where the key is 'password'
const filteredEntries = entries.filter(([key, value]) => key !== 'password');
// filteredEntries = [
//   ['username', 'john'],
//   ['isAdmin', false]
// ]

// Step 3: Convert the filtered entries back to an object
const filtered = Object.fromEntries(filteredEntries);

console.log(filtered);
// Output: { username: 'john', isAdmin: false }

Or short version:

const raw = {
  username: 'john',
  password: '1234',
  isAdmin: false
};

const filteredShort = Object.fromEntries(
  Object.entries(raw).filter(([key]) => key !== 'password')
);

console.log(filteredShort); // { username: 'john', isAdmin: false }

πŸ”Ž 4. Object.values() β€” Get All Values

Returns an array of an object's enumerable property values:

πŸ“¦ Use Case: Calculating total from price object

const prices = { apple: 0.99, banana: 1.29, cherry: 2.49 };

// Get an array of the prices: [0.99, 1.29, 2.49]
// Use reduce to sum them all:
// 'sum' starts at 0, and we add each 'price' in the array
const total = Object.values(prices).reduce((sum, price) => sum + price, 0);

// Format the result to 2 decimal places and log it
console.log(`Total: $${total.toFixed(2)}`); // Total: $4.77

πŸ” 5. Object.keys() β€” Get All Keys

Returns an array of all enumerable property names:

πŸ“¦ Use Case: Auto-generating form inputs

const formFields = { name: '', email: '', password: '' };

// Get an array of the keys: ['name', 'email', 'password']
// Loop through each field and log a message
Object.keys(formFields).forEach(field => {
  console.log(`Render input for: ${field}`);
  // This could be where you'd render an <input> for each field
});

βœ… Conclusion

Static methods like Array.from, Object.entries, and others can clean up your code and give you expressive tools to work with complex data structures. The better you know them, the more readable and elegant your JavaScript will become. These real-life examples show that even small methods can bring big clarity. Want to go deeper? Try combining them in clever ways β€” and let me know your favorite use case!

0
Subscribe to my newsletter

Read articles from Viktor Sivulskiy directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Viktor Sivulskiy
Viktor Sivulskiy

I build tools, write code, and try not to touch things that already work. Mostly JavaScript, or something dangerously close to it.