Monday, October 23, 2017

Template Strings in ES6

With the new version of JavaScript (ECMAScript 2015+), new String functionalities — very convenient for ImageJ scripts — are available. Take a tour about these new features.

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

1. Reminder: A String?

In Javascript, a text is defined as a String delimited by single quotes or doubles quotes like this...

let i = "this is a string of characters";
let j = 'This is also a string delimited by single quotes'; 

In ImageJ scripts, strings are everywhere especially in the arguments of the function. For example, the following script resizes the active image as a square of 100x100 pixels.

let imp=IJ.getImage();, "Size...", "width=100 height=100 interpolation=Bilinear");

If you want to set the output size in a variable, you have to split your string in parts and then concatenate the various pieces of your string by using the + operator like this:

let imp=IJ.getImage();
let size=100; 
let params =  "width=" + size + " height=" + size + " interpolation=Bilinear";
IJ.log(params); //  ← "width=100 height=100 interpolation=Bilinear", "Size...", params);

The concatenation is always a tricky operation because...
  • you need to be careful about the number of + signs
  • you must not forget the spaces acting as separators in the string between the various ImageJ pairs keyword/values. (width=100<space>height=100...).

2. The template strings

The template strings can be single-line (like previously in JS5) and multi-line (new!!) and they are using back quotes   ` .

let str = `This is a string`;
let str2 = `This is
a multi-line

Moreover, the most powerful novelty with these template strings is the ability to easily include in the text values (stored in variables).
The syntax is a dollar sign $ followed by curly brackets enclosing the variable name like this...

For example,

let height=324;
IJ.log(`The Eiffel tower is ${height} meters high.`);

This is extremely useful for us, because our script is now much more readable.

let imp=IJ.getImage();
let size=100;
// Template String
let params = `width=${size} height=${size} interpolation=Bilinear`;
IJ.log(params); //  ← "width=100 height=100 interpolation=Bilinear", "Size...", params);

And without all the comments and intermediate steps, the code becomes...

let imp=IJ.getImage();
let size=100;, "Size...", `width=${size} height=${size} interpolation=Bilinear`);

Neat and concise. Great!!

Thank you for reading.

<<  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