1

I'm learning JavaScript and I found this example

say("Hello")("World"); 

This code should return "Hello World".

I don't know how to implement this even what keyword type to google to find soulution. Can you advice me please what is name of this pattern or how it is possible to implement it in JavaScript?

Dhaval Marthak
  • 17,246
  • 6
  • 46
  • 68
y0j0
  • 3,369
  • 5
  • 31
  • 52

2 Answers2

4

You could do:

function say(firstword){
    return function(secondword){
     return firstword + " " + secondword;   
    }
}

http://jsfiddle.net/o5o0f511/


You would never do this in practice though. I'm sure this is just to teach you how functions can return executable functions.

There's some more examples of this pattern here:

How do JavaScript closures work?

Community
  • 1
  • 1
Curtis
  • 101,612
  • 66
  • 270
  • 352
4

Possibly you can try closures:

var say = function(a) {//<-- a, "Hello"
  return function(b) {//<-- b, "World"
    return a + " " + b;
  };
};

alert(say("Hello")("World")); //<--  "Hello World"

Here, when say("Hello") is invoked it returns the inner block. The later call with ("World") invokes the inner block returning the concatenated string "Hello World"