Function is not working

I want to write a function to check if the ‘email’ input in ‘myInfo’ contains a ‘@’,
but i found that the function returns ‘true’ no matter if ‘@’ is present,
so how should i amend the code? thank you!

let myInfo = {
  name:'peter',
  email:'abc@gmail.com',
};

function checkEmail () {
   var correct = ['email'].includes('@');
    return true;
}

console.log(checkEmail(myInfo.email));

When you post code on the forums, you need to format it so it will display correctly. You can highlight your code, then use the </> button in the editor window, or you can place three backticks ``` (top left key on US/UK keyboards) on a line above your code, and three on a line below your code. I find this approach easier, but unfortunately some European and other keyboards don’t have that character.

You need something more like this

let myInfo = {
    name:"peter",
    email:"abcgmail.com"
};

function checkEmail(email) {
    if(email.includes("@")) {
        return true;
    } else {
        return "Invalid email address"
    }
}

console.log(checkEmail(myInfo.email));

Currently, the first line of your function is assigning ['email'].includes('@') to the variable correct (which you then don’t use anywhere). In the 2nd line, you just return true. So the function when called just responds with true whatever you put in it.

Also note, that when you call checkEmail(), you are passing in an argument which the function itself hasn’t been set up to use.

2 Likes

Appreciated for your reply, chrisofarabia.
so you mean when i’m calling the checkEmail function, the argument supposed to be sent is actually hasn’t been set up to use? If i want to send the argument from the ‘email’ in "myInfo’
How can i set up?

It’s all in that alternative code I’ve given you there.

When you call the function, it is given the myInfo.email as a value to work with. Looking at the function itself, this is then passed into the function as email and used inside the function to access the value of myInfo.email - in the case of my version of the code, this value is “abcgmail.com” - as the “@” is missing, it returns the message “Invalid email address”.

Have a play around with different values of myInfo.email in the browser console and give it a bit of a test.

You might also find this reference useful - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.