Created
June 6, 2022 05:37
-
-
Save dfkaye/3edcbbbc4be80edaf51c850863a82ddb to your computer and use it in GitHub Desktop.
switch(true) pattern by Sean Barry
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
// 5 June 2022 | |
// Sean Barry's Using the switch(true) pattern in javascript | |
// https://seanbarry.dev/posts/switch-true-pattern | |
function s(v) { | |
switch(true) { | |
case v === 1: | |
console.log("strictly equals 1") | |
return; | |
case v == 1: | |
console.log("loosely equals 1") | |
return; | |
case !!v: | |
console.log("truthy") | |
return; | |
default: | |
console.error("default"); | |
return v; | |
} | |
} | |
[2,'1',1,0].forEach(v => s(v)); | |
/* | |
truthy | |
loosely equals 1 | |
strictly equals 1 | |
default | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment