Function Constructor

// let x = 60 (doesn't work)

var x = 60
var mike = new Function('return x;')
console.log(mike())

This code runs just fine with the var keyword declaring and initializing x, but throws an error when I use let
Can someone please explain why?

Hi @owolagbadavid

I just pasted your code into CodePen and it works with var, let and const.
Can you post the exact code that throws the error and the error message you get?

Michael

1 Like
let x = 60; 
    var mike = new Function('return x;'); 
    console.log(mike()) 

OK I didn’t try it on codepen, but I tried it on JsBin and I got this error
"ReferenceError: x is not defined at eval (eval at <anonymous> (:1:29), <anonymous>:3:1) at null.js:1:93..."

I also tried it on the Try it section on MDN Web docs references where I read about Function constructors and I got
"Error: x is not defined"

Just to let you know:
I’m still experimenting around with this problem. It’s a rather unusual way to create functions (and not recommended), but I’m intrigued by the different behavior base on where you execute it.
This is the code I’m using. These are the four combinations of var/let for the variable and the function.

var f1 = 10;
var func1 = new Function('return f1;');
console.log(`func1: ${func1()}`);

let f2 = 20;
var func2 = new Function('return f2;');
console.log(`func2: ${func2()}`);

var f3 = 30;
let func3 = new Function('return f3;');
console.log(`func3: ${func3()}`);

let f4 = 40;
let func4 = new Function('return f4;');
console.log(`func4: ${func4()}`);

My results so far:

  • Local file: All worked
  • CodePen: All worked
  • JSFiddle: All worked
  • JSBin: f1 and f3 work (where the variable has var)
  • Interactive example on Function() constructor: None works

I think it has something to do with the scope where those are created/executed. A tricky little problem you have discovered. :wink:

Michael

2 Likes

I know right
I was just reading functions on Javascript guide and decided to experiment

Hey everyone, there does indeed seem to be a bug with the interactive examples editor on MDN Web Docs pages. I will open an issue for this.

@owolagbadavid as @mikoMK mentioned, if you run the code in another online editor such as Codepen you will see that the code executes successfully. My apologies for the confusion caused.


Schalk
Staff Community Manager - MDN Web Docs

3 Likes

I have files the following issue: https://github.com/mdn/bob/issues/808

3 Likes