2017-05-01

LET it be

In my previous post Some thoughts on being a polyglot developer I pondered about the usage of arrow constructs in programming languages. This time I will reflect on the let keyword.

As you know, I love home computers. So, let’s (ah, no pun intended) start with them. The following screenshot, by the way, shows the Oric emulator Oricutron by Peter Gordon.

Screenshot of the Oric emulator Oricutron by Peter Gordon

Most (but certainly not all) home computers offered a builtin BASIC interpreter and a (full screen) editor. As BASIC aimed to be easily learnable and understanable, the language sounds like short english sentences. For example, to assign a value to a variable, one might say Let A be Hello World. This translates to let a$ = “Hello World”. The dollar sign is needed to represent sequences of characters.

Other languages use let for assignment, too. There is an interesting question In what programming language did “let” first appear? on Software Engineering. Well. So far, so good. But we don’t use BASIC, do we?

Winking smile

ES6 brought let to the web. Instead of var we can now say

class black {}
let orange = new black();

The difference between both keywords is scoping. var is scoped to the nearest function block and let is scoped to the nearest enclosing block (which can be smaller than a function block). Both are global if the are outside any block. Variables declared with let are not accessible before they have been declared in their enclosing block. Further assignments to an already declared variable (using let) are valid. Why am I emphasizing this? Let us take a look at Swift. This language knows let, too. However assignments can be made only once. As you can see in the following screenshot, for non-constant-like usages we need to take var instead.

A Swift session at https://iswift.org/playground

The Dart programming language is optionally typed. That means that we can either write

var a = 42;
print(a.runtimeType);

or

int a = 42;
print(a.runtimeType);

Both result in int being printed.

To declare constants, Dart has the const keyword:

const a = 42;
print(a.runtimeType);

Again, int is printed. Dart offers compiletime constants, so const a = new Random().nextInt(10); is not valid. A similar expression in ES6, however, is valid:

const c2 = Math.random();

The same is true for Swift’s let. The assigned value can be computed during runtime.

let a = random()
print(a);

Speaking of const, remember that const is a reserved keyword in Java, but currently not used. C#, on the other hand, does:

public const double Pi = 3.14159;
Well, that has been enough of brain dance for now. 
Smile
Happy coding!

No comments:

Post a Comment