JavaScript eval function can not perform operation on two numbers

55 views Asked by At
alert('The result is ${eval('${num1} ${operator} ${num2}')}'); 

eval() function used to perform operation on two numbers (num1 and num2 are numbers and operator is "+ , - , * , /") but I got problem in the code. is there any mistake in my code?

1

There are 1 answers

0
Joshua George On

Try:

alert(`The result is ${eval(`${num1} ${operator} ${num2}`)}`); 

Backticks instead of single quotes when using template literals. That said, I would caution against using eval(), as it can execute arbitrary code and might pose security risks if used with user input.