Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript "undefined" value

Im a very newbie to JS. Would anyone please explain how did I got the "undefined" value base on this script below:

const hummus = function(factor) {
  const ingredient = function(amount, unit, name) {
    let ingredientAmount = amount * factor;
    if (ingredientAmount > 1) {
      unit += "s";
    }
    console.log(`${ingredientAmount}, ${unit}, ${name}`);
  };
  ingredient(1, "can", "chickpeas");
  ingredient(0.25, "cup", "tahini");
  ingredient(0.25, "cup", "lemon juice");
  ingredient(1, "clove", "garlic");
  ingredient(2, "tablespoon", "olive oil");
  ingredient(0.5, "teaspoon", "cumin");
};
console.log(hummus(6))

Output result:

6, cans, chickpeas  
1.5, cups, tahini  
1.5, cups, lemon juice  
6, cloves, garlic  
12, tablespoons, olive oil  
3, teaspoons, cumin  
undefined

If I change the last code console.log(hummus(6)) to only hummus(6), the undefined value will be omitted from the output result. I just want to know how the undefined value generated in this circumstances. I appreciate all your helps.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The reason why it shows undefined is because it is logging the return value from the executed function hummus.

Add a return statement at the end of the hummus function, then it should return the value instead of undefined.

const hummus = function(factor) {
  // ...

  return "Hello world";
};

console.log(hummus(6))

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions#description

To return a value other than the default, a function must have a return statement that specifies the value to return. A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is undefined.

JavaScript by default, as comments mentioned, is return undefined, you could check it by running console.log((()=>{})());

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading