Tips To Write Less JavaScript

Introduction

In my last article, I shared some of the One Liner Hacks In JavaScript, and now I would like to share some tips to write less in Javascript. Below are 8 tips with examples to save time and write better javascript code.

  • Condition true
  • Arrow Function
  • Template literals
  • Power of any Number(Exponention)
  • Assignment operator
  • Declaring Variables
  • Ternary Operator

Condition True

Generally, we use the strict equality operator to check if two operands are equal, so we can avoid this operator checking the condition. 

boolvar = true
if (boolvar === true) {
    console.log('True')
}
//----------- SHorthand method
if (boolvar) { //true condition
    console.log('True')
}

Arrow Function

One of the features introduced in the ES6 version of javascript. An arrow function is a compact alternative to traditional functions and allows you to write a function concisely.

function func(name) {
console.log('I'm a regular function named ' + name);
}
//---------- Shortand
const fullname = name => console.log('I'm a regular function named ' + name);

Template Literals

Template literals in ES6 provide a feature to create a string that gives more control over a dynamic string.

const name = "Abhishek"
const role = "Developer"
console.log("My Name is " + name + " I'm a " + role)
//-------- Shorthand
const name = "Abhishek"
const role = "Developer"
console.log(`My Name is ${name} I'm a ${role}`)

Power of any number

For the power of any number, we generally use Math functions like the one below, but for this, we directly use the operator(**)

console.log(Math.pow(6, 3))
// output 216
//--------------shorthand
console.log(6 ** 3)
// output 216

Assignment operator

Assignment operators assign values to JavaScript variables. Similarly, we have an addition assignment operator that assigns and adds in the same variable. Below is the example for the Addition assignment operator, but similarly, we can use this way assignment with any of the operations.

x = x + y
//-------------------- shorthand
x += y

Declaring Variables

Let's say we need to declare multiple variables, so we generally use the below approach. But there is a shorthand way to declare multiple variables in a single line.

var x;
var y;
var z = 'Abhi';
//-------------------- shorthand
var x, y, z = 'Abhi'

Ternary Operator

The only JS Conditional operator that takes three operands is a condition followed by a (?) expression to execute the true condition followed by a (:) and false condition to execute.

let result = 40,
    isPass
if (result > 33) {
    isPass = true;
} else {
    isPass = false;
}
//------------ shorthand
let result = 20,
    isPass = result > 33 ? true : false

Conclusion

I hope you all understand these with the given examples better now and try to implement this in your projects and also will provide you with more tips on these types in the following article.

Till then, Happy Coding :) 


Similar Articles