1. Assigning a value to the same thing conditionally using ternary operators.
❌
a > b ? foo = 'apple' : foo = 'ball';
✔️
foo = a > b ? 'apple' : 'ball';
2. Assigning the same value to a specific object property conditionally.
❌
c > d ? a.foo = 'apple' : a.bar = 'apple';
✔️
a = { [c > d ? 'foo' : 'bar']: 'apple' };
3. Exporting multiple variables
❌
export const foo;
export const bar;
export const kip;
✔️
export const foo, bar, kip;
4. Declaring and assigning variables from object properties.
❌
const a = foo.x, b = foo.y;
✔️
const { ['x']: a, ['y']: b } = foo;
5. Declaring and assigning variables from array indexes.
❌
let a = foo[0], b = foo[1];
✔️
let [a, b] = foo;
6. Getting multiple elements from the DOM.
❌
const a = document.getElementById('a'),
b = document.getElementById('b'),
c = document.getElementById('c');
d = document.getElementById('d');
✔️
const elements = {};
['a', 'b', 'c', 'd'].forEach(item => elements = {
...elements,
[item]: document.getElementById(item)
});
const { a, b, c, d } = elements;
/*
For this to work your elements ID's must be
able to be valid Javascript variable names
and the names of the variables in which you store
your elements have to match with that elements' ID.
This is good for naming consistency & accesibility.
*/
7. Use logical operators for simple conditionals.
❌
if (foo) {
doSomething();
}
✔️
foo && doSomething();
8. Passing parameters conditionally.
❌
if(!foo){
foo = 'apple';
}
bar(foo, kip);
✔️
bar(foo || 'apple', kip);
9. Dealing with lots of 0`s.
`
❌
const SALARY = 150000000,
TAX = 15000000;
✔️
const SALARY = 15e7,
TAX = 15e6;
``
10. Assigning the same thing to multiple variables.
``
❌
a = d;
b = d;
c = d;
✔️
a = b = c = d;
``
Bonus⭐ (A deugging tip)
Debugging with
console.log()
can be a pain having to write it
over and over again. You can shorten it by object destructuring
assignment.
``
const { ['log']: c } = console;
c("something");
``
Now Instead of having to write out
console.log()
you can just writec()
which is easier to write for
faster debugging.
Latest comments (70)
Most of the time clean code is simply "my code". Performance also takes the back seat lot of the times when trying to write "clean code" and lot of the times you have a take a hit on the readability too.
const { ['log']: c } = console;
c("something");
Oh, wouldn't like to get this in any legacy project. It's easy to search
console.log
string and remove any instances from the code. And that's much harder to find the instances in the case that author suggests.Neat
Thanks. Your examples are really interesting
Sorry...I disagree with many of them..
I agree with one of the other commenters, this is more about more concise code than it is clean code.
Some of these would not fly if I was doing the code review.
Particularly 6 (this is replacing 4 simple assignments by creating a number of intermediate objects, and the code takes more time to grok what's going on).
4 replaces the two assignments with more code, not less, and arguably little performance improvement.
2 is:
a = { [c > d ? 'foo' : 'bar']: 'apple' };
I'd put that into two lines:
const prop = c > d ? 'foo' : 'bar';
a[prop] = 'apple';
Hey man, some of those are great (love the console.log shorthand), thanks for sharing.
I agree with some comments around the cleverness rather than the clearness of some of this examples.
I personally doubt about 7 too.
Despite I am familiar with the && operator, which I think pretty much everyone is familiar with when dealing with layout files (jsx, tsx), I prefer to go with the good old known friend if then -> doSomething();
In general when I write let's say business logic, I prefer to attach to the conditional semantics improved by the word if (and the block of course), which I think is also more legible.
Just a thought.
Cheers
Hey Ibeh, just wanted to say that I respect the way you handle all the criticism. I imagine it must have taken a lot of courage to write your first article, so kudos to your for being open to criticism. It will only make you a better software engineer in the end.
Having said that, my 2 cents would be that some of your examples show a lack of understanding some of the fundamentals of the language, such as the difference between an
expression
and astatement
. Finally as many pointed out, "clean" code and "short" code are not the same thing. My suggestion would be to spend a bit more time reading up on the language itself, as well as the well known "Clean Code" book by Robert C. Martin.Stay safe.
😄 Thank you!
On looking deeper, I find that roughly half of these are plain wrong. It's not even a matter of opinion.
For number 2, this:
assigns 'apple' to
foo
orbar
depending on the values ofc
andd
. It leaves the other keys ofa
alone.This:
reassigns
a
(which means it is not aconst
), wiping out all previous key-value pairs. It's also pretty unreadable. Both mutatea
.They are not equivalent.
Better would be to use the spread operator:
Number 3 is just plain wrong.
const
must be assigned when it is declared, so the example cannot occur in real code. Smart code avoidslet
as much as possible, and if necessary strives to assign at the same time as it is declared. So an actual example would be more like:This is difficult to read (worse if you try to do it on one line). So much cleaner to write:
At a glance I can see exactly how many variables I've declared and assigned and that each is exported and each is not reassignable.
Shorter or terser is not the same thing as cleaner, more intuitive, or more readable. Sometimes duplication is better.
Number 4 is needlessly verbose and difficult to read. This:
Should be this:
Number 5 is OK, but number 6 is pointlessly mutable. Why? Instead of this:
Do this:
The variables are positional, so no reason their names have to match the IDs. You can make them better. You need better variable (and ID) names in general. These are terrible examples.
Number 7: instead of this:
But the full
if
statement is more obviously a guard and more scannable. Don't make terseness the enemy of readability.Number 8 is OK, but number 9 needs work. Who can read this?
How many people can do the math in their head? Few, I bet. But use the underscore and both the magnitude and the difference in magnitudes become clear:
Re number 10, assigning the value of one variable to another is generally something to avoid as it's not clear what you're assigning (unless you've named the variables very well). But even if you're assigning, say, a string, it is better to stack them. This:
Is easily missed and takes a moment to parse. And you probably have to keep reminding yourself that
a
,b
, andc
have the same value. (Why on Earth would you need 3 variables with identical values -- unless you're mutating them, which... just don't.)Much better:
The bonus is half a good idea, and half a bad one. Instead of this:
Do this:
Now you know what it's doing.
I guess posts like this spur discussion, but for the unwary newbie they are strewn with land mines, doing them a disservice. So BEGINNERS BEWARE! Much of what you read online is written by people who haven't really done their homework. Don't let their mistakes be yours.
That's the first thing I noticed when saw the code. Great explanation.
Hi Ibeh! I really like you post. Thank you for sharing it with us. As you see there are lots of people which has another point of view. It’s quite good to debate around what you suggested. Thank you and all the best.
You are welcome! 😄
Some comments may only be visible to logged-in visitors. Sign in to view all comments.