início

my personal approach on using let, const and var in javascript

Since these names can be used interchangeably almost everywhere and there are a lot of people asking and searching on the internet on how to use them (myself included until some weeks ago), I developed a personal approach that uses the declarations mostly as readability and code-sense sugar, for helping my mind, instead of expecting them to add physical value to the programs.


let is only for short-lived variables, defined at a single line and not changed after. Generally those variables which are there only to decrease the amount of typing. For example:

for (let key in something) {
  /* we could use `something[key]` for this entire block,
     but it would be too much letters and not good for the
     fingers or the eyes, so we use a radically temporary variable
  */
  let value = something[key]
  ...
}

const for all names known to be constant across the entire module. Not including locally constant values. The value in the example above, for example, is constant in its scope and could be declared with const, but since there are many iterations and for each one there’s a value with same name, “value”, that could trick the reader into thinking value is always the same. Modules and functions are the best example of const variables:

const PouchDB = require('pouchdb')
const instantiateDB = function () {}
const codes = {
  23: 'atc',
  43: 'qwx',
  77: 'oxi'
}

var for everything that may or not be variable. Names that may confuse people reading the code, even if they are constant locally, and are not suitable for let (i.e., they are not completed in a simple direct declaration) apply for being declared with var. For example:

var output = '\n'
lines.forEach(line => {
  output += '  '
  output += line.trim()
  output += '\n'
})
output += '\n---'

for (let parent in parents) {
  var definitions = {}
  definitions.name = getName(parent)
  definitions.config = {}
  definitions.parent = parent
}

Links to this page

This article on Nostr

naddr1qqyrxcmxvyun2vr9qyghwumn8ghj7enfv96x5ctx9e3k7mgzyqalp33lewf5vdq847t6te0wvnags0gs0mu72kz8938tn24wlfze6qcyqqq823cvj9k9l