/ Gists / 4 ways to dynamically execute JavaScript code on the front end
On gists

4 ways to dynamically execute JavaScript code on the front end

JavaScript

HOW.JS Raw #

// https://medium.com/@bestowensss/4-ways-to-dynamically-execute-javascript-code-on-the-front-end-01648b4f527a

// 1
/*
Synchronous execution;
The execution context is the current scope .
*/
let a = 1;
function test() {
  let a = 2;
  eval('console.log(a)'); // 2
}
test();


// 2
/*
Synchronous execution;
The execution environment is the global scope .
*/
let a = 1;
function test() {
  let a = 2;
  let fn = new Function('console.log(a)');
  fn(); // 1
}
test();


// 3
// 2
/*
Asynchronous execution;
The execution environment is the global scope .
*/
let a = 1;
function test() {
  let a = 2;
  setTimeout('console.log(a)', 1000); // 1
}
test();


//4 
/*
Synchronous execution;
The execution environment is the global scope .
*/
var a = 1;
let script = document.createElement('script');
script.textContent = 'console.log(1)';
document.body.appendChild(script); // 1