Hacker News new | ask | show | jobs
by elviejo 3259 days ago
For the same reason every variable in JavaScript is global by default... I.e. I don't have a clue how that could seem like a good idea.
3 comments

That's not how JavaScript works. Variable declarations are hoisted to the start of the enclosing function scope and only undeclared variables are global by default.

But yes it seems pretty asinine to use global by default for (not so) smart contracts.

Another way of describing that is that variables are global (scoped to the lobby, to borrow a term from the languages which came before JavaScript) unless explicitly marked with the "var" keyword, which has semantics that some languages might have chosen to give the name "local". Like: your entire premise that a variable is only the declared variables makes no sense to me as someone who teaches college-level classes in programming languages. In Python variables default to local unless marked "global". In JavaScript, variables default to captured via scope unless marked "var".
And even that undeclared-are-global thing is gone in modern js. It's explicitly an error in strict mode.
Well, if they are global when they are undeclared, that pretty much means they are global by default. Maybe a better way of putting it would be "js variables are declared global by default, when unspecified and not using strict mode".

Anyway, I think parent's point was to say this behavior already has been seen in javascript. Actually, it may even be inherited from javascript. When I first looked at solidity last year, I was under the impression it was a modified version of javascript, like unity3d's one. Nowadays, solidity landing page reads "high-level language whose syntax is similar to that of JavaScript", so not sure if it still is (or has ever been, for the matter) derived from something like v8 or rhino.

The reason for that choice seems not far fetched : it's not uncommon, when wanting to add scripting to something, to go with javascript, since it's arguably the most known language, developers knowing "<their main language> and javascript", especially webdevs (a blockchain app project, lisk, even made html/css/js the defacto mean to build apps). Of course, fintech is an industry where the usual values from webdev (release early, release often) have disastrous results.

In javaScript, the following lines does different things:

  "use strict";
  foo = 1;
  var bar = 1;
"foo=1" changes the variable foo (this is very useful) and "var bar=1" creates variable bar and adds it to the function/lexical scope. If the variable foo is not created/declared, it will throw an error! But without "use strict", "foo=1" would add variable foo to the global scope! Which might create unexpected bugs if you are used to other languages that does the sane thing and adds it to the local function/lexical scope. So I suggest to always "use strict" !
Sounds like you don't know anything about JavaScript.