Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bkinsey808/e28effd64ba8e254e5e8f887f32a4b2d to your computer and use it in GitHub Desktop.
Save bkinsey808/e28effd64ba8e254e5e8f887f32a4b2d to your computer and use it in GitHub Desktop.
// suppose I have the following function.
// in this case message is declared as const following the constantly const convention
const TEMPLATE = `Howdy ${PLACEHOLDER}!`
function welcome(name) {
const message = TEMPLATE.replace(PLACEHOLDER, name)
const wordCount = message.split(' ').length
return {message, wordCount}
}
// but let's say we need to add a new feature, now we need to refactor our code
// and declare message with let, because we are mutating it
const SPECIAL_GUEST = 'Warren'
function welcome(name) {
const message = TEMPLATE.replace(PLACEHOLDER, name)
if (name === SPECIAL_GUEST) {
// Wait! You can't change a `const` like this!
message += ' You old so and so'
}
const wordCount = message.split(' ').length
return {message, wordCount}
}
// in my opinion this is still not a really compelling argument.
// personally, i prefer string templates and ternary operators any way,
// code below may be slightly more verbose, but I find it more clear to put the entire
// declaration together up front rather than re-assigning.
function welcome(name) {
const message = `${TEMPLATE.replace(PLACEHOLDER, name)}${
name === SPECIAL_GUEST
? ' You old so and so'
: ''
}`
const wordCount = message.split(' ').length
return {message, wordCount};
}
// and of course if that were too complicated and we wanted to break it apart a little:
function welcome(name) {
const optionalMessagePart = name === SPECIAL_GUEST
? ' You old so and so'
: ''
const message = `${TEMPLATE.replace(PLACEHOLDER, name)}${optionalMessagePart}`
const wordCount = message.split(' ').length
return {message, wordCount}
}
// the advantage of the above code is that it uses more named consts,
// which i find helpful for writing self-documenting code. To each their own.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment