Last active
October 26, 2017 16:09
-
-
Save jasonrhodes/acedccb46ceaeba2f8f3406b4f0aa0a0 to your computer and use it in GitHub Desktop.
Looking at using let and const vs using var, semantically
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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