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?
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)
})()
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)
})()