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

47
Views
Why is this tiny library function returning undefined?

I want to build a tiny JavaScript library that can be used like this:

library('input').method()

(async () => {
  // const nlp = function (text = '', lexicon) {
  const library = function (text) {
    const options = {}

    options.addQuotes = function (text) {
      return `"${text}"`
    }

    return options
  }

  const result= library('test').addQuotes()
  console.log(result)
})()

library.addQuotes is suppose to surround text around double quotes.

So I thought result would be:

"test"

Instead I got:

"undefined" 

Why is this, and how to fix it?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

By having an extra parameter you are creating an inner variable text (scoped inside the addQuotes function). You do not pass any value and JS has not problem with that, only it will be undefined. When JS looks for text variable, it finds this undefined value and returns that.

Remove that extra argument name and you are good.

(async () => {
  // const nlp = function (text = '', lexicon) {
  const library = function (text) {
    const options = {}

    options.addQuotes = function () {
      return `"${text}"`
    }

    return options
  }

  const result= library('test').addQuotes()
  console.log(result)
})()

about 4 years ago · Juan Pablo Isaza Report

0

The text parameter in the addQuotes function is overshadowing the text variable in the outer scope.

Remove the parameter from the addQuotes function:

(async () => {
  // const nlp = function (text = '', lexicon) {
  const library = function (text) {
    const options = {}

    options.addQuotes = function () {
      return `"${text}"`
    }

    return options
  }

  const result= library('test').addQuotes()
  console.log(result)
})()

about 4 years ago · Juan Pablo Isaza 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!