Skip to content

Instantly share code, notes, and snippets.

@jasonrhodes
Last active October 26, 2017 16:09
Show Gist options
  • Save jasonrhodes/acedccb46ceaeba2f8f3406b4f0aa0a0 to your computer and use it in GitHub Desktop.
Save jasonrhodes/acedccb46ceaeba2f8f3406b4f0aa0a0 to your computer and use it in GitHub Desktop.
Looking at using let and const vs using var, semantically
function getNameWithLetAndConst(options) {
// `name` scoped to its nearest parent block (here: the function-block)
let name = 'Jill'
if (options.test) {
// `combined` is scoped to its nearest parent block (here: the if-block)
// because of how block-scoping works, `name` is also available here
const combined = `${name}-tested`
if (options.someCondition) {
// the outer `name` is mutated (which let allows)
name = combined
}
}
// this will be `name` value, conditionally mutated within the nested if blocks
return name
}
function getNameWithVar(options) {
// `name` is scoped to its nearest parent function
// QUESTION: how is this clearer than using `let` or `const` here?
var name = 'Jill'
if (options.test) {
const combined = `${name}-tested`
if (options.someCondition) {
name = combined
}
}
return name
}
// this is the only reason I can think of that using `var` would be more meaningful:
function omg(a, b) {
if (a) {
var value = a
}
if (b) {
value = value ? value + b : b
}
return value
}
// except this is really confusing to look at (imo) and would almost certainly be rewritten as:
function omg(a, b) {
var value
if (a) {
value = a
}
if (b) {
value = value ? value + b : b
}
return value
}
// in which case why not just write:
function omg(a, b) {
let value
if (a) {
value = a
}
if (b) {
value = value ? value + b : b
}
return value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment