Hey there DEV.to community!
Although this article is titled as a JavaScript article some of the tips and points in this article can be also applicable for other programming languages as well.
I'm not considering myself as a pro programmer and these are only some stuff I learnt during my career mostly as a JavaScript developer so I beg your pardon since I'm a newbie programmer amongst you.
Cover image credit goes to this video on YouTube: https://www.youtube.com/watch?v=Cn1BqQ7VXc0, I love Minecraft and watch a lot of these Noob vs Pro videos about Minecraft. xD
Bracket-less
When using conditional statements or loops in your code you most likely put brackets to define the code to be executed respectively:
if(condition) {
console.log('Yes')
} else {
console.log('No')
}
or like:
for(let i = 0; i < 10; i++) {
console.log(i)
}
In case you only have one statement to be executed you can drop the brackets, but be sure you only have one statement:
if (condition) console.log('Yes')
else console.log('No')
and:
for (let i = 0; i < 10; i++) console.log(i)
Return statement
If you are writing a function that checks many conditions and returns a value based on that you probably do something like this as a new programmer:
function numberKind(n) {
if (n > 0) {
return 'positive'
} else {
if(n < 0) {
return 'negative'
} else {
return 'zero'
}
}
}
As a somewhat experienced programmer, you'll use else if
instead of nested conditions:
function numberKind(n) {
if (n > 0) {
return 'positive'
} else if (n < 0) {
return 'negative'
} else {
return 'zero'
}
}
Here is the next tip, remember the code after a return
statement is unreachable meaning that it won't be executed so we can use this and the previous tip to clean up our code:
function numberKind(n) {
if(n > 0) return 'positive'
else if (n < 0) return 'negative'
return 'zero'
}
Consider the probable errors
Junior developers mostly forget about errors than can be fixed easily, in case of JavaScript this usually involves type errors since JavaScript is one of the most easy-going languages when it comes to data types.
Having the function below which sums up two numbers, pretty simple yes?
function sum(x, y) {
return x + y
}
Works perfectly fine when we pass two numbers as our arguments:
console.log(sum(5, 9)) // 14
But what if we pass one (or both) of arguments as a string?
console.log(sum("5", 9)) // 59
Since JavaScript uses +
operator both in a mathematical way (arithmetic) and as a concatenation operator it will concatenate two arguments instead of summing them up.
What to do is simple, to check if both of our arguments are numbers for sure:
function sum(x, y) {
if(!(typeof x === 'number' && typeof y === 'number')) return
return x + y
}
Combining with the previous tip I returned nothing which means returning undefined and the rest of the code won't be reachable.
Working with arrays
Working with arrays is one of the most common things you are going to do as a developer and iterating through them is the most common of it.
Programmers usually iterate through an array using a for loop like this:
let fruits = ['orange', 'apple', 'banana']
for(let i = 0; i < fruits.length; i++) console.log(fruits[i])
But JavaScript has a simpler way which is a prototype method for arrays. You can use the forEach
method to iterate through an array:
fruits.forEach(item => console.log(item))
You want to access your index, just like i
, you can pass a second argument to your callback which will be your index:
fruits.forEach((item, index) => console.log(index))
Given that you need to get the average of all the numbers in an array, you can either loop through it and sum all of the values up and then divide it by the count of the elements in the array (pretty normal way) or you can choose a more simple way by using the reduce
method to accumulate your numbers:
let numbers = [100, 250, 300, 500]
let sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue) // 1150
Pretty simple and neat. Now you can divide it by the count:
let avg = numbers.reduce((a, c) => a + c) / numbers.length
There are more tips and tricks in the article below:
Tell me if I missed something that you want me to add to the article or if I did something wrong.
I hope you enjoyed!
Top comments (3)
I'll add, in any bracketed language, no-bracket conditionals are an utter style sin unless they're on the same line, simply because of how easy it is to not notice the lack of brackets and add another line!
BAD:
You're now at high risk of forgetting those brackets are missing and just adding another line:
Oops, why is my program crashing all the time now? Missing brackets. I just ninja'd myself right into a brick wall.
However, what you showed is usually acceptable...
Regardless, this also becomes a "cleverness" trap, as that "pro" code can easily become unreadable, even respecting the one-line rule. Terrible example:
Heaven help you if you get a lambda or iteration involved.
After functionality, readability and maintainability matter above all else!
The real difference between a newbie and a pro is not found in how clever the code can be; it's in knowing when to use the syntactic sugar, and when to stick with the "boring" conventions for the sake of good code.
P.S. I'm a C++ (and Python) dev, not a JS dev, but the style rules are pretty much universal across all ALGOL-inspired languages.
Another one of those "pro-dev" things that can be a bit confusing is this for only positive conditionals:
I can never make my mind up if I like it - I do write that when debugging, but pretty much never in "real code"
It works with everything apart from assignment which requires brackets
Again not advocating, but it is out there in people's code.
Thank goodness of optional chaining though (thanks babel) so my if's can go from:
to
IMO this are just bad advice, making code shorter don't make it better, if you would be Pro you will know that. If you check ESLint there are rules to always have one expression per line and always use curly braces. This just make code harder to read and harder to edit if the code is in version control.