<!DOCTYPE html>
<
html
>
<
body
>
<
h1
style
=
"color:green;"
>
GeeksforGeeks
</
h1
>
<
h3
>
This example shows how we can transform string
into a function in javascript
</
h3
>
<
h3
>1. Use of eval()</
h3
>
<
p
>
When string "var func = function(){ return a+b }" is
passed in eval() and func() is called, The output is :
<
span
id
=
"result"
></
span
>
</
p
>
<
h3
>2. Use of Function constructor</
h3
>
<
p
>
When strings "x=5", "y=20", "return x*y" is
passed in Function constructor and fn() is called,
The output is :
<
span
id
=
"func1"
></
span
>
</
p
>
<
p
>
When strings "x=5", "y=20", "return x*y" is
passed in Function constructor and fn(4,10) is called,
The output is :
<
span
id
=
"func2"
></
span
>
</
p
>
<
script
>
// use of eval()
var a = 100;
var b = 200;
eval("var func = function(){ return a+b }");
document.getElementById("result").innerHTML = func();
// Use of Function Constructor
const fn = new Function("x=5", "y=20", "return x*y");
document.getElementById("func1").innerHTML = fn();
document.getElementById("func2").innerHTML = fn(4, 10);
</
script
>
</
body
>
</
html
>