I’m new to JavaScript/programming and I was playing around with passing functions as arguments just to get familiar with the concept. I saw the following example online and tried to create my own more simple example:
var materialsLength1 = materials.map(function(material) {
return material.length;
});
Here’s what I tried:
function appendLetterToString(letter, str) {
return str += letter
}
let pizza = appendLetterToString("a", function(){
return "pizz";
})
console.log(pizza);
I was expecting to get ‘pizza’ in the console but the result I got is this string:
function(){
return "pizz";
}a
Why does my ‘function’ get evaluated as a string?
Hope this isn’t a dumb question. Appreciate any answers!
>Solution :
Why does my ‘function’ get evaluated as a string?
Because you don’t run the function, so the value isn’t pizz, but the function itself, as a string.
In your example there is no need to pass the second arg as a function, but if you want that, you should call it to get it’s return value:
function appendLetterToString(letter, str) {
return str() + letter
}
let pizza = appendLetterToString("a", function(){
return "pizz";
})
console.log(pizza);
But you’re probably better of passing a string:
function appendLetterToString(letter, str) {
return str += letter
}
let pizza = appendLetterToString("a", "pizz");
console.log(pizza);