Search code examples
javascriptundefined

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.


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((()=>{})());