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
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 returnsundefined
.arryIncludesAlt()
does not have areturn
statement, and instead, it usesconsole.log
to print a string (true
orfalse
) to the console.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:
You should be doing:
As inside your
arryIncludesAlt
function you’re already logging the result.The difference is "return" statement. It makes function to have a result.
The alternate way is: