Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 30

Implementing 'get' Traps for Negative Indexing and Default Values

This lesson is built with resources from javascript.info and calmops.com.

Hello! Welcome to our next lesson on metaprogramming with Proxies.

In the previous lesson, we dove deep into the set trap, building a powerful observable object pattern that is fundamental to modern reactive UI frameworks. We saw how intercepting property writes allows us to trigger notifications and create dynamic, data-driven applications.

Today, we'll shift our focus to the other side of the coin: the get trap. Our learning outcome is to implement negative array indexing or default property values using a get trap. By intercepting property reads, we can create more flexible, forgiving, and expressive data structures. These patterns are a form of "operator overloading," a concept you might be familiar with from languages like Python or C++, but implemented here through JavaScript's metaprogramming capabilities.

The get Trap: A Quick Refresher

As a brief reminder, the get trap intercepts the action of reading a property from an object. Its handler method has the following signature:

get(target, property, receiver)

  • target: The original object passed to the Proxy constructor.
  • property: The name (a string or Symbol) of the property being accessed.
  • receiver: The proxy itself, or another object that inherits from the proxy. When using Reflect.get, this is used to preserve the correct this context for getters.

With this in mind, let's explore our first practical application.


1. Providing Default Property Values

A common feature of JavaScript is that accessing a non-existent property on an object yields undefined.

const user = { name: "Alice" };
console.log(user.age); // undefined

const data = [10, 20, 30];
console.log(data[5]); // undefined

While predictable, this often forces us to write defensive code with checks like if (key in object) or user.age || 0 to avoid undefined propagating through our application and causing potential errors. A Proxy allows us to build this defensive logic directly into the object itself.

Let's see how to implement this.

Proxy and Reflect

The article "Proxy and Reflect" from javascript.info provides two excellent examples of using the get trap to provide default values. This reading will demonstrate the core pattern for both array-like and dictionary-like objects.

Please read the section titled "Default value with β€œget” trap". Pay close attention to the two distinct use cases presented: one for a numeric array and another for a string-based dictionary.

As the article demonstrates, the get trap logic is straightforward:

  1. Check if the requested property exists on the target object (if (prop in target)).
  2. If it exists, return the actual value using target[prop].
  3. If it does not exist, return a custom default value instead of undefined.

Let's review the two powerful examples from the reading:

Example 1: A "safe" array that returns 0 for non-existent indices.

let numbers = [0, 1, 2];

numbers = new Proxy(numbers, {
  get(target, prop) {
    if (prop in target) {
      return target[prop];
    } else {
      // It's a non-existent property.
      // Let's check if it's a numeric property access that is out of bounds.
      // If we try `numbers.length`, `prop` will be "length", so we don't want to return 0.
      // The `Number.isInteger(Number(prop))` check ensures we only default for numeric indices.
      if (Number.isInteger(Number(prop))) {
        return 0; 
      }
      // For other properties like 'length', fall back to the default behavior.
      return Reflect.get(...arguments);
    }
  }
});

console.log(numbers[1]);   // 1
console.log(numbers[123]); // 0 (instead of undefined)
console.log(numbers.length); // 3

Note: I've slightly enhanced the example from the article to correctly handle non-numeric properties like .length.

Example 2: A dictionary that returns the key if a translation is missing.

This is a clever way to ensure your UI never shows undefined, but rather the original term you tried to translate.

let dictionary = {
  'Hello': 'Hola',
  'Bye': 'AdiΓ³s'
};

dictionary = new Proxy(dictionary, {
  get(target, phrase) {
    if (phrase in target) {
      return target[phrase];
    } else {
      return phrase; // Return the key itself as the default
    }
  }
});

console.log(dictionary['Hello']);          // Hola
console.log(dictionary['Welcome']);      // Welcome (no longer undefined)

The resource Proxy Objects: Interception and Traps in JavaScript shows an even more concise way to write this using the nullish coalescing operator (??), which you should be familiar with. This version returns a default for any property that is null or undefined.

const config = { host: 'localhost' };

const proxyConfig = new Proxy(config, {
  get(target, prop) {
    // If target[prop] is null or undefined, return the default string.
    return target[prop] ?? `Default value for ${String(prop)}`;
  }
});

console.log(proxyConfig.host); // localhost
console.log(proxyConfig.port); // Default value for port

2. Implementing Negative Array Indexing

If you've used Python, you know how convenient it is to access array elements from the end using negative indices (arr[-1] for the last element, arr[-2] for the second-to-last, etc.). JavaScript does not support this syntax natively. Accessing arr[-1] is treated as a lookup for the property key "-1", which doesn't exist on a standard array.

However, we can implement this elegant feature ourselves with a get trap!

First, let's visualize what we want to achieve.

Array Indexing: Positive and Negative
This image illustrates the desired behavior. An element can be accessed from the start with a positive index (e.g., `[0]` is the apple) or from the end with a negative index (e.g., `[-1]` is the papaya).

The logic is simple: an index of -N should map to an index of array.length - N. Let's create a proxy to implement this.

Proxy and Reflect

We'll turn again to javascript.info, which has a concise task and solution for this exact problem. This will serve as our guide for implementation.

In the "Tasks" section, find the problem titled "Accessing array[-1]" and study its proposed solution.

Let's break down the solution provided in the article.

let array = [1, 2, 3];

array = new Proxy(array, {
  get(target, prop, receiver) {
    // 1. The property 'prop' comes in as a string, e.g., "-1".
    // We convert it to a number to check if it's negative.
    const index = Number(prop);

    // 2. If the index is negative...
    if (index < 0) {
      // 3. ...we calculate the corresponding positive index.
      // e.g., for prop "-1", new prop is 3 + (-1) = 2.
      // e.g., for prop "-2", new prop is 3 + (-2) = 1.
      prop = String(target.length + index);
    }
    
    // 4. Finally, use Reflect.get with the (potentially modified) prop.
    return Reflect.get(target, prop, receiver);
  }
});

console.log(array[-1]); // 3 (Correctly accesses array[2])
console.log(array[-2]); // 2 (Correctly accesses array[1])
console.log(array[0]);  // 1 (Positive indices still work)

A crucial detail is that property keys, even for arrays, are handled as strings within the trap. That's why we must convert prop to a number for the numeric comparison. The solution in the resource uses a unary plus (+prop) for a concise conversion, while Number(prop) is more explicit. Both are valid. After calculating the new index, we pass it to Reflect.get.

Test your understanding!

Let's combine these two patterns. Create a proxy for an array that:

  1. Supports negative indexing.
  2. Returns the string 'out of bounds' if an index (positive or negative) does not exist in the array.

For example, with let arr = [10, 20, 30]:

  • proxy[1] should be 20.
  • proxy[-1] should be 30.
  • proxy[5] should be 'out of bounds'.
  • proxy[-5] should be 'out of bounds'.
Show answer

Here's one way to implement the get trap to satisfy both requirements:

function createSmartArray(arr) {
  return new Proxy(arr, {
    get(target, prop, receiver) {
      let index = Number(prop);

      // We only want to apply our logic to integer property names.
      // This prevents us from messing with properties like 'length'.
      if (!Number.isInteger(index)) {
        return Reflect.get(target, prop, receiver);
      }

      // Handle negative indexing
      if (index < 0) {
        index = target.length + index;
      }

      // Check for out-of-bounds after normalization.
      // The `prop` we check must exist on the target.
      // `String(index)` ensures we are checking for a valid property key.
      if (String(index) in target) {
        return Reflect.get(target, String(index), receiver);
      } else {
        return 'out of bounds';
      }
    }
  });
}

const arr = createSmartArray([10, 20, 30]);

console.log(`arr[1]: ${arr[1]}`);       // arr[1]: 20
console.log(`arr[-1]: ${arr[-1]}`);      // arr[-1]: 30
console.log(`arr[5]: ${arr[5]}`);       // arr[5]: out of bounds
console.log(`arr[-5]: ${arr[-5]}`);     // arr[-5]: out of bounds
console.log(`arr.length: ${arr.length}`); // arr.length: 3

This solution first normalizes any negative index to its positive equivalent and then checks if the resulting index is valid before either returning the value or the 'out of bounds' default.


Conclusion

In this lesson, we've explored the creative power of the Proxy get trap. By intercepting property read operations, we can fundamentally alter how an object behaves, making it more robust and developer-friendly.

Key Takeaways:

  • The get trap allows you to define custom logic for property access.
  • You can implement default values to prevent undefined from appearing when accessing non-existent properties, making your objects safer.
  • You can add features from other programming paradigms, like negative array indexing, to make your data structures more expressive and convenient.
  • It's critical to remember that property keys are passed as strings (or Symbols) to the trap, and you often need to convert them to numbers for calculations.

Next Up

We've now seen how to control property reading (get) and writing (set). In our next lesson, we will explore another dimension of metaprogramming: security and lifecycle control. You will learn how to create a revocable proxy for temporary access control that can be turned off, a useful pattern for managing resources and permissions.