1

A code example from a JavaScript book. I am learning about passing functions as arguments to functions. The solution explains that when we pass the hawaiianTranslator function to the sayIt function that the string "hello" is the argument for hawaiianTranslator.

Can someone please explain very simply why this is. sayIt doesn't return anything so why/how is the value of phrase being passed to the hawaiianTranslator function.

Thank you in advance

function sayIt(translator) {
    var phrase = translator("Hello");
    alert(phrase);
}

function hawaiianTranslator(word) {
if (word === "Hello") return "Aloha"; 
if (word === "Goodbye") return "Aloha";
} 

sayIt(hawaiianTranslator);

sayIt(hawaiianTranslator); alerts "Aloha". How does this happen? I don't understand how the string "hello" is the argument to the function hawaiianTranslator

2
  • 1
    Hi, I don´t fully understand the question, could you try to reprhase a little bit to see if I understand the problem? Commented Jul 7, 2017 at 5:32
  • sayIt(hawaiianTranslator); alerts "Aloha". How does this happen? I don't understand how the string "hello" is the argument to the function hawaiianTranslator I've added this to the question to Commented Jul 7, 2017 at 5:36

1 Answer 1

3

You are passing function reference hawaiianTranslator into sayit function as argument, there you are recieving it in translator variable. So inside sayit function you are calling translator("Hello") which will be same as hawaiianTranslator("Hello") in effect

function sayIt(translator) {
    var phrase = translator("Hello");
    alert(phrase);
}

In the above function when you call translator("Hello"), which will invoke hawaiianTranslator function with "Hello" as argument.

function hawaiianTranslator(word) {
    if (word === "Hello") return "Aloha"; 
    if (word === "Goodbye") return "Aloha";
}

This function return the translated word. So in the first function you will get the translated word ("Aloha") in phrase variable.

Sign up to request clarification or add additional context in comments.

1 Comment

Why is it the same? As we alert "hello" the function doesn't return it and the functions value isn't "hello". Could you please explain a little further please. I'm quite new to JavaScript

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.