Friday, October 20, 2017

Variables in ECMAScript



With the new version of JavaScript (ECMAScript 2015+), the variables are now defined by three distinct keywords: var, let, and const. Why? That's what we'll see in this post.



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

1. Introduction

In Javascript 5, the variables were defined by the keyword var like this...

var i = 123;

But with ES2015+, we have now two other keywords: let and const to define local and constant variables, respectively.

2. Local variables: keyword let

let i = 234;
let str = 'This is a string';
let arr = ['This', 'is', 'an', 'array', 'of', 'strings'];

A local variable is only visible in a block of code delimited by curly brackets. For example, the local variable i is only visible in the loop but not outside (this is a new behavior compared to JS5 and is more bug safe).

for (let i = 0; i < 10; i++) {
  IJ.log(i);
}
IJ.log(i) // ← ERROR: Unknown variable

In this other script, there are two variables i. One is outside the loop, the other is inside. Because they are both declared as local, the inner i is only visible within the loop, the outside i is not impacted by the inner i. Thus, they are not related and act independently.

IJ.log('\\Clear');
let i=123;
for (let i=0; i<5; i++) {
  IJ.log('Loop ' +i); // ← 0, 1, 2, 3 and 4 successively
}
IJ.log('global ' + i); // ← 123

3. Constant variables: keyword const

The const keyword is used to declare constant variables.

const my_constant = 1234;
my_constant = 4321; // ERROR: unauthorized assignment

4. What about keyword var?

The keyword var is now reserved to global variables, but they are dangerous to use. Look at this script (same as above, but I replace the let by var). Now, what is the value of i?

IJ.log('\\Clear');
var i=123;
for (var i=0; i<5; i++) {
  IJ.log('Loop ' +i); // ← 0, 1, 2, 3 and 4 successively
}
IJ.log('global ' + i); // ← 5
Note: My advice is to replace all the keywords var by let because var corresponds to global variables - variable visible everywhere in the script - and its use could trigger bugs that could be tricky to find.

5. Types and variables

In ES6, the main types we are using in scripts for ImageJ are:
  • numbers including integer, floating-point numbers.
  • strings of characters
  • arrays
  • objects
let i = 1; // this is a number
let j = 3.14; // This is also a number
let k = 10*2; // This is also a number equal to 20
let i ="Hello"; // This is a string
let j = 'World!!'; // This is also a string
let i ="Hello"; 
let j = i;
IJ.log(j); // Display Hello 
let i = "Hi! "; 
let j = "John"; 
let k = i + j; 
IJ.log(k); // Display Hi! John 

<<  Previous: Config. ES6 Next: Template Strings  >>

6. Other crazybiocomputing posts

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

No comments:

Post a Comment