bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/JavaScript/Objects, Classes, and Advanced Patterns
JavaScript•Objects, Classes, and Advanced Patterns

JavaScript Reflect

The Reflect Object

Reflect is a object with methods for low-level operations on JavaScript objects.

With the Reflect object you can get, set, delete, and check object properties in a consistent way.

Reflect was added to JavaScript in ES6 (2015).

Yor Toolbox

Reflect is a toolbox for working with objects in a safe and consistent way.

Before Reflect

Before Reflect, object operations were scattered:

  • Using operators like in and delete
  • Using methods like Object.defineProperty
  • Using language mechanisms like [[ Get ]] and [[ Set ]]

After Reflect

Reflect brings all object operations into clean methods :

  • Reflect methods unifies object operations
  • Reflect methods are more predictable than operators (in/delete)
  • Reflect methods provides standard return values instead of errors
  • Reflect methods are cleaner and safer for meta-programming
  • Reflect methods are tailored for the Proxy object

Why Reflect

Reflect is safe and flexible, especially when used inside a Proxy.

Reflect.has()

The Reflect.has() method checks if an object has a specific property.

The Reflect.has() method is similar to the in operator.

Check if Property Exists

// Create an Object
const person = {name: "John", lastname: "Doe"};
let answer = Reflect.has(person, "name");
Syntax
Reflect.has(obj, prop)
Properties
obj - the target object prop - the property to check
Returns
true - if true false if false
Exeptions
TypeError thrown if obj is not an object

Reflect.deleteProperty()

The Reflect.deleteProperty() method deletes a property from an object.

The Reflect.deleteProperty() method is similar to the delete operator.

Deleting a Property

// Create an Object
const person = {name: "John", lastname: "Doe"};
Reflect.deleteProperty(person, "name");
Syntax
Reflect.deleteProperty(obj, prop)
Properties
obj - the target object prop - the property to delete
Returns
true - if true false if false
Exeptions
TypeError thrown if obj is not an object

Reflect.get()

The Reflect.get() method retrieves the value of a property:

Example

// Create an Object
const user = {name: "Jan", age: 40};
let age = Reflect.get(user, "age");
Syntax
Reflect.get(obj, prop [,receiver])
Properties
obj - the target object prop - the property to get receiver - the this value if it is a getter
Returns
The value of the property
Exeptions
TypeError thrown if obj is not an object

Reflect.set()

The Reflect.set() method sets the value of a property:

Example

// Create an Object
const user = {name: "Jan", age: 40};
Reflect.set(user, "age", 41);
let age = Reflect.set(user, "age");
Syntax
Reflect.set(obj, prop, value [,receiver])
Properties
obj - the target object prop - the property to set value - the value to set receiver - the this value if it is a setter
Returns
true - for success false - if not
Exeptions
TypeError thrown if obj is not an object

Reflect.apply()

The Reflect.apply() method calls a function with a this value and an argument array.

Example

function greet(message) {
  return message + ", " + this.name;
}
const person = {name: "Jan"};
let msg =  Reflect.apply(greet, person, ["Hello"]);
Syntax
Reflect.apply(function, this, arguments)
Properties
function - target object (function) this - the value of this calling the target arguments - array-like object of function arguments
Returns
The return value from the function
Exeptions
TypeError thrown if function is not a function or arguments is not an object

Reflect.apply() is preferred when:

  • You are doing meta-programming
  • You are inside a Proxy handler
  • You want consistent behaviors (no silent errors)
  • You want to mirror JavaScript's internal operations

Reflect.construct()

The Reflect.construct() method acts like the new operator, creating a new instance of target with the provided arguments. newTarget allows for custom new.target values for subclassing.

Example

// Create a new Array
const colors = Reflect.construct(Array, ["red", "green", "blue"]);
Syntax
Reflect.construct(obj, args [, newTarget])
Properties
obj - the constructor object args - an array-like object of arguments to be passed newTarget - the constructor
Returns
A new object constructed from the argumets list
Exeptions
TypeError thrown if obj or newTarget is not a constructor, or if args is not an object

Reflect.defineProperty()

The Reflect.defineProperty() defines or modifies a property.

Example

// Create an Object
const user = {};
// Add a Property Reflect.defineProperty(user, "id", { value: 123, writable: false
});
Syntax
Reflect.defineProperty(obj, prop, attributes)
Properties
obj - the target object prop - the property to define attributes - an array-like object of the property attributes
Returns
Exeptions
TypeError thrown if obj is not an object or attributes is not an object

Reflect.defineProperty() in Proxy

Reflect.defineProperty() must be used in Proxy

If used in a Proxy, the defineProperty trap must return true or false .

  • Object.defineProperty() returns the target object Reflect.defineProperty() returns true or false

Reflect.ownKeys()

The Reflect.ownKeys(obj) method returns an array of an object's own property keys (string and Symbol based), similar to combining Object.getOwnPropertyNames() and Object.getOwnPropertySymbols().

Example

const sym = Symbol("secret");
const obj = { a: 1, [sym]: 2 };
let keys = Reflect.ownKeys(obj);
Syntax
Reflect.ownKeys(obj)
Properties
obj - the target object
Returns
An Array of the object's own property keys, including strings and symbols
Exeptions
TypeError thrown if obj is not an object

Why Using Reflect?

Reflect.ownKeys() also returns symbols.

Object.keys() does not.

Reflect.isExtensible()

The Reflect.isExtensible() method Checks if an object is extensible (can have properties added), similar to Object.isExtensible().

Example

let answer = Reflect.isExtensible(obj);

The same as using Object.isExtensible() :

let answer = Object.isExtensible(obj);
Syntax
Reflect.isExtensible(obj)
Properties
obj - the target object
Returns
true - is extensible false - is not
Exeptions
TypeError thrown if obj is not an object

Why Using Reflect?

Object.isExtensible() is a user method - not part of the internal trap machinery.

Reflect.isExtensible() maps directly to the internal [[IsExtensible]] method.

Reflect.isExtensible() correctly handles primitive targets, which matters when proxied.

Reflect.isExtensible(1); // TypeError
Object.isExtensible(1); // false (does not throw)

When to Use Reflect?

CaseUseWhy
Getting / setting valuesYesIf you need consistent return values
Creating new objectsYesReflect.construct() works with Proxy
Calling a function with contextYesReflect.apply() is cleaner than func.apply()
Meta programmingYesDesigned for low-level tasks
Simple object workNoUse normal JS syntax

Reflect with Proxy (Very Common)

Proxy lets you intercept operations on objects:

Example

// Create an Object
const user = { name: "Jan", age: 40 };
// Create a Proxy
const proxy = new Proxy(user, {
  set(target, property, value) {
    log(property + ": " + value);
    // safe forwarding
    return Reflect.set(target, property, value);
  }
});

Reflect can provide safe and unified forwarding calls.

Reflect ensures that a Proxy behaves like a normal object.

Proxy and Reflect

Proxy was designed first. Reflect was designed second.

Proxy was designed to allow JavaScript developers to:

  • Intercept property access
  • Override default property behaviors
  • Validate data
  • Wrap functions
  • Virtualize objects
  • Create reactive objects

The idea of Proxy was developed during the ES6 (2015) design phase before Reflect existed.

However, Proxy had a big issue:

"How to forward an intercepted operations safely?"

JavaScript had no functional equivalents of many operations.

Because of this limitation, Reflect was invented.

JavaScript Reflect History

Reflect was introduced because Proxy needed it.

Before Reflect

  • delete, in, new were operators
  • some operations threw errors
  • object operations returned inconsistent values
  • no generic version of property access existed
  • no way to forward constructor calls

This made Proxy impossible to implement safely.

So ES6 (2015) introduced Reflect to

  • provide clean, function-based versions of every internal operation
  • return predictable booleans instead of objects
  • avoid unnecessary errors
  • mirror the JavaScript engine's behavior
  • give Proxy traps a reliable forward-path

Learn More

JavaScript Metaprogramming JavaScript Proxy Tutorial JavaScript Meta Reference

JavaScript Proxy Tutorial JavaScript Meta Reference

JavaScript Meta Reference

Previous

JavaScript Meta Programming

Next

JavaScript Proxy

This chapter

Overview
123

Lessons

539m

Read time

1. JavaScript Objects2. JavaScript Temporal Tutorial3. JavaScript Loops4. JavaScript Advanced Functions5. JavaScript Objects6. JavaScript Temporal Intro7. JavaScript Iterables8. JavaScript Function Definitions9. JavaScript Object Properties10. JavaScript Temporal vs Date11. JavaScript Iterators12. JavaScript Callbacks13. JavaScript Object Methods14. JavaScript Temporal Duration15. JavaScript Generators16. The JavaScript this Keyword17. JavaScript this Keyword18. JavaScript Temporal Instant19. JavaScript Function call()20. JavaScript Display Objects21. JavaScript PlainDateTime22. JavaScript Function apply()23. JavaScript Object Constructors24. JavaScript Temporal PlainDate25. JavaScript Function bind()26. JavaScript PlainYearMonth27. Self-Invoking Functions28. JavaScript PlainMonthDay29. JavaScript Closures30. JavaScript Temporal PlainTime31. JavaScript Objects - Advanced32. JavaScript ZonedDateTime33. JavaScript Object Definitions34. JavaScript Temporal Now35. this in JavaScript Objects36. JS Temporal Arithmetic37. JavaScript Object Iterations38. JS Temporal Differences39. JavaScript Object Accessors40. JS Temporal Compare41. JavaScript Object Management42. JavaScript Temporal Conversion43. JavaScript Object Protection44. Temporal Display Formats45. JavaScript Object Prototypes46. JavaScript Temporal Mistakes47. JavaScript Classes48. Migrate from Date to Temporal49. JavaScript Class Inheritance50. Temporal Standards51. JavaScript Static Methods52. Asynchronous JavaScript53. Asynchronous Programming54. JavaScript Timeouts55. JavaScript Callbacks56. JavaScript Promises57. JavaScript async and await58. JavaScript fetch API59. Debugging Async JavaScript60. JavaScript Modules61. JavaScript Modules Export62. JavaScript Modules Import63. JS Module Namespace64. JavaScript Dynamic Modules65. JavaScript Meta Programming66. JavaScript Reflect67. JavaScript Proxy68. JavaScript Typed Arrays69. Typed Array Methods70. JavaScript ArrayBuffer71. JavaScript DataView72. JavaScript Atomics73. JavaScript HTML DOM Navigation74. JavaScript HTML DOM Elements (Nodes)75. JavaScript HTML DOM Collections76. JavaScript HTML DOM Node Lists77. JavaScript Window - The Browser Object Model78. JavaScript Window Screen79. JavaScript Window Location80. JavaScript Window History81. JavaScript Window Navigator82. JavaScript Popup Boxes83. JavaScript Timing Events84. JavaScript Cookies85. Web APIs - Introduction86. JavaScript Fetch API87. Web Geolocation API88. Web History API89. Pointer Events API90. Web Storage API91. JavaScript Validation API92. Web Workers API93. AJAX Introduction94. AJAX - The XMLHttpRequest Object95. AJAX - XMLHttpRequest96. AJAX - Server Response97. AJAX XML Example98. AJAX PHP Example99. AJAX ASP Example100. AJAX Database Example101. XML Applications102. JavaScript JSON103. JSON Syntax104. JSON vs XML105. JSON Data Types106. JSON.parse()107. JSON.stringify()108. JSON Object Literals109. JSON Array Literals110. JSON PHP111. JSON HTML112. JSONP113. JavaScript / jQuery DOM Selectors114. JavaScript / jQuery HTML Elements115. JavaScript / jQuery CSS Styles116. JavaScript / jQuery HTML DOM117. JavaScript Graphics118. HTML Canvas119. Plotly.js120. Chart.js121. Google Chart122. D3.js123. JavaScript Interview Preparation

On this page

The Reflect ObjectYor ToolboxBefore ReflectAfter ReflectWhy ReflectReflect.has()Reflect.deleteProperty()Reflect.get()Reflect.set()Reflect.apply()Reflect.construct()Reflect.defineProperty()Reflect.defineProperty() in ProxyReflect.ownKeys()Why Using Reflect?Reflect.isExtensible()Why Using Reflect?When to Use Reflect?Reflect with Proxy (Very Common)Proxy and ReflectJavaScript Reflect HistoryLearn More