Some while ago I've written this article Small Javascript things I did not know until today. Meanwhile, I've discovered a few more small Js tips I would like to share with you:
1. If you have a return
statement in a finally
block it will overwrite other returns
function thisFunctionReturnsB() {
try {
throw new Error( 'Foo' );
} catch( e ) {
return 'A';
} finally {
return 'B';
}
}
More details in this article written by Jake Archibald.
2. We can use numbers separators to improve readability
const myFirstMillion = 1_000_000;
console.log(myFirstMillion); // 1000000
3. The default
case does not need to be last in a switch
statement
Even if we see the default
as the last option in a switch case, and somehow is also a bit logical to put it so, also the following is a valid syntax:
switch (foo) {
case 1:
// do something...
break;
default:
// do something...
break;
case 3:
// do something...
break;
}
More details here.
Btw, you can also match multiple values in a switch statement.
4. Easily convert from a string to string to a number
const str = '404';
console.log(+str) // 404;
Before I was using the parseInt
function.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.