skip to Main Content

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!

2

Answers


  1. 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);
    Login or Signup to reply.
  2. Anonymous functions work the same as named functions: you have to call them explicitly; they don’t get called automatically when used in expressions.

    So if you want a method to accept an anonymous function as an argument, you have to write the code inside the method to call the function.

    For example, if you want str to be a function, you could write the append function like this:

    function appendLetterToString(letter, str) {
      return str() += letter
    }
    

    Now it will work only if you pass a function, not if you pass a string. If you want it to work both ways, you have to examine the type of the value inside the body:

    function appendLetterToString(letter, strOrFun) {
        let str = strOrFun
        if (typeof strOrFun === 'function')
            str = strOrFun()
        return str += letter
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search