Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

48
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda