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?
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.