7 Tips to Write Clean JavaScript Code

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.

1. Use meaningful Variable Names

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 radius = 5;
let area = PI * radius * radius;
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) {
  // …
});

2. Throw Informative Errors

“An error occurs.”

Or just: “Error.”

What error?

Every time I see an error like that in some applications or websites, as a user, I hate it. What do I do wrong? I make that error? So what error? You don’t tell me, how can I know what I’m going to do next?

Your users probably have the same feeling as me. Sometimes they will uninstall your app and never get back.

Writing a clear error message is not hard at all.

If there’s no internet connection, then:

showMessage(‘No internet connection! Please check your connection and try again!’);

If the user forgets to input something, then:

showMessage(‘Please enter your username’);

More importantly, a clear error helps you debug quickly and save you a lot of development time.

if (error) {
  throw new Error(‘validation.js:checkUser: special characters are now allowed’);
}

The above is the error message format you can refer to.

3. Return as Soon as Possible

Take a look at the code below:

function login(username, password) {
  if (isValid(username)) {
    // Log in
  } else {
    showMessage(‘Username is not valid’);
  }
}

The else part is unnecessary. We should remove it by returning the message early:

function login(username, password) {
  if (!isValid(username)) {
    showMessage(‘Username is not valid’);
    return;
  }  // Log in
}

This makes your code clearer. Edge cases should be placed early followed by the longer part with more logic to handle.

4. Don’t Give too Much Power to a Function

Every function should only take one responsibility. Don’t make one the powerful function that does a lot of things.

function validateAndLogin() {
  // Do a lot of things here
}

The “and” should not be a part of the function’s name. “And” add more responsibilities to a function, which does more harm than good in the long run.

Below are the best:

function validate() {
  // Only validate
}function login() {
  // Only login
}

5. Avoid Side Effect

Anything outside a function is not its business. So the function should not touch any of them.

For example:

var number = 3;function changeNumber(add) {
  number = 2 + add;
  return number;
}changeNumber();

When you call changeNumber function, the variable number will be changed to 6. This is a real problem because sometimes you have no clue about changes of a global variable. So, you should avoid this side effect in your projects.

How? By using pure function.

The example above can be changed to:

function addThree(summand) {
  const constant = 3;
  const sum = summand + constant;  return sum;
}

6. Create Modules

You create some functions. They seem to do a similar type of action. For example, validateUsername and validatePassword. You sense that they can be grouped into one module. Let’s call it validation module.

const validateUsername = function (username) {
  // Validate username
};const validatePassword = function (password) {
  // Validate password
};Module.exports = {
  validateUsername,
  validatePassword
};const { 
  validateUsername,
  validatePassword
} = require(‘./validation’);let isUsernameValid = validateUsername(‘amyjandrews’);

7. Use a Code Formatting Plugin

I use VSCode for most of my projects. If you are using VSCode, make sure to install Prettier for the sake of beautiful code.

This plugin will save you some time of formatting code. Thanks to it, you can use that time to focus more on the quality of your code.

Original article source at https://javascript.plainenglish.io

#javascript 

 

What is GEEK

Buddha Community

7 Tips to Write Clean JavaScript Code

ahsan dev

1594116983

nice

Thank you ahsan dev!

Giles  Goodwin

Giles Goodwin

1603857900

4 Ways You Can Get Rid of Dirty Side Effects for Cleaner Code in JavaScript

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.

1. use strict;

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

Armando  Bruen

Armando Bruen

1593621572

Who Else Wants to Write Clean JavaScript Code?

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.

1. Use meaningful Variable Names

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

Tyrique  Littel

Tyrique Littel

1604008800

Static Code Analysis: What It Is? How to Use It?

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.”

  • J. Robert Oppenheimer

Outline

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.

How does it all work?

Before a computer can finally “understand” and execute a piece of code, it goes through a series of complicated transformations:

static analysis workflow

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:

Scanning

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., 7Bob, 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

Kaustav Hazra

1589858834

How to start writing less error-prone code in JavaScript

Everything in JavaScript is an object!’. We said that this assertion is false. Many things in JavaScript can behave like an object, but that doesn’t mean it’s the object. We can say we have three types of objects (objects, functions and arrays) in JavaScript.

In ECMAScript Specification, the functions aren’t on the type list. Intuitively, function values have a specific behaviour, that is different from values that are numbers - so isn’t it a type? JavaScript refers to functions as a sub-type of the object type - sometimes refers to them as a callable object.

Conclusion: Functions are sort of type, but a sub-type - not a top level type…

#javascript-development #javascript-tips #programming-tips #javascript #programming

JavaScript Dev

JavaScript Dev

1610158495

7 Simple JavaScript Tips for Optimizing Your Code

I know you care about optimizing your code but sometimes you don’t know how to do it.

Imagine every piece of your code is well optimized, the performance would be great and you can easily investigate your code if having any issue.

So, without any further ado, let’s dive right into the 7 simple JavaScript tips below.

#programming-tips #javascript #programming #javascript-tips