Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
Function class javascript not finding variable

I have two javascript docs on my project. js (script.js) #1:

let func = new Function('return thisvar')
console.log(func())

js (script1.js) #2:

let thisvar = 'hello'

I get an error: ERROR:{@script.js line 4: cannot find variable 'thisvar'} I have tried using var instead of let or even window.thisvar What am I doing wrong?

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

When you run func() in your first script, you haven't yet defined thisvar.

Just move the function call to your second script after you define the variable.

let func = new Function('return thisvar')
let thisvar = 'hello'
console.log(func())
about 4 years ago · Santiago Gelvez Report

0

Readable "hello world" example (The console.log(func(your_error) return the same error - cannot find variable (You didn't declare the variable).

<span>example</span>
<script>
      let func = new Function("arg1", "return arg1")

      let thisvar = 'hello'; /* missing in your code */
      console.log(func(thisvar))
      // expected output: hello
      console.log(func("world"))
      // expected output: world
      console.log(func(your_error))
      // expected output: "Uncaught ReferenceError: your_error is not defined"
 </script>

In general it is more efficient to use function expression or function statement.

Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!