TIL of this switch shorthand
POSTED ON:
TAGS: javascript
This snippet is so freakin' awesome.
Say you had a switch statement fire a function.
// Longhand
switch (data) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break;
// And so on...
}
// Shorthand
var data = {
1: test1,
2: test2,
3: test
};
data[anything] && data[anything]();
The shorthand does the following:
- Check if the value exists in the object
- then fires the value as a function
data[anything]()
via Blessing Hirwa's 17 Javascript optimization tips to know in 2021
Related TILs
Tagged: javascript