Tuesday, January 2, 2018

Functions in ECMAScript



Functions have a central role in JavaScript (ECMAScript 2015+),this is important to know how to use them...



Updated for  ECMAScript2015+, it requires at least version ImageJ 1.51r and Java 9. See this post for update [Link].

1. Reminder: A Function?

In JavaScript, a function is defined by the keyword function followed by the function name and parentheses containing the arguments if required.
In the example below, the function hello() takes no argument and returns the String 'Hello World!'. To use/call it, just type hello() in the script.


function hello() {
  return 'Hello World!';
}

IJ.log(hello() ); //  ← Hello World!

Functions are useful to structure your code in independent blocks. There are some useful habits to write good functions:
  • Functions must return a value (number, string, array, object like image, etc.)
  • Functions must not modify the argument(s)

Here is an example of a bad function. It does not return anything and the input ImagePlus imp is modified by the plugin "Size..."

function resize(imp,size) {
  IJ.run(imp, "Size...", `width=${size} height=${size} interpolation=Bilinear`);
}


However, this one is better:

function rescale(imp,size) {
  let params = `x=- y=- width=${size} height=${size} create interpolation=Bilinear`;
  IJ.run(imp, "Scale...", params);
  let output = IJ.getImage();
  return output;
}

and you can use it like that...

let imp = IJ.getImage();
let small_imp = rescale(imp,100);
IJ.log(small_imp.getTitle());

2. Anonymous functions

It is possible to define function without names.

const hello = function() {
  return 'Hello World!';
}
IJ.log(hello() ); //  ← Hello World!
Some Explanations, here...

3. Arrow functions

It is possible to define anonymous functions with a simplified syntax:
  • no keyword function
  • the keyword return is replaced by a fat arrow =>

And the code becomes...

const hello = () => 'Hello World!';

IJ.log(hello() ); //  ← Hello World!


Hope that helps.

<<  Previous: Variables Next: Functions  >>

3. Other crazybiocomputing posts

Further readings are available in ...
  • Programming in JavaScript Series  [Link]
  • JavaScript/ECMAScript TOC [Link]

No comments:

Post a Comment