How to Call Function by Name in JavaScript

Abid Ullah Feb 02, 2024
How to Call Function by Name in JavaScript

In JavaScript, sometimes it’s convenient to store function names in the string because we can use those strings to call the actual functions.

We can call a JavaScript function whose name is stored in a string variable using the eval() method but is an old method.

We will use the window object method to call a function.

Use the window object Method to Call Function by Its Name in JavaScript

We created a function named changeColor(). We stored that function in the string variable.

Now, we want to call that function we stored in the string. We need to click on the button.

In the string function, we pass parameter red. So, when we click on the button, the color of the text You called the Function changes to red.

<!DOCTYPE html>
		To call a function
	<h1 style="color: Red">
		Call function by name
       To call a function by its name stored in string variable in JavaScript.
      Click on the button to call the function in the string.
	<p class="example">
		You called the function.
	<button onclick="evaluateFunction()">
		Click Here
	<script type="text/javascript">
		function changeColor(color) {
				= `color: ${color}`;
		function evaluateFunction() {
			stringFunction = "changeColor";
			param = 'red';

In this way, we call the string function by using the window[stringFunction](param) method.


The result before clicking the button

The result after clicking the button

Author: Abid Ullah
Abid Ullah avatar Abid Ullah avatar

My name is Abid Ullah, and I am a software engineer. I love writing articles on programming, and my favorite topics are Python, PHP, JavaScript, and Linux. I tend to provide solutions to people in programming problems through my articles. I believe that I can bring a lot to you with my skills, experience, and qualification in technical writing.


Related Article - JavaScript Function