Last active
May 2, 2016 12:26
-
-
Save jnsprnw/e42fd94f2ef25b988df931942ffe76c2 to your computer and use it in GitHub Desktop.
Build a conditional String in JavaScript
This file contains 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
var foo = 'Hello' | |
var bar = 'World' | |
function clean (str) { | |
return str.trim().replace(/\s\s+/g, ' '); | |
} | |
// With ES6 | |
function buildES6 (foo, bar) { | |
return clean(`${foo || ''} ${bar || ''}`); | |
} | |
// Without ES6 | |
function buildWithoutES6 (foo, bar) { | |
return clean((foo || '') + ' ' + (bar || '')); | |
} | |
// With array | |
function buildArray (foo, bar) { | |
var arr = []; | |
arr.push( foo || '', bar || '' ); | |
return arr.join(' '); | |
} | |
// With string concatenation operator | |
function buildConcat (foo, bar) { | |
return clean("" | |
+ ( foo || '' ) | |
+ ' ' | |
+ ( bar || '' )); | |
} | |
console.log(buildES6(foo, bar)); | |
// "Hello World" | |
console.log(buildWithoutES6(foo, bar)); | |
// "Hello World" | |
console.log(buildArray(foo, bar)); | |
// "Hello World" | |
console.log(buildConcat(foo, bar)); | |
// "Hello World" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment