Is it possible to set functions as variables within an if statement in JavaScript and then not be able to call them later?

My validation process involves a multi-function where I don't invoke a master function beforehand to check and validate inputs. Within my "SignUp Function", I have implemented a validation function as variables that are checked before passing to the remaining functions. While the validation process works smoothly, I encounter issues with the rest of the functions not being invoked resulting in an empty database.

// Example of Validation Function
handleUsername = () => {
    const {userName} = this.state;
    if (userName.length <= 0) {
      this.setState({
        NameValid: 'Please enter your name',
      });
      return;
    } else {
      this.setState({
        NameValid: '',
      });
    }
}

signUpFunc = async () => {
    console.log('I am here');
    const {email, password} = this.state;
    
    // Performing Validations on Inputs
    const nameValid = this.handleUsername();
    const emailValid = this.handleEmail();
    const phoneValid = this.handlePhone();
    const passwordValid = this.handlePassword();

    if (!nameValid || !phoneValid || !emailValid || !passwordValid) {
      console.log('Validation statement present');
      return;
    } else {
      console.log('else statement'); // This is not showing up in the console after validation
      console.log('email', email);
      console.log('password', password);
      
      await auth()
        .createUserWithEmailAndPassword(email, password)
        .then(() => {
          console.log('done');
          this.setState({loading: true}, () => this.createUserDatabase());
        })
        .catch(error => {
          // Handling Errors 
          var errorCode = error.code;
          switch (errorCode) {
            case 'auth/email-already-in-use':
              alert('This email is already in use, please try another one');
              this.setState({loading: false, password: ''});
              break;
            case 'auth/invalid-email':
              alert('Invalid email address, please try another one');
              this.setState({loading: false, password: ''});
              break;
            case 'auth/operation-not-allowed':
              alert('This email service is disabled by the app administration');
              this.setState({loading: false, password: ''});
              break;
            case 'auth/weak-password':
              alert('Weak password provided');
              this.setState({loading: false, password: ''});
              break;
            default:
              alert('Check your internet connection');
              this.setState({loading: false, password: ''});
              break;
          }
        });
    }
  };

Answer №1

When using if and else, the code will only execute either the if block or the else block, like so:

if (true) {
  console.log('Here'); // this will be executed
} else {
  console.log('Not here'); // this won't be executed
}

Only the first condition will be executed.

Another important point is that if you assign a function to a variable but don't return anything from the function, the variable will be considered as false, for example:

function example() {
  return;
}

const variable = example();

if(!variable) { // although it's false, the 'not' makes it evaluate to true
  console.log('is true');
}

To properly check whether something is valid or not, make sure to explicitly return true or false from your function, like this:

function example() {
  if(1 === 1) {
    return true;
  } else {
    return false;
  }
}

const variable = example();
console.log(variable);

Therefore, in your code, you should structure it similar to this:

// sample of validation functions
handleUsername = () => {
    const {userName} = this.state;
    if (userName.length <= 0) {
      this.setState({
        NameValid: 'Please enter your name',
      });
      return false; // return false for invalid input
    } else {
      this.setState({
        NameValid: '',
      });
      return true; // return true for valid input
    }
}

signUpFunc = async () => {
    console.log('im here');
    const {email, password} = this.state;
    // Validate Inputs
    const nameValid = this.handleUsername();
    const emailValid = this.handleEmail();
    const phoneValid = this.handlePhone();
    const passwordValid = this.handlePassword();

    if (nameValid || phoneValid || emailValid || passwordValid) {
      console.log('Validation successful');
      
      // Execute the following code if any validator returns true
      console.log('else statement'); 
      console.log('email', email);
      console.log('password', password);
      await auth()
        .createUserWithEmailAndPassword(email, password)
        .then(() => {
          console.log('done');
          this.setState({loading: true}, () => this.createUserDatabase());
        })
        .catch(error => {
          // Handle Errors
          var errorCode = error.code;
          switch (errorCode) {
            case 'auth/email-already-in-use':
              alert('This email is already in use, please try another one');
              this.setState({loading: false, password: ''});
              break;
            case 'auth/invalid-email':
              alert('Invalid email address, please try another one');
              this.setState({loading: false, password: ''});
              break;
            case 'auth/operation-not-allowed':
              alert('This email address has been disabled by the app administrator');
              this.setState({loading: false, password: ''});
              break;
            case 'auth/weak-password':
              alert('Weak password provided');
              this.setState({loading: false, password: ''});
              break;
            default:
              alert('Check your internet connection');
              this.setState({loading: false, password: ''});
              break;
          }
        });
    }
  };

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 issue persists with the ajax.reload() function in DataTables

It's been driving me crazy that my datatables table won't refresh, despite using ajax.reload. I've spent weeks on this code but still can't get it to work. DataTablesDraw = (selector, order, pages, file, sort, column, template, data_se ...

"Eliminate a specified range of characters from a string using JavaScript

I am currently working on a JavaScript function that will remove specific characters from a string. I have tried various methods such as `string.slice()`, `string.substr()`, and `string.substring()`, but what I really need to do is remove everything before ...

Having trouble importing a package into my React boilerplate

Having trouble importing the react-image-crop package with yarn and integrating it into a react boilerplate. Encountered an error after installing the package: Module parse failed: /Users/...../frontend/node_modules/react-image-crop/lib/ReactCrop.js Unex ...

sliding to the right gets jammed

I am encountering a peculiar issue with Multi-page slide functionality. Whenever I attempt to switch pages, the new page gets stuck on the left before sliding out into position. Feel free to test this problem using my JSFiddle This is the JQuery code that ...

Is there a way to retrieve the value from an input box?

<td class="stockQuantity"> <input class="form-control" id="Cart1" name="qty_req" required="required" type="text" value=""><br> <button type="button" o ...

What is the proper way to indicate the pointer to the current element within the array?

How can I modify a code that displays a list of posts? import React from "react"; type respX = { "id": any, "userId": any, "title": any, "body": any, } interface PropsI { } interface StateI { data: respX []; } export class Compone ...

Discovering ways to align specific attributes of objects or target specific components within arrays

I am trying to compare objects with specific properties or arrays with certain elements using the following code snippet: However, I encountered a compilation error. Can anyone help me troubleshoot this issue? type Pos = [number, number] type STAR = &quo ...

What distinguishes running rm -rf node_modules + npm i from using npm ci?

When using a Unix system and needing to clean out the node modules folder, is there any benefit or distinction between executing rm -rf node_modules followed by npm i as opposed to npm ci My understanding is that both yield the same outcome, but is th ...

Using JQuery to retrieve part of a className results in a null value being returned

I am facing an issue with a piece of code in codesandbox where it returns null when I attempt to retrieve part of the className from a div using JQuery. How can I troubleshoot this and make it work? Check out the Codesandbox Example import React, { Compo ...

Encountering a console error: Prop type validation failed for the `Rating` component with the message that the prop `value` is required but is currently `undefined`

I am encountering a proptype error which is causing an issue with the URL display on my Chrome browser. Instead of showing a proper address, I am seeing the URL as undefined like this: http://localhost:3000/order/undefined Instead of undefined, I should h ...

Error: The checkbox was clicked, but an undefined property (includes) cannot be read

Link to live project preview on CodeSandbox Visit the product page with checkbox I have developed a code snippet that allows users to filter products by checking a box labeled "Show Consignment Products Only", displaying only those products with the term ...

Access user connections through Discord.js bot

Hi there, I'm currently working on creating a bot that can retrieve a user's connected battle.net account and display their game rank. I am utilizing the discord.js library and have been attempting to access the UserProfile through the bot. Unfor ...

Preserving the initial input values in a secure manner for future reference, utilizing either an object or a

Recently, I've started revisiting a script I created a while back that checks for changes in a form to prompt a message asking 'Would you like to save your changes?'... One thing that's been on my mind is whether I should store the ori ...

Experiencing an issue with the countdown timer while utilizing react-countdown library

Currently, I am in the process of creating a countdown timer that allows users to input time in minutes and start or stop the clock. However, I have encountered two challenges: I defined a state running to determine if the clock is running, and based on t ...

Initiate automatic playback of audio on website following a delay

I attempted to change the state of play from false to true and also experimented with adding ComponentDidMount,ComponentDidUpdate, and ComponentWillMount but unfortunately, nothing seemed to solve the issue. I consistently encountered errors at different p ...

Are there any better methods for transforming a class component into a hook component?

After some attempts, I'm working on getting this code to function properly using useState: https://codesandbox.io/s/rdg-cell-editing-forked-nc7wy?file=/src/index.js:0-1146 Despite my efforts, I encountered an error message that reads as follows: × ...

Tips for capturing changes in a "count" variable and executing actions based on its value

I have a counter on my webpage and I'm trying to change the style of an element based on the count variable. I tried using the .change action but I haven't been able to get it working. It might not be the right solution. Can anyone provide some ...

Combining broken down values within a loop

https://i.sstatic.net/PI3NI.png Take a look at this image, then review the code I've provided: function addNumbers() { var inputList = document.getElementById("listInput").value.split(" "); for(i = 0; i <= inputList.length; i+=1) { ...

Converting UTC Date Time to Full Date Using ES6

Is there a way to transform the date 2021-01-10 12:47:29 UTC into January 10, 2021? I've been attempting to achieve this using moment.js code below, but it seems to be functioning in all browsers except Safari. {moment(video?.createdAt).format(' ...

Executing a node module in a web browser

I'm attempting to upload and read an Excel file with the help of a node module called read-excel-file. Following the instructions for usage in the browser, I have added the following code snippet to my .js file: import readXlsxFile from 'read-ex ...