Stop Doing These Things In JavaScript
By: Kesk - -
Tags: Javascript Tips, JavaScript, Javascript Development, Web Development, Software Development

Stop Doing These Things In JavaScript

In this small article, I list some of the things I usually see in code reviews. These are not things that will make our program fail, but they make it harder to read, harder to maintain, and more error-prone.

Let’s start!

Conditionals

Using If

//1.

if( condirion === true){

//A lot of code.

} //2.

if(condition){

//A lot of code.

} //3.

const doSomething = () => (

//A lot of code.

) if(condition){

doSomething();

} //4.

if (condition) doSomething();

Here we are unnecessarily comparing the condition with the true value and writing a lot of code inside the block code. The first improvement to this code is to remove the comparison with true and leave its equivalent. Then we can take all the code that runs inside the if statement and put it into a function. Here already depends on your personal taste, but in this case, that we only execute one function, we can avoid the brackets.

Using Ternary

//1.

const value;

if( condition ){

value = 1;

}else{

value = 2;

} //2.

const value = condition ? 1 : 2;

We can use an if-else statement or… Improve the code and using a ternary operator. The result is the same.

Using If-Else

//1.

if( condition1 ){

doSomething();

}else(condition2 ) {

doOtherthing();

} //2.

if( condition1){

doSomething();

}

if( condition2){

doOtherthing();

}

This is another personal matter. We can use if-else statements or… We can use ifs sentences. I personally prefer the code in this way.

Using Switch

//1.

if (condition1) {

doSomething1();

} else if (condition2) {

doSomething2();

} else if (condition3) {

doSomething3();

} else if (condition4) {

doSomething4();

} else if (condition5) {

doSomething5();

} else {

doOtherthing();

} //2.

switch(expression) {

case condition1:

doSomething1();

break;

case condition2:

doSomething2();

break;

case condition3:

doSomething3();

break;

case condition4:

doSomething3();

break;

case condition5:

doSomething5();

break;

default:

doOtherthing();

}

In this example, we have a lot of if-else statements. In these cases, it is advisable to use a “Switch” statement. The resulting code is much cleaner, although it is still quite verbose, and the same sentences are repeated (case…break) several times

//3.

const conditions= new Map()

.set('condition1', '1'])

.set('condition2', '2')

.set('condition2', '3')

.set('condition2', '4')

.set('condition3', '5'); const condition = 'condition1'; function doSomething(condition) {

return conditions.get(condition) || console.log('default) ;

} doSomething(‘condition1’);

3. The same result can be achieved using (ES6) Map but with cleaner syntax.

Using the Include function

//1

function inRGB(color) {

if (color === 'red' || color ==='blue' || color ==='green') {

console.log(' The color is included in the RGB palette ');

}

} //2.

function inRGB(color) {

const rgb = ['red', 'blue', 'green'];

if (rgb.includes(color)) {

console.log(' The color is included in the RGB palette ');

}

}

What happened if we have more colors? Are we going to extend the statement with more ‘||’? The code looks better, and we no longer care about the number of colors we will have.

Return early when invalid conditions

//1.

function inRGB(color) {

const rgb = ['red', 'blue', 'green']; if (!color) throw new Error('No color!'); if (rgb.includes(color)) {

console.log(' The color is included in the RGB palette ');

}

}

We can achieve less level of nested statements if we return early when invalid conditions are found.

Using Default Function Parameters

//1.

function logCar(car, quantity) {

if( !! quantity ){

quantity = 0;

}

console.log(`You have ${quantity} a ${car} car/s`);

} function logCar(car, quantity) {

//2.

quantity = quantity || 0;

console.log(`You have ${quantity} a ${car} car/s`);

} //3.

function logCar(car, quantity = 0) {

if (!car) return;

console.log(`You have ${quantity} a ${car} car/s`);

} logCar('Ford');

logCar('Mercedes', 2);

A first approximation in which the parameter “quantity” is not passed, we assign a value of 0 to the parameter “quantity.” One way to do this before the default parameters existed was to use the “||” operator, but this does not always work well. Depending on which parameter is passed, it can give an unexpected result. Using Default Function Parameters.

Result in Chrome dev tools console

Using Destructuring

//1.

function logCarModel(carObject) {

if (carObject && carObject.model) {

console.log (carObject.model);

} else {

console.log('unknown');

}

} //2.

function logCarModel( {model} = {} ) {

console.log (model|| 'unknown');

} logCar({ model: '250', color: 'black' });

logCar({});

Here we want to write in the log console the car model if it’s available. In other cases, we will write the “unknown” value. We can avoid conditional “carObject && carObject.model” checking with default function parameter (ES6) and destructing (ES6).

Functions and variables names

Function names

//1.

function biggerThanCero(money){

return money > 0;

}



//2.

function isValidBalance(age){

return money > 0;

}

Use names with the code description, not the functionality. Describe your function.

Variable names

//1.

let a;

let b; //2.

let thisVariableIsForTheName;

These name variables are too short. What is “a” or “b”? In the other case, is this long name essential? It isn't easy to read.

Class Names



class myclass{

//...

}

class myClass{

//...

} //1.

class MyClass{

//...

}

Class names should be PacalCase.

Constant names

const constantValue = 1; //1.

const CONSTANT_VALUE= 1;

The names upper case letters, with words separated by underscores.

Remember that constants have const declaration, but not all “const” are immutables.

Field names and local variables names

let carmodel; //1.

let carModel;

Field names, static or otherwise, should be written in camelCase.

Private names

//1.

let _privateVariable = 0;

The convention of prepending an underscore “_ “ to a variable (method, …) name indicates a private variable.

Short notation

Short-circuit evaluation “||”

var someVariable;

var otherVariable = 'Hello!';

var finalValue; //1.

if ( someVariable == null || someVariable =='undefined' || someVariable== '' ) {

finalValue = otherVariable ;

}

console.log(finalValue);

//Hello! //2.

finalValue= someVariable || otherVariable ;

console.log(finalValue);

//Hello! //3.

someVariable = 0;

otherVariable = 'Hello!';

finalValue= someVariable || otherVariable ;

console.log(finalValue);

//Hello!

Long notation: prints “Hello!” Short notation: using a short-circuit evaluation. Prints “Hello!” Keep in mind that this does not always work well; if you set the variable “someVariable” to false or 0, the “otherVariable” value will be assigned. Prints “Hello!” too.

Result in Chrome dev tools console.

Short-circuit evaluation “&&”

const value1 =1;

const value2 =2;

const sumValues = (a,b) => a+b; //1.

if ( value1 && value2 ) {

const result = sumValues(value1, value2);

console.log(result);

} //2.

const result = value1 && value2 && sumValues(value1,value2);

Long notation: The function sumValues is executed if value1 and value2 have values. Short notation: The function sumValues is executed if value1 and value2 have values.

Declaring variables shorthand

//1.

let a = 1;

let b = 2;

let c = 3; //2.

let a = 1, b = 2, c = 3;

Long notation Short notation, All inside the same sentence separated by commas.

For loop shorthand

const cars = ['Jeep', 'ford', 'Cadillac']; //1.

for (let i = 0; i < cars.length; i++){

console.log(cars[i]);

} //2.

[cars].forEach(c => {console.log(c)});

Long notation Short notation

Result in Chrome dev tools console

Object property shorthand

ES6 provides an even easier way of assigning properties to objects. If the variable name is the same as the object key, you can take advantage of the shorthand notation.

//1.

const a = 1, b = 2;

const obj1 = { a:a, b:b };

console.log(obj1); //2.

const obj2 = { a, b};

console.log(obj2);

Long notation Short notation

Result in Chrome dev tools console

Arrow Functions Shorthand

Arrow function expressions are a compact alternative to traditional function expressions but remember they can’t be used in all situations.

//1.

function sayHello(name) {

console.log(‘Hello: ‘ +name);

}

console.log(sayHello("Amanda")); //2.

const sayHello2 = name => console.log(‘Hello: ‘ +name);

console.log(sayHello2("Amanda"));

Long notation Short notation

Result in Chrome dev tools console

Destructuring Assignment Shorthand

//1.

const props = {

p1 : 1,

p2 : 2,

p3 : 3

}; const p1 = props.p1;

const p2 = props.p2;

const p3 = props.p3;

console.log(p1, p2, p3); //2.

const { p1, p2, p3 } = props;

console.log(p1, p2, p3);

Long notation Short notation

Result in Chrome dev tools console.

Mandatory Parameter Shorthand

//1.

function f1(param1) {

if(param1 === undefined) {

throw new Error('Missing parameter!');

}

return param1;

} //2.

mandatory = () => {

throw new Error('Missing parameter!');

}



const f1 = (param1= mandatory()) => {

return bar;

}

Long notation Short notation. In this way, the resulting code is more clear.

Exponent Power Shorthand

//1.

console.log(Math.pow(2,4)); //2.

console.log(2**4);

Long notation Short notation. In this way, the resulting code is more clear.

Result in Chrome dev tools console

Comments

function isValidBalance(age){

return money > 0;

} //1.

//check if the balace is greater than zero.

if(isValidBalance(account)) doSomething(); //2.

//If the balance is positive we will doSomething.

//3.

if(isValidBalance(account)) doSomething();

Comments should explain the purpose of the code, not read what the code says. Here we explain the purpose of the function. If you define a good function name, you will not need the comment; the function name itself indicates what is done.

Globals

Global variables clutter up the global namespace and are slower to look up than local variables. Also, having many global variables is always bad because it’s easy to forget you declared a variable somewhere and accidentally re-declare it somewhere else and overwriting the original value.

In Javascript, variables declared without any keyword (var, let, const) will become global variables and attached to the global object.

//1.

prefix= "Hello:"; function hello(param) {

//1.

return prefix + param;

}



hello('Kesk');

//Hello: Kesk

Here, we are declaring a variable called “prefix” with the value “Hello,” and without any (var, let, const) keyword. In this way, it becomes a global variable.

//1.

console.log(window.prefix)

//Hello:

As you can see, the prefix variable is defined in the global window object.

//2.

prefix = "Bye:"; function hello(param) {

//1.

return prefix + param;

}



hello('Kesk');

Now in another part of our code, we overwrite the “prefix” variable, and if he executes again our hello function instead of “Hello Kesk,” we obtain “Bye Kesk.” Do you see the problem?

Result in Chrome dev tools console

Conclusion

Remember, it is our responsibility to write clean and robust code: easy to read and easy to maintain in the future.

I’ve had fun writing this little guide, plus it’s a good way to remember good practices that many times, for various reasons, we don’t apply.

Thanks for reading me! Take care!

Enjoyed this article? If so, get more similar content by subscribing to our YouTube channel!