Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing an anonymous function as an argument but it treats it as a string

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading