What could be causing my prompt for a username to not work properly as I attempt to develop a system that generates a unique code using the user's initials?

I'm currently working on a script that will be used by the secretaries in our school district to generate unique codes for new students or hires. The code will consist of an 8-digit output, a randomly generated 6-digit number, and the user's initials at the end. This unique code will trigger automatic account creation in our systems. While we have the account creation process set up and working smoothly, we're facing challenges with generating the unique code. I've omitted the random number generation part of the script since my main obstacle lies in prompting for the user's name and extracting their initials.

function ID() {
    var userName = prompt("Please enter your name", "<User Name>");
}

function getInitials(name) {
  let initials = "";
  let waitingForSpace = false;

  for (var i = 0; i < name.length; i++) {
    if (!waitingForSpace) {
      initials += name[i];
      waitingForSpace = true;
    }

    if (name[i] === " ") {
      waitingForSpace = false;
    }
  }

  return initials;
}
console.log(getInitials(userName));


I expect to receive a prompt for the User Name, which will be stored as userName. This variable is then passed to the getInitials function. However, when attempting to run Node Initials.js, I encounter the following error message...

ReferenceError: userName is not defined
at Object. (/Users/dross/Documents/UserID/Initials.js:22:25)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js(internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)

Answer №1

There seems to be a missing } in your code snippet. To correct this issue, you can modify your code like this:

function retrieveUserName() {
  var user = prompt("Please enter your username", "<Your Username>");
  return user; // return the inputted username
}

function getInitials(fullname) {
  let initials = "";
  let spacePending = false;

  for (var j = 0; j < fullname.length; j++) {
    if (!spacePending) {
      initials += fullname[j];
      spacePending = true;
    }

    if (fullname[j] === " ") {
      spacePending = false;
    }
  }

  return initials;
}

var username = retrieveUserName(); // returns the entered username
console.log(getInitials(username));

Answer №2

Your initial post contained the entire function as a closure, making the inner 'username' function accessible from the outside. By the way, I believe there was no missing '{' as you mentioned.

In your updated code, 'username' is now a local variable since it is not assigned as a 'function'. This means that it is 'not defined' outside of its scope.

I recommend taking note of Peter B's comment advising you to call the (original) function like this:

console.log(getInitials(userName()));

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

The error message that keeps popping up is saying that it cannot access the property "username" as it is undefined

signup.js const SignupForm = () => { const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const handleSignup = () => { fetch("/signup", { method: "post", header ...

retrieve the date value of Focus+Context by using the Brushing Chart

Currently, I am engaged in analyzing the sentiment of tweets on Twitter. The analysis will produce an overall area graph that allows me to choose a specific date range and extract all or some of the tweets falling within that range. In order to create a t ...

Increase the border at the bottom while hovering with React.js and the Material UI library

Can someone help me achieve a hover effect similar to the one in this question on Stack Overflow: Hover effect : expand bottom border I am attempting to create the same effect in React using makeStyles of Material UI. Here is my current code: const useSty ...

Creating a wrapper class in Express JS: A step-by-step guide

I am currently developing a basic wrapper app that retrieves the following information from user requests: a) Request Date & Time b) Request URL c) Response Time This is my approach to wrapping the functionality using Express.js: var express = require(&a ...

Tips for choosing a single checkbox from a set of multiple checkboxes in React.js

I iterated through a list of objects to generate table rows, each containing an input tag with the type set as checkbox. const [ isChecked, setIsChecked ] = useState(false); const handleChange = (e) => { setIsChecked(e.target.checked) ...

Master the art of displaying complete text when zooming in and elegantly truncating it when zooming out

I am currently working on a data visualization project using d3.js. The tree chart that I have created is functioning well, but I would like the text to react dynamically when zooming in and out. You can find the code for my project on this JSFiddle page. ...

Failing to utilize callback functions results in forgetting information

I am facing an issue with my code where changes in the parent component trigger a re-render of the child element. The Menu component is supposed to appear on right-click on top of the placeholder tag, but when it does, the entire parent component flicker ...

The div smoothly descended from the top of the page to the center under the control of jQuery

I am trying to implement a feature where a div slides down from the top of the page to the center when a button is clicked. However, my current code seems to be causing the div to slide from the bottom instead of the top. Ideally, I want the div to slide ...

The Php fetch function provides a string output instead of a boolean value of "true" or "false"

In my use of FullCalendar, I have noticed that some events are being displayed with a time even though they are set to be all-day events in PHP using 'allDay' => 'false'. I want to set the default value for all events to false unless ...

Understanding jest.mock: Verifying the invocation of a nested function

I have a section of code in my application that looks like this: import validationSchema from "./../_validation/report"; const reportModel = require("../models/report"); ctrl.addReport = async (req, res) => { const { body } = req; try { cons ...

Identifying and implementing page language in nextJS: Solving the ReferenceError "window is not defined" issue

I am currently working on developing a website that can automatically detect the user's country and set the language accordingly. In React, I usually achieve this by using window.navigator.language. Here is a snippet of the code: import * as pt from ...

What steps can I take to fix error TS7015 in my TypeScript, Next.js, and React application when I encounter an index expression that is not a number data type?

I encountered an error stating "Element implicitly has an 'any' type because the index expression is not of type 'number'.ts(7015)" The file I imported is import { useAmazon } from "@context/amazon"; I used it as follows con ...

Sending the content of a textBox to a JavaScript function

Although my question may be somewhat outdated, after exhausting all possible solutions, I am still unable to find a resolution. I am trying to create a function for verifying input fields: This particular function is functioning correctly: function myFu ...

Using NodeJS to perform asynchronous tasks with setImmediate while also incorporating private class

Today marks my first time experimenting with setImmediate. I've come to realize that it may not be able to run private class methods. Can someone shed some light on this? Why is that the case? Not Functioning Properly When trying to use a private cl ...

Commencement of timeline utilizing amchart's gantt feature

I am currently utilizing the Gantt chart feature in Amchart. The chart segments are organized based on dates. I am looking to specify a specific initial location for the chart's navigator between two dates, rather than having it applied across the en ...

Tips for refreshing a webpage after switching screens

// I have implemented the code below to navigate from one screen to another, specifically the Home page. However, I am facing issues with the page refreshing or reloading when navigating to the home screen. None of the lifecycle methods are being called, e ...

What is the best way to uppercase each element in an array using only a while loop in plain ECMAScript 5?

Struggling with a simple exercise that requires converting names to uppercase and passing them to an empty array using only while loop(s) in plain JavaScript: var names = ['rob', 'dwayne', 'james', 'larry', 'st ...

Enhancing Security: Implementing Node.js API Authentication

Looking for guidance on setting up multiple authentications with different roles in Next.js development. Can anyone help me navigate this aspect of website building? Using Next.js for the frontend Utilizing Node.js and JWT (JSON web token) for the backend ...

How can we leverage the nullish coalescing operator (`??`) when destructuring object properties?

When working with ReactJS, I often find myself using a common pattern of destructuring props: export default function Example({ ExampleProps }) { const { content, title, date, featuredImage, author, tags, } = ExampleProps || {}; ...

The CSS class names for Next.js have not been defined yet

Just getting started with next js and trying to use css modules for styling my nav component. However, I noticed that the classname I setup for the nav element is not showing up in the rendered DOM. Even though I can see the generated styles by webpack in ...