Closure is an amazingly powerful programming tool, most tricks you can do in a functional language based on closure.

To put it simple, closure is a function without name. Its a value, just like normal variable, can be associate with any valid variable name. You can assign it to local variable name, pass it as parameter, return it from a function.

 
myClosure = { arg1 , arg2 ->
    println arg1
    println arg2
}
 

A closure is the same as any normal function except the way of the parameter declaration. In Groovy , parameter list and function body divided by "->" operator. It looks like an arrow, means send the parameter to function body.

There are a lot of ways to call the closure.

 
myClosure 'hello', 'world'
myClosure.call('hello', 'world')
myClosure('hello', 'world')
myClosure.doCall('hello', 'world')
 
 

Pass closure as parameter or return from function.

 
def foo( closure ) {
    closure('hello','world')
    closure
}
 
foo(myClosure)
foo(myClosure)('return', 'value')
 
 

But the most used form is the following.

 
 
foo { arg1 , arg2 ->
    println arg1
    println arg2
}
 
list = [3,4,5]
list.each { it ->
    println it
}
 

In Javascript, the inner function can reference the variable that defined in its parent function. Groovy closure is just like that.

 
def bar () {
    local = 'I am local'
    localClosure = { it -> 
        println it
        println local
    }
 
    localClosure
} 
 
bar()('hello')