Can you conceal a JavaScript function within a specific scope?

Suppose I have two functions a and b that I want to keep within a certain functional scope. Since they share some common code, I decide to extract this shared functionality into another method named support.

support should be accessible by both a and b, but I prefer it not to be visible to other methods within the same scope. Is there a way to achieve this?

// This is the scope; could be global or inside another function

function a() {
  let res = support()
  res.name = "a"
  return res
}

function b() {
  let res = support()
  res.name = "b"
  return res
}

function support() {
  return {"foo": "bar", "name": "support"}
}

I had an idea while writing this, which I will share as an answer. However, it's not exactly what I'm looking for since a and b end up being function expressions instead of behaving like regular function declarations (if my terminology is correct).

Answer №1

While I was in the process of writing, this idea came to mind so I decided to share it as an "answer", even though it's not exactly what I originally had in mind. Essentially, I crafted an immediately invoked function expression that returns the functions a and b, assigning them respectively to the variables "a" and "b" within the appropriate scope.

let [a, b] = (function(){ 

  function helper() {
    return {"foo": "bar", "name": "helper"}
  }

  function a() { 
    let result = helper()
    result.name = "a"
    return result;
  }
    
  function b() { 
    let result = helper()
    result.name = "b"
    return result;
  }

  return [a, b]
})()

Therefore, at the higher level scope, you can call a and b, while helper remains inaccessible. It's worth noting that these top-level [a, b] aren't technically function declarations; rather, they are variables holding function expressions (as far as I understand). Consequently, calling a() before defining the variables is not possible; if a were indeed a function declared within this scope, it would be hoisted and thus callable beforehand. Ultimately, it seems like achieving what I initially hoped for may be unattainable, hence why this represents my best attempt.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for including an element at the start while creating a map()

enum StatusEnum { accepted = "AC", rejected = "RJ", } const select = (Object.keys(StatusEnum) as Array<keyof typeof StatusEnum>).map((x) => ({ value: x, name: x + "_random", })) /** * Console.log(select) * [ ...

Incorporating Entrance Animations for Individual Elements within ngView Using AngularJS

Can each content within ngView be animated individually upon entering, rather than the entire View (div) itself? ...

Refresh the page using a promise in Angular after a delay of 3 seconds

Currently, I am working on enhancing the functionality of the login page. In case a user enters an incorrect login and password combination, my goal is to have the page automatically reload after 3 seconds. Despite my best efforts, I have encountered chall ...

Is there a way to monitor and trigger a function in jQuery when a loaded PHP file is modified?

I am currently working on a dynamic dashboard that automatically updates every few seconds to display new information fetched from a PHP file. My goal is to trigger an alert only when there is a change in the data itself, rather than just a refresh. In ord ...

Custom HTML form created by Ryan Fait with additional unique elements

My current script for styling checkboxes and radiobuttons is working perfectly: The issue arises when I dynamically add checkboxes and radiobuttons to the page using jQuery. The new elements do not inherit the custom styling. Is there a workaround for th ...

Upcoming verification with JSON Web Token

I am looking to incorporate JWT auth into my Next app. Currently, I have mapped out the flow as such: User enters email and password to log in Server responds with status 200 and a jwt access token in httpOnly cookies My main dilemma lies in deciding on ...

Angular directives enable the addition of DOM elements using ng functions

I'm currently working on creating a custom directive for a small input field that only accepts text. The goal is to dynamically change an icon from a search glass to an X if there is text in the input field, and clear the text when it is clicked on. I ...

Guide on accessing a nested array within a JSON object using JavaScript

I'm currently faced with a json object that contains nested arrays and names with spaces like Account ID. My goal is to only display the Account ID's within my Vue.js application. While I can access the entire response.data json object, I'm ...

Build a Docker container for a project that requires utilizing yarn link for dependencies

While working on my NextJS project, I made the decision to utilize yarn as my package manager and utilized yarn link for import aliases/absolute imports. This feature of yarn is quite handy and is recommended for managing aliases within a project. However, ...

Encountering an error: [nsIWebProgressListener::onStatusChange] when utilizing jQuery AJAX within a click event?

Greetings! I am currently learning how to implement AJAX with jQuery to load an HTML document into a div element within another HTML document. Here is the approach I am using: function pageload() { $.ajax({ url: 'Marker.aspx', ...

Upcoming API and backend developments

When working with the NEXT project, API Routes provide the ability to create an API endpoint within a Next.js application. This can be achieved by creating a function in the pages/api directory following this format: // req = HTTP incoming message, res = H ...

I am looking to modify the background color of characters in a text box once the characters in a textarea exceed 150 characters

Currently, I am utilizing event.data to capture the text inputted into this particular HTML textbox. My intention is to change the background color to red based on that input. However, when using the style attribute on event.data, I encounter an error. It& ...

I am struggling to display an array of objects retrieved from the server in the UI using AngularJS

I am receiving an array of objects as a JSON from the server. When I try to access my service URI from HTML, I encounter the following array in my console: "angular.js:13920 Error: [$resource:badcfg] http://errors.angularjs.org/1.5.8/$resource/badcfg?p0= ...

Communicate through PHP and JavaScript chat to display HTML content in the chat window

I have been attempting to display HTML output in the chat window but instead, it is showing the HTML code. Here are the two files involved in the chat system: chat.js `function chatHeartbeat(){ var itemsfound = 0; if (windowFocus == false) { var ...

Speed up - Handle alias resolution with module federation

Currently import federation from '@originjs/vite-plugin-federation'; import react from '@vitejs/plugin-react-swc'; import dns from 'dns'; import path from 'path'; import { visualizer } from 'rollup-plugin-visual ...

Selecting elements dynamically with JQuery

Trying to use a jQuery selector within plugin code created by a 3rd party has proved difficult. When hardcoded, it works fine; however, when attempting to use variables for dynamic selection, the object cannot be found. The lack of id handles in the CSS c ...

Suggestions for efficiently filtering nested objects with multiple levels in RXJS within an Angular environment?

Just a Quick Query: Excuse me, I am new to Typescipt & RxJS. I have this JSON data: [ { "ID": "", "UEN": "", "Name": "", "Address": "", "Telephone&quo ...

The animation in Material UI does not smoothly transition with the webkit scrollbar

I've been experimenting with CSS animations in Material UI's sx property to achieve a webkit scrollbar that eases in and out. However, instead of the desired effect, the scrollbar appears and disappears instantly. Whether I define the keyframes ...

Specialized express Validator for 2 particular fields

I currently have 2 custom validators set up for the fields email and phone. check('phone') .not() .isEmpty() .withMessage('Phone should not be empty') .custom(async phone => { const phoneCheck = await ...

After deploying on Vercel, Next.js' getServerSideProps function is returning undefined

I am trying to create a Netflix-inspired website using next.js. I am able to fetch movie data from TMDB using getServerSideProps(). While everything works as expected in development mode, once deployed on Vercel (re-deployed multiple times), the props I re ...