1570246901
JavaScript has its origins in the early web. Starting out as a scripting language, it has now evolved into a fully fledged programming language with support for server-side execution.
Modern web applications rely heavily on JavaScript, especially single-page applications (SPAs). With emerging frameworks like React, AngularJS, and Vue.js, web apps are mainly built with JavaScript.
Scaling these applications — frontend equally as backend — can be quite tricky. With a mediocre setup, you will eventually hit limitations and get lost in a sea of confusion. I want to share a couple of small tips that will help you write clean code in an efficient way.
This article is geared towards JavaScript developers of any skill level. However, developers with at least intermediate knowledge of JavaScript will benefit most from these tips.
The most important thing I can recommend to keep a codebase clean and readable is having specific chunks of logic (usually functions) separated by topic. If you write a function, the function should default to having only one purpose and should not do multiple things at once.
Also, you should avoid causing side effects, meaning in most cases, you should not change anything that is declared outside your function. You receive data into functions with parameters; everything else should not be accessed. If you wish to get something out of the function, return
new values.
Of course, you can group multiple functions into one module (and/or class, if you wish) if these functions are used in a similar way or do similar things. For example, if you have many different calculations to do, split them up into isolated steps (functions) that you can chain. However, these functions can all be declared in one file (module). Here is the example in JavaScript:
function add(a, b) {
return a + b
}
function subtract(a, b) {
return a - b
}
module.exports = {
add,
subtract
}
const { add, subtract } = require('./calculations')
console.log(subtract(5, add(3, 2))
If you are writing frontend JavaScript, definitely make use of default exports for the most important items and named exports for secondary items.
When declaring a function, you should always prefer multiple parameters over one parameter that expects an object:
// GOOD
function displayUser(firstName, lastName, age) {
console.log(`This is ${firstName} ${lastName}. She is ${age} years old.`)
}
// BAD
function displayUser(user) {
console.log(`This is ${user.firstName} ${user.lastName}. She is ${user.age} years old.`)
}
The reason behind this is that you know exactly what you need to pass to the function when you look at the first line of the function declaration.
Even though functions should be limited in size — doing only one job — it may happen that functions grow bigger in size. Scanning through the function body for the variables you need to pass (that are nested inside an object) will take you more time. Sometimes it might seem easier to just use the whole object and pass it to the function, but to scale your application, this setup will definitely help.
There is a certain point where declaring specific parameters does not make sense. For me, it is above four or five function parameters. If your function grows that big, you should pivot to use object parameters.
The main reason here is that parameters need to be passed in a specific order. If you have optional parameters, you need to pass undefined
or null
. With object parameters, you can simply pass the whole object, where order and undefined
values do not matter.
Destructuring is a nice tool that was introduced with ES6. It lets you grab specific fields from an object and assign it to a variable immediately. You can use this for any kind of object or module.
// EXAMPLE FOR MODULES
const { add, subtract } = require('./calculations')
It does make sense to only import the functions you need to use in your file instead of the whole module, and then access the specific functions from it. Similarly, when you decide that you definitely need an object as function parameter, use destructuring as well. This will still give you the overview of what is needed inside the function:
function logCountry({name, code, language, currency, population, continent}) {
let msg = `The official language of ${name} `
if(code) msg += `(${code}) `
msg += `is ${language}. ${population} inhabitants pay in ${currency}.`
if(contintent) msg += ` The country is located in ${continent}`
}
logCountry({
name: 'Germany',
code: 'DE',
language 'german',
currency: 'Euro',
population: '82 Million',
})
logCountry({
name: 'China',
language 'mandarin',
currency: 'Renminbi',
population: '1.4 Billion',
continent: 'Asia',
})
As you can see, I still know what I need to pass to the function — even if it is wrapped in an object. To solve the problem of knowing what is required, see the next tip!
(By the way, this also works for React functional components.)
Default values for destructuring or even basic function parameters are very useful. Firstly, they give you an example of what value you can pass to the function. Secondly, you can indicate which values are required and which are not. Using the previous example, the full setup for the function could look like this:
function logCountry({
name = 'United States',
code,
language = 'English',
currency = 'USD',
population = '327 Million',
continent,
}) {
let msg = `The official language of ${name} `
if(code) msg += `(${code}) `
msg += `is ${language}. ${population} inhabitants pay in ${currency}.`
if(contintent) msg += ` The country is located in ${continent}`
}
logCountry({
name: 'Germany',
code: 'DE',
language 'german',
currency: 'Euro',
population: '82 Million',
})
logCountry({
name: 'China',
language 'mandarin',
currency: 'Renminbi',
population: '1.4 Billion',
continent: 'Asia',
})
Obviously, sometimes you might not want to use default values and instead throw an error if you do not pass a value. Oftentimes, however, this is a handy trick.
The previous tips lead us to one conclusion: do not pass around data that you don’t need. Here, again, it might mean a bit more work when setting up your functions. In the long run, however, it will definitely give you a more readable codebase. It is invaluable to know exactly which values are used in a specific spot.
I have seen big files — very big files. In fact, over 3,000 lines of code. Finding chunks of logic is incredibly hard in these files.
Therefore, you should limit your file size to a certain number of lines. I tend to keep my files below 100 lines of code. Sometimes, it is hard to break up files, and they will grow to 200–300 lines and, in rare occasions, up to 400.
Above this threshold, the file gets too cluttered and hard to maintain. Feel free to create new modules and folders. Your project should look like a forest, consisting of trees (module sections) and branches (groups of modules and module files). Avoid trying to mimic the Alps, piling up code in confined areas.
Your actual files, in comparison, should look like the Shire, with some hills (small levels of indentation) here and there, but everything relatively flat. Try to keep the level of indentation below four.
Maybe it is helpful to enable eslint-rules for these tips!
Working in a team requires a clear style guide and formatting. ESLint offers a huge ruleset that you can customize to your needs. There is also eslint --fix
, which corrects some of the errors, but not all.
Instead, I recommend using Prettier to format your code. That way, developers do not have to worry about code formatting, but simply writing high-quality code. The appearance will be consistent and the formatting automatic.
Ideally, a variable should be named based on its content. Here are some guidelines that will help you declare meaningful variable names.
Functions usually perform some kind of action. To explain that, humans use verbs — convert or display, for example. It is a good idea to name your functions with a verb in the beginning, e.g., convertCurrency
or displayUserName
.
These will usually hold a list of items; therefore, append an s
to your variable name. For example:
const students = ['Eddie', 'Julia', 'Nathan', 'Theresa']
Simply start with is
or has
to be close to natural language. You would ask something like, “Is that person a teacher?” → “Yes” or “No.” Similarly:
const isTeacher = true // OR false
forEach
, map
, reduce
, filter
, etc. are great native JavaScript functions to handle arrays and perform some actions. I see a lot of people simply passing el
or element
as a parameter to the callback functions. While this is easy and quick, you should also name these according to their value. For example:
const cities = ['Berlin', 'San Francisco', 'Tel Aviv', 'Seoul']
cities.forEach(function(city) {
...
})
Oftentimes, you have to keep track of the ids of specific datasets and objects. When ids are nested, simply leave it as id. Here, I like to map MongoDB _id
to simply id
before returning the object to the frontend. When extracting ids from an object, prepend the type of the object. For example:
const studentId = student.id
// OR
const { id: studentId } = student // destructuring with renaming
An exception to that rule is MongoDB references in models. Here, simply name the field after the referenced model. This will keep things clear when populating references documents:
const StudentSchema = new Schema({
teacher: {
type: Schema.Types.ObjectId,
ref: 'Teacher',
required: true,
},
name: String,
...
})
Callbacks are the worst when it comes to readability — especially when nested. Promises were a nice improvement, but async/await has the best readability, in my opinion. Even for beginners, or people coming from other languages, this will help a lot. However, make sure you understand the concept behind it and do not mindlessly use it everywhere.
As we saw in tips 1 and 2, keeping logic in the right place is key to maintainability. In the same way, how you import different modules can reduce confusion in your files. I follow a simple structure when importing different modules:
// 3rd party packages
import React from 'react'
import styled from 'styled-components'
// Stores
import Store from '~/Store'
// reusable components
import Button from '~/components/Button'
// utility functions
import { add, subtract } from '~/utils/calculate'
// submodules
import Intro from './Intro'
import Selector from './Selector'
I used a React component as an example here since there are more types of imports. You should be able to adapt that to your specific use case.
console.log
is a nice way of debugging — very simple, quick, and does the job. Obviously, there are more sophisticated tools, but I think every developer still uses it. If you forget to clean up logs, your console will eventually end up a giant mess. Then there is logs that you actually want to keep in your codebase; for example, warning and errors.
To solve this issue, you can still use console.log
for debugging reasons, but for lasting logs, use a library like loglevel or winston. Additionally, you can warn for console statements with ESLint. That way you can easily globally look for console...
and remove these statements.
Cool, isn’t it?
Following these guidelines help to Keep your JavaScript code clean forever and scalable. Are there any tips you find particularly useful? Let us know in the comments what you will include in your coding workflow, and please share any other tips you use to help with code structure!
Thanks for reading, Keep visiting. Hope this post will surely help and you! Please share if you liked it!
Related Articles: Keeping your Vue.js code Clean
#javascript #reactjs #xcode #security #web-development
1603857900
According to an analysis, a developer creates 70 bugs per 1000 lines of code on average. As a result, he spends 75% of his time on debugging. So sad!
Bugs are born in many ways. Creating side effects is one of them.
Some people say side effects are evil, some say they’re not.
I’m in the first group. Side effects should be considered evil. And we should aim for side effects free code.
Here are 4ways you can use to achieve the goal.
Just add use strict; to the beginning of your files. This special string will turn your code validation on and prevent you from using variables without declaring them first.
#functional-programming #javascript-tips #clean-code #coding #javascript-development #javascript
1622207074
Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.
JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.
JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.
Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.
In JavaScript, ‘document.write‘ is used to represent a string on a browser.
<script type="text/javascript">
document.write("Hello World!");
</script>
<script type="text/javascript">
//single line comment
/* document.write("Hello"); */
</script>
#javascript #javascript code #javascript hello world #what is javascript #who invented javascript
1604088000
There are more code smells. Let’s keep changing the aromas. We see several symptoms and situations that make us doubt the quality of our development. Let’s look at some possible solutions.
Most of these smells are just hints of something that might be wrong. They are not rigid rules.
This is part II. Part I can be found here.
The code is difficult to read, there are tricky with names without semantics. Sometimes using language’s accidental complexity.
_Image Source: NeONBRAND on _Unsplash
Problems
Solutions
Examples
Exceptions
Sample Code
Wrong
function primeFactors(n){
var f = [], i = 0, d = 2;
for (i = 0; n >= 2; ) {
if(n % d == 0){
f[i++]=(d);
n /= d;
}
else{
d++;
}
}
return f;
}
Right
function primeFactors(numberToFactor){
var factors = [],
divisor = 2,
remainder = numberToFactor;
while(remainder>=2){
if(remainder % divisor === 0){
factors.push(divisor);
remainder = remainder/ divisor;
}
else{
divisor++;
}
}
return factors;
}
Detection
Automatic detection is possible in some languages. Watch some warnings related to complexity, bad names, post increment variables, etc.
#pixel-face #code-smells #clean-code #stinky-code-parts #refactor-legacy-code #refactoring #stinky-code #common-code-smells
1604008800
Static code analysis refers to the technique of approximating the runtime behavior of a program. In other words, it is the process of predicting the output of a program without actually executing it.
Lately, however, the term “Static Code Analysis” is more commonly used to refer to one of the applications of this technique rather than the technique itself — program comprehension — understanding the program and detecting issues in it (anything from syntax errors to type mismatches, performance hogs likely bugs, security loopholes, etc.). This is the usage we’d be referring to throughout this post.
“The refinement of techniques for the prompt discovery of error serves as well as any other as a hallmark of what we mean by science.”
We cover a lot of ground in this post. The aim is to build an understanding of static code analysis and to equip you with the basic theory, and the right tools so that you can write analyzers on your own.
We start our journey with laying down the essential parts of the pipeline which a compiler follows to understand what a piece of code does. We learn where to tap points in this pipeline to plug in our analyzers and extract meaningful information. In the latter half, we get our feet wet, and write four such static analyzers, completely from scratch, in Python.
Note that although the ideas here are discussed in light of Python, static code analyzers across all programming languages are carved out along similar lines. We chose Python because of the availability of an easy to use ast
module, and wide adoption of the language itself.
Before a computer can finally “understand” and execute a piece of code, it goes through a series of complicated transformations:
As you can see in the diagram (go ahead, zoom it!), the static analyzers feed on the output of these stages. To be able to better understand the static analysis techniques, let’s look at each of these steps in some more detail:
The first thing that a compiler does when trying to understand a piece of code is to break it down into smaller chunks, also known as tokens. Tokens are akin to what words are in a language.
A token might consist of either a single character, like (
, or literals (like integers, strings, e.g., 7
, Bob
, etc.), or reserved keywords of that language (e.g, def
in Python). Characters which do not contribute towards the semantics of a program, like trailing whitespace, comments, etc. are often discarded by the scanner.
Python provides the tokenize
module in its standard library to let you play around with tokens:
Python
1
import io
2
import tokenize
3
4
code = b"color = input('Enter your favourite color: ')"
5
6
for token in tokenize.tokenize(io.BytesIO(code).readline):
7
print(token)
Python
1
TokenInfo(type=62 (ENCODING), string='utf-8')
2
TokenInfo(type=1 (NAME), string='color')
3
TokenInfo(type=54 (OP), string='=')
4
TokenInfo(type=1 (NAME), string='input')
5
TokenInfo(type=54 (OP), string='(')
6
TokenInfo(type=3 (STRING), string="'Enter your favourite color: '")
7
TokenInfo(type=54 (OP), string=')')
8
TokenInfo(type=4 (NEWLINE), string='')
9
TokenInfo(type=0 (ENDMARKER), string='')
(Note that for the sake of readability, I’ve omitted a few columns from the result above — metadata like starting index, ending index, a copy of the line on which a token occurs, etc.)
#code quality #code review #static analysis #static code analysis #code analysis #static analysis tools #code review tips #static code analyzer #static code analysis tool #static analyzer
1593621572
Your college: “Who’s the author of this code?”
Expectation: “It’s me!” You answer proudly because that code is beautiful like a princess.
Reality: “Nah, it’s not me!” You lie because that code is ugly like a beast.
Now, if you want to make the expectation become the reality, keep reading.
Use meaningful names, which you know exactly what it is at first glance.
// Don't
let xyz = validate(‘amyjandrews’);
// Do
let isUsernameValid = validate(‘amyjandrews’);
It makes sense to name a collection type as plural. Thus, don’t forget the s:
// Don't
let number = [3, 5, 2, 1, 6];
// Do
let numbers = [3, 5, 2, 1, 6];
Functions do things. So, a function’s name should be a verb.
// Don't
function usernameValidation(username) {}
// Do
function validateUsername(username) {}
Start with is for boolean type:
let isValidName = validateName(‘amyjandrews’);
Don’t use constants directly because as time pass you will be like, “What the hell is this?” It’d better to name constants before using them:
// Don't
let area = 5 * 5 * 3.14;
// Do
const PI = 3.14;
let area = 5 * 5 * PI;
For callback functions, don’t be lazy to just name parameters as one character like h, j, d (maybe even you, the father of those name, don’t know what they mean). Long story short, if the parameter is a person, pass person; if it’s a book, pass book:
// Don't
let books = [‘Learn JavaScript’, ‘Coding for Beginners’, ‘CSS the Good Parts’];
books.forEach(function(b) {
// …
});
// Do
let books = [‘Learn JavaScript’, ‘Coding for Beginners’, ‘CSS the Good Parts’];
books.filter(function(book) {
// …
});
#coding #javascript-tips #programming #javascript #javascript-development