Wednesday, October 28, 2020
[vc_custom_heading text=”JavaScrtipt Closures” google_fonts=”font_family:Noto%20Sans%3Aregular%2Citalic%2C700%2C700italic|font_style:400%20regular%3A400%3Anormal”]

In order to understand closures in JavaScript I think is necessary to really understand the difference between Function scope and Lexical Scoping.

In JavaScript we have Function and Lexical Scoping.

Function Scope means that any variable which is defined within a function is visible within that entire function.

[vc_wp_text]
// global scope

// foo is a global function
function foo() {

  // bar is local to foo
  function bar() {

  }
}
  [/vc_wp_text]

Lexical Scoping is simply how variable names are resolved in nested functions. It means that the scope of an inner function contains the scope of a parent function.

Other names of Lexical Scoping are Static Scoping or Closure.

A closure happens when you return a function from inside of a function and that inner function retains access to the scope.

Let’s look at the following example:

[vc_wp_text]
var closureAlert = function () {
  var x = 0;
  var alerter = function () {
    alert(++x);
  };
  return alerter;
}

var funcStorer = closureAlert();
var funcStorer2 = closureAlert();

funcStorer(); //1
funcStorer(); //2
funcStorer2(); //1
  [/vc_wp_text]

Here in funcStorer is the closure.

Alerter function has access to his own scope as well as the previous scope

All this possible because in JavaScript functions are first objects,

which means that functions are objects, with a type and a behavior. They can be dynamically built, passed around as any other object.

[vc_custom_heading text=”C# Closures ” google_fonts=”font_family:Noto%20Sans%3Aregular%2Citalic%2C700%2C700italic|font_style:400%20regular%3A400%3Anormal”]

As we saw earlier the concept of closure is a first-class function with free variables bound in the lexical environment.

In C# we can create a first class function using anonymous methods using delegates or lambdas

[vc_wp_text]
Func<int, string> myFunc = delegate (int var1) {
  return "something";
};
 
[/vc_wp_text]

Using the delegate keyword allow us to write an inline method or anonymous method, unfortunately anonymous method have a noise syntax because of the return keyword extra curly braces that makes them hard to read but there is an alternative to makes this code better using lambda expression syntax which were introduced where the language designers introduced LINQ into the language.

Lambda syntax:

[vc_wp_text]
Funk<int,string> myFunc = var1 => "something";
  [/vc_wp_text]

Let’s look in one simple example:

I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

[vc_wp_text]
public static void Main (string[] args) {
  var inc = Incrementer ();
  Console.WriteLine (inc (3));
  Console.WriteLine (inc (4));
  Console.WriteLine (inc (4));

  Console.WriteLine ("\n");

  var inc2 = Incrementer ();
  Console.WriteLine (inc2 (3));
  Console.WriteLine (inc2 (4));
  Console.WriteLine (inc2 (4));

  Console.ReadLine ();
}

public static Func<int, int> Incrementer () {
  var myVar = 1;
  Func<int, int> inc = var1 => {
    myVar = myVar + 1;
    return var1 + myVar;
  };
  return inc;
}
  [/vc_wp_text]

When we call ” Incrementer “, we get a method back that increments a local variable inside of the method. now “myVar” is a local variable, but when we return the “inc” method, it is bound inside lambda expression

Well this is a Closure in C#.

[vc_custom_heading text=”Swift Closures” google_fonts=”font_family:Noto%20Sans%3Aregular%2Citalic%2C700%2C700italic|font_style:400%20regular%3A400%3Anormal”]

Let’s finally examine Swift Closures

In Swift functions are defined with the func keyword. Functions can take and return none, one or multiple parameters (tuples).

[vc_wp_text]
func funcname(Parameters) - > returntype {
  Statement1
  Statement2
  -- -
  Statement N
  return parameters
}
  [/vc_wp_text][vc_wp_text]
func multiplyNumbers(number1: Int, number2: Int) - > Int {
  return number1 * number2
}
var result = multiplyNumbers(3, 6)
// result = 18
  [/vc_wp_text]

Every function has its own function type, this type is made up of the parameter types and the return type of the function itself.

For example, the type of our last multiplyNumbers functionis:

[vc_wp_text]
(Int, Int) -> (Int)
  [/vc_wp_text]

Function types in Swift can be used as parameters types or as return types for nesting functions.

Closures are typically enclosed in curly braces { } and are defined by a function type () -> (), where -> separates the arguments and the return type, followed by the in keyword which separates the closure header from its body.

[vc_wp_text]
{
  (params) - > returnType in
    statements
}
  [/vc_wp_text]

Closure arguments can be references by position ($0, $1, …) rather than by name

Furthermore, when a closure is the last argument of a function, parenthesis can be omitted as such:

[vc_wp_text]
applyMutliplication(2) {$0 * 3}
  [/vc_wp_text][vc_wp_text]Here’s a simple function called duplicate. It takes an Int argument and it returns a Double with the duplicated value. We can declare the function, and we can declare the variable at the same time, and since we have a reference to our function we can get rid of the function name. This unnamed function that we just created is called a Closure, or sometimes a Lambda functions. [/vc_wp_text][vc_wp_text]
func duplicate(x: Int) - > Double {
  return Double(x) * 2
}
  [/vc_wp_text]

Turns out that we can simplify this declaration quite a bit more.

There’s a lot of information that’s on both sides of the equal sign, typing information in particular. So we can leave out anything that the compiler can figure out. when the compiler sees the declaration, it can infer the argument types and the return value from that declaration, so we don’t need to put that information inside the closure definition also, so we can get rid of the types, leaving the variable name.

[vc_wp_text]
let dup: (Int) - > Double = {
  (x: Int) - > Double in
  return Double(x) * 2
}
   
  [/vc_wp_text]

Now, Instead of accessing the arguments by name, you can do it by position, where $0 is the first argument, $1 is second etc..

Having done that, I can now get rid of the variable name on the left . The reference declaration says that the function returns a Double. Now the compiler looks at the closure definition and it sees there’s only one statement in it, so it can make the reasonable assumption that that statement is computing the return value, so we can actually get rid of the return keyword, leaving nothing but the code that’s computing a return value.

[vc_wp_text]
let dup: (Int)-> Double = { Double($0) * 2 }
  [/vc_wp_text]