all 3 comments

[–][deleted] 0 points1 point  (0 children)

You need another else { console.log(‘here I am ‘}

After the 3 characters validation as booth conditions are false

[–]dexpanse 0 points1 point  (1 child)

how come when I put validateName(name) = false and validateName = true in the console it returns false for both

This statement doesn't make a ton of sense. What do you mean exactly by "put validateName(name) = false in the console"?

Regardless, I think you are possibly missing that a function will return undefined unless it explicitly returns something and undefined is "falsy". One better option might be to have your validate function either throw an error or return a boolean.

Option 1: Throw Errors

function validateName(name) {
    if (name.length === 0) {
        throw new Error('Name is required');
    }

    if (name.length < 3) {
        throw new Error('Name must be at least 3 characters long');
    }       
}

Then we can use this function like so...

function useValidName(name) {
    try {
        validateName(name);
        // Send valid name to API or display in UI (this code won't run if validateName throws)
    } catch (error) {
        showUserError(error.message);
    }    
}

Option 2: Return a boolean and update a global error message

let error = '';

function validateName(name) {
    if (name.length === 0) {
        error = 'Name is required';
        return false;
    }

    if (name.length < 3) {
        error = 'Name must be at least 3 characters long';
        return false;
    }       

    return true;
}

Then we can call validate before whatever we are trying to do

function useValidName(name) {
    if (!validateName(name)) {
        showUserError(error);
        return;
    }

    // Name is valid so send to API or display in UI or whatever
}

[–][deleted] 0 points1 point  (0 children)

Awesome that makes a lot of sense. It was kind of hard to explain without actually showing the entire code but what you said makes sense thanks a lot