skip to Main Content

I am new to JavaScript, try to learn how to read a function, it would be great if someone could look at this code and tell me why I am getting ‘undefined’ output here:

const myArray = [0, 1, 2, 3, 4, 5];
function arryIncludesMain(arr, item) {
  return arr.includes(item);
}

function arryIncludesAlt(arr, item) {
  if (arr.includes(item)) {
    console.log("true");
  } else {
    console.log("false");
  }
}

console.log(myArray.includes(8))

console.log("-----------------------------------------------");

console.log("Main function output:");
console.log(arryIncludesMain(myArray, 3));
console.log(arryIncludesMain(myArray, 6));
console.log("-----------------------------------------------");

console.log("Alt function output:");
console.log(arryIncludesAlt(myArray, 3));
console.log(arryIncludesAlt(myArray, 6));

And here is the console output:

false
-----------------------------------------------
Main function output:
true
false
-----------------------------------------------
Alt function output:
true
undefined
false
undefined

What is the difference between Main and Alt approach that I am getting ‘undefined’ output in console? what this ‘undefined’ refer to?

3

Answers


  1. Functions return:

    In JavaScript, when a function does not have a return statement or when it reaches the end of the function without returning a value, it implicitly returns undefined.

    arryIncludesAlt() does not have a return statement, and instead, it uses console.log to print a string (true or false) to the console.

    Login or Signup to reply.
  2. The reason you’re getting undefined, is because your arrayIncludesAlt function is not returning anything, instead it’s a ‘void’ method that logs
    the result. So you shouldn’t call console.log on this method.

    Instead of doing:

    console.log(arryIncludesAlt(myArray, 3)); // logs undefined
    console.log(arryIncludesAlt(myArray, 6)); // logs undefined
    

    You should be doing:

    arryIncludesAlt(myArray, 3) // will do console.log while calling this function
    arryIncludesAlt(myArray, 6) // will do console.log while calling this function
    

    As inside your arryIncludesAlt function you’re already logging the result.

    Login or Signup to reply.
  3. The difference is "return" statement. It makes function to have a result.

    The alternate way is:

    function arryIncludesAlt(arr, item) {
      if (arr.includes(item)) {
        console.log("true");
      } else {
        console.log("false");
      }
      return arr.includes(item);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search