+ 1

How function constructor works in the below scenario ?

let a=10; let b=20; function sum(){console.log(a+b)}; sum() In the above scenario I am getting the output as 3. But, let a=10; let b=20; let sum=new Function("console.log(a+b)"); sum() I am getting an error saying a is not defined. Why ?

6th Jan 2023, 6:44 AM
Levi
Levi - avatar
3 Answers
+ 3
Levi may be you are trying both in same code and getting 'a' already defined..? Try this : let a=10; let b=20; function sum(){ console.log(a+b) }; sum() let a2=10; let b2=20; let sum2=new Function("console.log(a2+b2)"); sum2()
6th Jan 2023, 7:54 AM
Jayakrishna 🇼🇳
+ 1
Recheck once. It's working fine for me..
6th Jan 2023, 7:37 AM
Jayakrishna 🇼🇳
+ 1
Jayakrishna🇼🇳 Could u spot of if there is any error in my code. I tried but not getting the output
6th Jan 2023, 7:49 AM
Levi
Levi - avatar