Reflect in JavaScript with Example Codes

In this article, we will discuss the concept of reflect in JavaScript and provide you with clear examples to understand its potential.

What is Reflection in JavaScript?

Reflection in JavaScript is the understanding of a program to check and manipulate its own structure and action.

It enables developers to access and interact with an object’s properties, methods, and metadata programmatically.

This is specifically useful when you need to create generic functions or change existing ones without modifying the source code directly.

Reflective programming can be related to taking a look behind the screen of your code to make on-the-fly adjustments.

The Power of Reflection

Reflection provides plenty of advantages that can approximately improve your coding experience and application development process:

  • Dynamic Analysis
    • Reflection allows dynamic analysis of objects during runtime. This means you can observe the properties and methods of an object without knowing its name beforehand.
  • Code Generics
    • By using reflection, you can create generic functions that can engage on a wide range of object types, saving you time and effort in writing repetitive code.
  • Debugging and Testing
    • Reflection helps in debugging and testing by providing insights into the structure of objects. You can achieve a deeper understanding of how your code is functioning and identify potential issues.
  • Metaprogramming
    • Metaprogramming involves writing code that manipulates other code. A reflection is a powerful tool for metaprogramming, enabling you to constantly create classes, methods, and properties.
  • Extensibility
    • Reflection improves extensibility by allowing you to add new methods and properties to existing objects during runtime, thereby adapting your application to changing requirements.

Exploring Reflection with Code Examples

Accessing Object Properties

Using reflection, you can access an object’s properties and values constantly.

Let’s take a look at the following example:

const employee = { name: "Jude", age: 21 };
const result = "age";

console.log(employee[result]);

Output:

21

Modifying Object Properties

Reflection also allows you to change the object’s properties dynamically.

Here’s an example code of how you can use it:

const fruits = { name: "Mango", type: "Sweet" };
const result = "type";

fruits[result] = "Bitter";
console.log(fruits.type);

Output:

Bitter

Invoking Methods

You can use reflection to invoke methods constantly.

Let’s see this example code:

class addition {
  sum(x, y) {
    return x + y;
  }
}

const res = new addition();
const output = "sum";

console.log(res[output](8, 9));

Output:

17

Adding New Methods

Reflection allows you to add new methods to an object dynamically.

For example:

class bird {
  twit() {
    console.log("twit twit!");
  }
}

const lovebirds = new bird();
lovebirds["chip"] = function () {
  console.log("chirping!");
};

lovebirds.chip();

Examining Object Metadata

Reflection enables you to check an object’s metadata, such as constructor information.

Here’s an example code:

class BookSample {
  constructorSample(bookTitle, bookAuthor) {
    this.bookTitle = bookTitle;
    this.bookAuthor = bookAuthor;
  }
}

const result = new BookSample("The Great President in Philippines", "J. Juan Delacruz");
console.log(result.constructorSample.name);

FAQs

How can reflection benefit developers?

Reflection allows dynamic analysis, code generics, debugging, metaprogramming, and extensibility, improving the coding process.

Can I modify object properties using reflection?

Yes, reflection enables you to dynamically access and change object properties, even those whose names you don’t know beforehand.

Is reflection limited to objects?

No, reflection extends to methods as well. You can invoke methods dynamically using reflection.

How does reflection help in metaprogramming?

Reflection allows you to create classes, methods, and properties dynamically, facilitating metaprogramming.

Conclusion

Reflecting in JavaScript opens doors to a new field of possibilities, allowing you to interact with your code dynamically and make real-time changes.

By utilizing the power of reflection, you can create more functional, adaptable, and efficient applications.

Whether you’re planning to create generic functions, extend object functionality, or inquire into the depths of metaprogramming, reflection is an indispensable tool in your JavaScript programming.

Additional Resources

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.
Adones Evangelista

Programmer & Technical Writer at PIES IT Solution

Adones Evangelista is a programmer and writer at PIES IT Solution, author of over 900 tutorials and error-fix guides at itsourcecode.com. Specializes in JavaScript, Django, Laravel, and Python error debugging covering ValueError, TypeError, AttributeError, ModuleNotFoundError, and RuntimeError, plus C/C++ and PHP capstone projects for BSIT students.

Expertise: JavaScript · Python · Django · Laravel · Error Debugging · C/C++  · View all posts by Adones Evangelista →

Leave a Comment