2024-02-10

javascript programming

see also javascript semicolons

libraries

how to use coffeescript for exec command-line scripts

#!/usr/bin/coffee

coffeescript-code ...

it is also possible to use a relative path to a node_modules directory

#!node_modules/bin/coffee

if this is not a full path then the script can only be executed from one directory

information encapsulation

with classes

especially for user interface related code, which browser javascript often is, one approach is to divide a page into areas or widgets, and have a class for that area for the associated features. the classes can have "ready" properties for when the initialise asynchronously and can take dependent area object references as arguments on construction.

common functions

  • loadDomElements: get dom element from selectors and store with useful keys in this.dom = {}
  • addEventListeners: one function that sets up all events for the widget

without classes

to ease development and maintenance by making it easier to guess side-effects and execution flow with information encapsulation, and to avoid top-level namespace conflicts (trying to use two different bindings with the same name) and confusion created by unnecessary global variables, javascript has function local scope that can be used to create encapsulate bindings* when not using something like modulejs (modulejs only abstracts on the following), code can be wrapped inside a function like this

;(function () {
  // all the files code ...
})()

this is an anonymous-function application - a function without a name is defined and immediately called by specifying (). the ";" avoids syntax errors when semicolons are avoided or forgotten especially when files are concatenated at some point.

or

someprefix.somemodule = (function () {
  // code ...
  return {
    exported_name: variable_name
    // ...
  }
})()

this creates an interface of accessible functions which excludes the inner utility functions and variables that may not be externally/generally applicable, in a scope where local bindings do not affect the top-level (if the var keyword is used consistently). application parts should be available as objects in the root object, which is usually "window" in browsers. in nodejs it has a different name

window.{module-name}.{sub-module-name}.{variable_name}

bindings are then accessible with

module_name.sub_module_name.variable_name

and can be shortened locally like

var shortname = module_name.sub_module_name.variable_name