JavaScript Function Syntax and Dynamic Code Execution

Day 25 of me reading random and basic but important coding facts.... Today I read about new Function syntax. We usually define functions with function() {} or () => {}, but I didn't know that we can create them from strings tooo.. The syntax let func = new Function(arg1, arg2, bodyString) allows us to turn any string of code into a callable function at runtime. It's popular use cases are ..... 1. Dynamic Code Execution: When you receive executable code from a server (e.g., a complex formula or logic block) as a string. 2. Templating Engines: Many complex web frameworks use it internally to compile templates into functions dynamically. Interesting part is it's internal implementation....... Normally, a function remembers its birthplace via the special [[Environment]] property, which links to the Lexical Environment where it was created. This allows standard functions to access outer variables (Closures). However, functions created with new Function have their [[Environment]] reference set to the Global Lexical Environment, not the local one. so, it cannot access outer local variables. It can only see global variables and its own arguments. But this is actually a feature to prevent conflicts with minifiers. Since minifiers rename local variables (e.g., let userName becomes let a), a function created from a string wouldn't know the new variable names. By forcing it to use the global scope, it avoids this crash. Few Performance related Challenges are...... * Runtime Parsing: Unlike regular functions, the code string is parsed every time the constructor is called. This adds overhead. * Optimization: JS engines have a harder time optimizing these functions compared to static code, potentially leading to slower execution. * Debugging: Debugging generated strings is significantly harder than standard code. * Maintenance: It breaks the readability and standard scoping rules of the language. Keep Learning!!!!! #javascript #webdevelopment #coding #softwareengineering #frontendDev

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories