You might be using Javascript development for a long time but sometimes you might not be updated with newest beautiful features that it offers whic...
For further actions, you may consider blocking this person and/or reporting abuse
Great list, just one thing in tip number 6
foreach Loop Shorthand
. Afor...in
is not the same as afor...of
loop!With the
for...in
you iterate over the object its properties. For thefor...in
with an array, you'll get the index value.With the
for...of
you iterate over all elements inside the array, soi
will be the element and not the index.Thanks for pointing that out, @estruyf . The following deno session demonstrates
That's a good list, just one thing I would like to mention in tips 4 and 5. It's better to check if the value is
null
orundefined
usingNullish Coalescing Operator (??)
since for some cases it might be an unexpected behavior:So, in that case
??
will work as expectedThank you for your work!
In some cases
Nullish Coalescing Operator
is the best choice. Thanks for the assistance.There are some good tips here! I hadn't come across the numeric separators, and it's great to see a
replaceAll
method after years of having to reach for a regex for that simple task!One thing I'd note is being careful with falsey checks, in #3 your
Longhand
version would allow any value other than those you've specified. TheShorthand
version would also fail the value0
andfalse
. If you're working with numbers, that can cause tricky to find bugs later on.The other bit may be more of a preference but nested ternary statements or function calls via a ternary (as in #8) are quite hard to read compared to the "long" alternative and that could make it far more susceptible to bugs and harder to find it when it comes up. I'd far prefer 5 clear lines of code and let my minifier convert it to a one liner before I push my code live!
Anyway, great list! Thanks!
+1 I would advise to not nest two or more ternary operations. Also avoid it entirely if it means you'll get a single like 100+ characters long, or 120 depending on preference. But more than that usually means your code will be hard to read
When I have nested ternaries, I format them this way:
ˋˋˋjavascript
let test2 = (x > 100) ? 'greater 100'
: (x < 50) ? 'less 50'
: 'between 50 and 100';
ˋˋˋ
IMHO this reads quite nicely, since every condition is paired with the corresponding result, similar to a ˋswitchˋ block or an if-elseif-else chain.
Still, you shouldn‘t push it too far. When the conditions or value expressions get long, this becomes unreadable as well.
I agree, it reads nicely enough, but what's the benefit to this over:
It's dealers choice with regard to using an
else
statement or default assignment as above and the formatting isn't my cup of tea, but it's still nevertheless the same statement on three lines. IMO, this is still way clearer and I don't see any downside to it.Long chained tenary operators are not good.
nice~
The code is used by the machine,and another function is to show it to people .
We have to make some trade-offs
This list contains some good tips. Using an object in place of a switch statement is one of my favorite tricks to use. For your first tip, you may want to also consider using an object, since Array.includes is at worst a O(n) operation compared to an object lookup, which is a O(1) operation.
Code from the article, the second example:
It could be shorter, like the following:
It could be not easy to read or understand several ternary operators in one and the same statement sometimes
Shorter not means better!
When I hear optimization I think making the file size smaller and having the code run faster, not refactors that make the code a lot cleaner.
True, this title definitely needs to be renamed to Clean Code tips as it's quite helpful.
These tips are really good.
Generally, I feel that using switch statements is most of the time not necessary, and using an object is very much a good alternative and one that is commonly available.
That being said, I think number 9 is misleading. You stated that objects are shorthand for switch statements, and they aren't. They're an alternative you could do sometimes. But saying an object is "shorthand" for a switch statement is definitely not correct.
There are definitely situations where you would need a switch statement instead of an object (IE, the object cannot replace the switch statement). A shorthand of syntax should be able to replace the original in all situations.
I think just modifying the text to state that its not a shorthand but an alternative that's commonly available would be good.
this is for making clear the use of for...in and for...of
In JavaScript, for...in and for...of are both loop constructs used to iterate over data structures, but they are used for different purposes and work with different types of collections.
for...in:
The for...in loop is used to iterate over the properties of an object. It works with enumerable properties, which include both own properties and inherited properties from the object's prototype chain.
for (variable in object) {
// code to be executed
}
Usage:
`const person = {
name: 'fadhili',
age: 30,
city: ''rwanda
};
for (let key in person) {
console.log(key + ': ' + person[key]);
}
// that will loop in object keys(name, age, city)
//it will output object key: object value`
for...of:
The for...of loop is used to iterate over the elements of an iterable object. Iterable objects include arrays, strings, sets, maps, and other data structures that have a defined iteration protocol.
for (variable of iterable) {
// code to be executed
}
Usage:
`const colors = ['red', 'green', 'blue'];
for (let color of colors) {
console.log(color);
}
//In this example, for...of is used to loop through the elements ('red', 'green', 'blue') of the colors array.`
Key Differences:
1. Iterating Over:
for...in: Iterates over object properties.
for...of: Iterates over iterable values (e.g., elements in an array).
2. Iteration Variables:
for...in: Iterates over property names (keys).
for...of: Iterates over values.
3. Suitable for:
for...in: Best used for objects and when you need to enumerate object properties.
for...of: Best used for iterating over iterable collections like arrays and strings.
4. Works With:
for...in: Works with objects, including their inherited properties.
for...of: Works with iterables, including arrays, strings, sets, maps, etc.
5. Order of Iteration:
for...in: The order of iteration is not guaranteed and may vary between JavaScript engines.
for...of: Iterates in the order the elements appear in the collection.
6. Compatibility:
for...in: Supported in all modern browsers and older versions of JavaScript.
for...of: Introduced in ES6 and may not be supported in older browsers without
7. transpilation.
Remember to use for...in when you need to iterate over object properties and for...of when you're working with iterable collections like arrays or strings.
real experience!!!
I am getting " Uncaught SyntaxError: expected expression, got keyword 'throw' " error while declaring this statement (!func) && throw new Error('Invalid value ' + type);
which trick were you trying?
I just type code you mentioned on console and got this error
which code? On which trick number?
I typed the code of point no 12 on console
Those are great tips, and they improve readability a lot. Thanks for sharing!
Glad to hear that.
In the part 13.Object.entries()
Object.entries
returns anarray of array
and not anarray of object
as mentioned.Good job!
Good list but please don't use this
(!func) && throw new Error('Invalid value ' + type); func();
it's unreadable when you scan the code
Great list of tips !
About arrow function, if I'm not wrong, you can lose the paranthesis (these should be brackets no ?) here :
//shorthand
getArea = diameter => Math.PI * diameter;
That's also correct. I just wanted everyone to spot the difference between the tow functions.
Thank you @blessing
Great work!!
Thanks mate.
Nice topic
Thanks mate.
This list is most important as a developer. Many many thanks for pointing that list.
Glad you liked it mate 🙂
Thanks for those tips! I already love them and will thankfully implement them in future projects, cheers!
PS: I am missing a number 10? 🕵️♂️
Thanks for the correction.
Thank you for the post. There is some gold.
😃
Dude! This is awesome, these are noice! 🤘
Loved the switch shorthand
when I first saw it I also felt happy.
Lovely... much creativity, especially no. 8 and 9. It's just so beautiful. Thanks for sharing
Good list!
// Longhand
if (first !== null || first !== undefined || first !== '') {
let second = first;
}
// Shorthand
let second = first|| '';
its not the same. first could be "0" or "[]".
I hope spread operator was included.
Great list. I enjoyed the Lookup Conditions Shorthand.
Nice, good post!
love this content, thanks for sharing!
I'm glad you liked it.
thanks bro
It really saved me a headache. Thank me later.