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

260
Views
Javascript: HackerRank function within a function is not a function

This is one of those job interview tests on HackerRank that I am embarrassed to say I didn't complete within the allotted 20 minutes, and it's driving me nuts. Basically, you're given the following:

function myList() {
    // write code here
}

function main() {
    // You can't edit this function. This is just pseudo, from what I can remember
    const obj = myList();
    if (operation === "add")
        obj.add(item);
    else if (operation === "remove")
        obj.remove(item);
    else
        obj.getList();
    // Some more stuff here
}

So my first train of thought was to write the following inside myList():

let objList = [];
function add(item) {
    objList.add(item)
}
// etc., etc.
return {add, remove, getList};

Needless to say, the above didn't work, with the error: obj.add is not a function, in the main function.

I tried experimenting with this and the returns (only returning add, with or without {}), but didn't really get anywhere. What could I have done to get this working?

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

0

For obj, inside myList() you could have run a closure, that is a self invoking function returning, in this case, an object with your k:v exports, but with private access to the context of the now expired anonymous caller. With "const add = function" etc statements you can define values for your exports, while the objList goes in the private context.

about 4 years ago · Juan Pablo Isaza Report

0

As the answer from Attersson already suggested, you could use a closure inside the myList function. This would allow to only expose the three methods add, remove and getList while the original list cannot be accessed. Here is an example:

function myList() {
  return (() => {
    const obj = {itemList: []} 
    const add = (item) => obj.itemList.push(item)
    const remove = (item) => obj.itemList = obj.itemList.filter(i => i !== item)
    const getList = () => obj.itemList
    return {add, remove, getList}
  })()
}
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!