DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Mastering React App Configuration With Webpack
  • Overcoming React Development Hurdles: A Guide for Developers

Trending

  • Integration Isn’t a Task — It’s an Architectural Discipline
  • Why High-Performance AI/ML Is Essential in Modern Cybersecurity
  • A Deep Dive Into Firmware Over the Air for IoT Devices
  • Top Book Picks for Site Reliability Engineers
  1. DZone
  2. Coding
  3. JavaScript
  4. Indexers in JavaScript

Indexers in JavaScript

Indexers are properties that allow you to index instances of a class like arrays by using the [] notation. In this article, learn how to use them in JavaScript.

By 
Alexey Shepelev user avatar
Alexey Shepelev
DZone Core CORE ·
Nov. 21, 21 · Code Snippet
Likes (13)
Comment
Save
Tweet
Share
10.4K Views

Join the DZone community and get the full member experience.

Join For Free

Some modern object-oriented languages have the concept of indexers, which are properties that allow you to index instances of a class just like arrays by using the [] notation. In this article, I would like to show you how to do it in modern JavaScript.

Here’s an example in C#:

C#
 
class Statuses {
  private Dictionary<string, Status> inner = new Dictionary<string, Status>();      
  // implement the indexer     
  public Status this[string name]     {         
    get => inner[name];         
    set => inner[name] = value;     
  } 
}

class Program {     
  static void Main(string[] args) {         
    Statuses s = new Statuses();         
    // refer to the property by using the [] notation         
    s["paid"] = Status.Paid;         
    s["pending"] = Status.Pending;     
  } 
}

Unfortunately, this is not yet possible in modern ES6. However, ES6 has certain mechanisms that allow you to achieve this kind of behavior, although this may look less elegant than in C#.

ES6 has a special proxy class that allows you to intercept calls to the base class. Thus, it becomes possible to handle calls to class fields in a special way.

Let’s repeat our C# example in JS without any tricks.

JavaScript
 
class Statuses {
    #statuses = new Map();
  
    getStatus(key) {
        // there may be complex logic here
        return this.#statuses.get(key);
    }

    setStatus(key, value) {
        //there may be complex logic here
        this.#statuses.set(key, value);
    }

    hasStatus(key) {
        return this.#statuses.has(key);
    }
}

const statuses = new Statuses();
statuses.setStatus('paid', ...);
statuses.setStatus('pending', ...);
statuses.hasStatus('paid'); => true

To add a status to the set, we use setStatus() instead of the [] notation. Let’s fix this by adding some proxy magic. To do this, let’s declare a constructor in the Statuses class and return its proxy wrapper with get and set accessors instead of the Statuses instance.

JavaScript
 
constructor() {
  return new Proxy(this, {
    // overrides getting Statuses.name
    get(target, name) {
      if (name in target) {
        const result = target[name];
        return typeof result === 'function' ? result.bind(target) : result;
      }
      return target.getStatus(name);
    },
    // overrides getting Statuses.name
    set(target, name, value) {
      if (name in target)
        target[name] = value;
      else
        target.setStatus(name, value);
      return true;
    }
  });
}

Here we need to clarify some code for the get accessor:

JavaScript
 
if (name in target) {…}

This fragment is needed to access the class properties and methods (for example, hasStatus), and only if the class has no such property or method, the call will go to getStatus().

JavaScript
 
return typeof result === 'function' ? result.bind(target) : result;

Here, functions are bound to target (i.e. to the Status instance). Otherwise, they will receive this = Proxy inside.

After creating such a constructor, the required syntax becomes available to us:

JavaScript
 
const statuses = new Statuses();

statuses['paid'] = …;
statuses['pending'] = …;

statuses.has('paid'); // true
console.log(statuses['pending']);

Although we have achieved the desired result, the JS code looks more like a crutch and I would recommend using it only if you port the existing code from another language (C#, Delphi) where such properties were actively used.

In turn, I’d be interested to know if there are any other ways to implement the [] notation for invoking a getter/setter without using a proxy.

JavaScript

Opinions expressed by DZone contributors are their own.

Related

  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Mastering React App Configuration With Webpack
  • Overcoming React Development Hurdles: A Guide for Developers

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!