I'm self-studying JavaScript and new to functions. I'm playing around with it and the results of one I made confuse me a bit--please see my code below. The first time my function is run, it spells out "cat" as "c", "a", "t" in the console. That makes sense to me. But when I store it in a variable and call that variable, it does the same exact thing but with "undefined" at the end. Shouldn't the results be the same? I don't understand how there is "undefined" when you call a function via a variable. I'd really appreciate any help to explain this.
function printCat(x) { for (i = 0; i < x.length; i++) { console.log(x[i]) } } printCat("cat") var func1 = printCat console.log(func1("cat"))
The output is the same. It prints cat. undefined is being printed by the last console.log(). When you print console.log('A'), it prints 'A'. As you are trying to console.log(function), it prints undefined.
console.log()
console.log('A')
console.log(function)
2.1m questions
2.1m answers
60 comments
57.0k users