Migrating to modern javascript

From NEOSYS Technical Support Wiki
Revision as of 04:59, 22 March 2020 by Arvind (talk | contribs) (Arvind moved page MIgrating to modern javascript to Migrating to modern javascript: Capitalisation error in title)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

In 2015 the new "ES6" version of javascript introduced a many fundamental and routine improvements in the language.

The concept of "modules" allows the packaging up a group of associated functions so that they have their own module scope variables that do not interfere with the standard global variables. NEOSYS may be refactored to take advantage of the protection that this brings and it will allow the introduction of industry standard libraries without those libraries conflicting with NEOSYS scripts. NEOSYS currently does not use any libraries since it was created long before any javascript libraries existed.

On the routine programming side this page will contain a list of the possible improvements in programming style that can be used when adding new code to the NEOSYS javascript code base.

Using map function instead of time honoured "for loop over array"

  • The purpose of the new "map" function is to convert every element of an array by using a given function. map doesn't actually touch the old array but rather outputs a new array. If you immediately assign the output of the map function into the old array then the end result is a conversion, not a creation.
  • The old ugly "for loop" syntax is replaced by the new beautiful "map" syntax. Both are equally incomprehensible in plain language.
  • Think of the "acno => {" is the new style shorthand meaning "function anonymous(acno) {"
  • "=>" is known as an "arrow function" in javascript. In the rest of the programming world they are known as "lamda" function or in plain language "anonymous functions" since they have no function name.
Old New
for (var acnon = 0; acnon < acnos.length; ++acnon) {
    var acno = acnos[acnon].split(sm)
    if (acno[1])
        acno = acno[1]
    else if (acno[0]) {
        acno = "." + acno[0]
    } else {
        acno = ''
    acnos[acnon] = acno
acnos = acnos.map(acno => {
    const acno2 = acno.neosyssplit(sm)
    if (acno2[1])
        return acno2[1]
    else if (acno2[0]) {
        //return "."+acno2[1]
        return "." + acno2[0]
    } else {
        return ''