U
U
user_of_toster2020-11-19 06:00:10
JavaScript
user_of_toster, 2020-11-19 06:00:10

Why are const \ let variable not available from the sandbox?

const vm = require('vm');

const context = {};

const code = `
  const v1 = 5;
  const v2 = 8;
  var c1 = 4;
  var c2 = 5;
`;

vm.runInNewContext(code, context);

console.dir(context)


Why are only c1 and c2 available to me from context? I did not wrap v1 and v2 in a separate block like this:
const code = `
  {const v1 = 5;
  const v2 = 8;}
  var c1 = 4;
  var c2 = 5;
`;

That is, in fact, v1 and v2 should have been in the global scope inside the sandbox like v1 and v2, and therefore in the context, no?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey P, 2020-11-19
@user_of_toster

In short, the scope affects!
An article about the differences between let/const/var.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question