Learn 30+ JavaScript shorthand methods to code efficiently, reduce errors, and increase productivity in your development projects.
I am Rakshit Shah and my work experience in IT Industries is over 5 years now. I am working as a full-stack developer. This really is a must-read for all full-stack developers. The syntax will be somewhat different for other technologies (Angular, Java, Vue, etc.), but let’s focus more on the concepts!
In this article, I will show you the long-hand vs short-hand tricks and tips that I have picked up over the years. These might be useful to you when you are developing awesome scripts!
Optimized and highly readable code will increase your own interest in your daily work life. ~ Rakshit Shah
Cover Image credits: JavaScript shorthand coding tricks, tips, and techniques | Image by Author
1. Declaring Variables
It’s good practice to declare your variable assignments at the beginning of your functions. This shorthand method can save you lots of time and space when declaring multiple variables at the same time.
Longhand:
let x;
let y;
let z = 3;
Shorthand:
let x, y, z=3;
2. Use Ternary Operators
Your life will become easier when you start to use ternary conditions instead of using if…else
statements.
Longhand:
const age = 26; let eligibility; if(age > 18){ eligibility = "Allowed"; } else{ eligibility = "Not Allowed"; }
Shorthand:
let eligibility = (age > 18) ? "Allowed" : "Not Allowed";
You can also nest your if
statement like this:
let eligibility = age > 10 ? "greater than 10" : (age < 5 ? "less than 5" : "between 5 and 10");
3. JavaScript For Loop
This little tip is really useful if you want plain JavaScript and don’t want to rely on external libraries such as jQuery or lodash.
Longhand:
const fruits = ['mango', 'peach', 'banana'];
for (let i = 0; i < fruits.length; i++)
Shorthand:
for (let fruit of fruits)
If you just wanted to access the index, do:
for (let index in fruits)
This also works if you want to access keys in a literal object:
const obj = {continent: 'Africa', country: 'Kenya', city: 'Nairobi'}
for (let key in obj)
console.log(key) // output: continent, country, city
Shorthand for Array.forEach:
function logArrayElements(element, index, array) {
console.log("a[" + index + "] = " + element);
}
[5, 7, 2].forEach(logArrayElements);
// a[0] = 5
// a[1] = 7
// a[2] = 2
4. Array.find
If you have ever been tasked with writing a find function in plain JavaScript, you would probably have used a for
loop. In ES6, a new array function named find()
was introduced.
Longhand:
const pets = [
{ type: 'Dog', name: 'Max'},
{ type: 'Cat', name: 'Karl'},
{ type: 'Dog', name: 'Tommy'},
]
function findDog(name) {
for(let i = 0; i
Shorthand:
pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');
console.log(pet); // { type: 'Dog', name: 'Tommy' }
5. If Presence
This might be trivial, but worth a mention. When doing “if
checks”, assignment operators can sometimes be omitted.
Longhand:
if (isLovely === true)
Shorthand:
if (isLovely)
Also, note that these two examples are not exactly equal, as the shorthand check will pass as long as isLovely
is a truthy value.
Here is another example. If a
is NOT equal to true, then do something.
Longhand:
let a;
if ( a !== true ) {
// do something...
}
Shorthand:
let a;
if ( !a ) {
// do something...
}
Bonus: Format JSON Code
When you want to format your JSON object or JSON response without using any third-party tool. Open your browser console and hit the below command to get your JSON formatted.
The stringify
method takes three inputs. The value
, replacer
, and space
. Probably, You know about value only!
The next two are optional parameters. That is why we did not use them in a general way. To indent our JSON, we must use the space
parameter.
console.log(JSON.stringify({name:"Rax",Age:26},null,'t'));
6. Arrow Functions
Classical functions are easy to read and write in their plain form, but they do tend to become a bit verbose and confusing once you start nesting them in other function calls.
Longhand:
function sayHi(name) {
console.log('Hello Rax', name);
}
setTimeout(function() {
console.log('Loaded')
}, 2000);
list.forEach(function(item) {
console.log(item);
});
Shorthand:
sayHi = name => console.log('Hello Rax', name);
setTimeout(() => console.log('Loaded'), 2000);
list.forEach(item => console.log(item));
It’s important to note that the value of this
inside an arrow (something similar to Java Lambda Expressions) function is determined differently than for longhand functions, so the two examples are not strictly equivalent.
7. Multi-line String
If you have ever found yourself in need of writing multi-line strings in code, this is how you would write it:
Longhand:
const lorem = 'Lorem ipsum dolor sit amet, consecteturnt'
+ 'adipisicing elit, sed do eiusmod tempor incididuntnt'
+ 'ut labore et dolore magna aliqua. Ut enim ad minimnt'
+ 'veniam, quis nostrud exercitation ullamco laborisnt'
+ 'nisi ut aliquip ex ea commodo consequat. Duis autent'
+ 'irure dolor in reprehenderit in voluptate velit esse.nt'
But there is an easier way. Just use backticks. ` …`
Shorthand:
const lorem = `Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse.`
8. Template Literals
Aren’t you tired of using ' + '
to concatenate multiple variables into a string? Isn’t there a much easier way of doing this? If you are able to use ES6, then you are in luck. All you need to do is use is the backtick, and ${}
to enclose your variables.
Longhand:
const welcome = 'You have logged in as ' + firstName + ' ' + lastName + '.'
const db = 'http://' + host + ':' + port + '/' + database;
Shorthand:
const welcome = `You have logged in as ${firstName} ${lastName}`;
const db = `http://${host}:${port}/${database}`;
9. Decimal Base Exponents
You may have seen this one around. It’s essentially a fancy way to write numbers without the trailing zeros. For example, 1e5 essentially means 1 followed by 5 zeros. It represents a decimal base (which JavaScript interprets as a float type) equal to 1,00,000.
Longhand:
for (let i = 0; i < 10000; i++) {}
Shorthand:
for (let i = 0; i < 1e7; i++) {}
// All the below will evaluate to true
1e0 === 1;
1e1 === 10;
1e2 === 100;
1e3 === 1000;
1e4 === 10000;
1e5 === 100000;
10. Short-circuit Evaluation
Instead of writing five-six lines of code to assign a default value if the intended parameter is null or undefined, we can simply use a short-circuit logical operator and accomplish the same thing with just one line of code.
Longhand:
let dbHost;
if (process.env.DB) {
dbHost = process.env.DB;
} else {
dbHost = '127.0.0.1';
}
Shorthand:
const dbHost = process.env.DB || '127.0.0.1';
Bonus: Get the Last Items in an Array
If you want to take the elements from the end of the array, you can use the slice
the method with negative integers.
let array = [0, 1, 2, 3, 4, 5, 6, 7] console.log(array.slice(-1)); >>>[7] console.log(array.slice(-2)); >>>[6, 7] console.log(array.slice(-3)); >>>[5, 6, 7]
11. Object Property
Defining object literals in JavaScript makes life much easier. 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.
Longhand:
const x = 2020, y = 2021;
const obj = { x:x, y:y };
Shorthand:
const obj = { x, y };
12. Implicit Return
Return is a keyword we use often to return the final result of a function. An arrow function with a single statement will implicitly return the result of its evaluation (the function must omit the braces ({}) in order to omit the return keyword).
To return a multi-line statement (such as an object literal), it’s necessary to use ()
instead of {}
to wrap your function body. This ensures the code is evaluated as a single statement.
Longhand:
function calcCircumference(diameter) {
return Math.PI * diameter
}
Shorthand:
calcCircumference = diameter => (
Math.PI * diameter;
)
13. Destructuring Assignment
If you are working with any popular web framework, there are high chances you will be using arrays or data in the form of object literals to pass information between components and APIs. Once the data object reaches a component, you’ll need to unpack it.
Longhand:
const observable = require('mobx/observable');
const action = require('mobx/action');
const runInAction = require('mobx/runInAction');
const store = this.props.store;
const form = this.props.form;
const loading = this.props.loading;
const errors = this.props.errors;
const entity = this.props.entity;
Shorthand:
import { observable, action, runInAction } from 'mobx';
const { store, form, loading, errors, entity } = this.props;
You can even assign your own variable names:
const { store, form, loading, errors, entity:contact } = this.props;
Mostly, Visual Studio code editor provides plugins for auto-import or autocomplete.
14. Spread Operator
The spread operator, which was introduced in ES6, has several use cases that make JavaScript code more efficient and fun to use. It can be used to replace certain array functions. The spread operator is simply a series of three dots.
Longhand:
// joining arrays
const odd = [1, 3, 5];
const nums = [2 ,4 , 6].concat(odd);
// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = arr.slice()
Shorthand:
// joining arrays
const odd = [1, 3, 5 ];
const nums = [2 ,4 , 6, ...odd];
console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]
// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = [...arr];
Unlike the concat()
function, you can use the spread operator to insert an array anywhere inside another array.
const odd = [1, 3, 5 ];
const nums = [2, ...odd, 4 , 6];
You can also combine the spread operator with ES6 destructuring notation:
const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 };
console.log(a) // 1
console.log(b) // 2
console.log(z) // { c: 3, d: 4 }
15. Default Parameter Values
You can use the if
statement to define default values for function parameters. In ES6, you can define the default values in the function declaration itself.
Longhand:
function volume(l, w, h) {
if (w === undefined)
w = 3;
if (h === undefined)
h = 4;
return l * w * h;
}
Shorthand:
volume = (l, w = 3, h = 4 ) => (l * w * h);
volume(2) //output: 24
Bonus: Truncate an Array
If you want to remove values from the end of an array destructively, there’s are faster alternatives than using splice()
.
For example, if you know the size of your original array, you can re-define its length property, like so:
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; array.length = 4;console.log(array); // Result: [0, 1, 2, 3]
This is a particularly concise solution. However, I have found the run-time of the slice()
method to be even faster. If speed is your main goal, consider using something like this:
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; array = array.slice(0, 4);console.log(array); // Result: [0, 1, 2, 3]
16. Object [key] Benefits
Did you know that Foo.bar
can also be written as Foo['bar']
? At first, there doesn’t seem to be a reason why you should write it like that. However, this notation gives you the building block for writing reusable code.
Consider this simplified example of a validation function:
function validate(values) {
if(!values.first)
return false;
if(!values.last)
return false;
return true;
}
console.log(validate({first:'Bruce',last:'Wayne'})); // true
This function does its job perfectly. However, consider a scenario where you have very many forms where you need to apply the validation but with different fields and rules. Wouldn’t it be nice to build a generic validation function that can be configured at runtime?
Shorthand:
// object validation rules
const schema = {
first: {
required:true
},
last: {
required:true
}
}
// universal validation function
const validate = (schema, values) => {
for(field in schema) {
if(schema[field].required) {
if(!values[field]) {
return false;
}
}
}
return true;
}
console.log(validate(schema, {first:'Bruce'})); // false
console.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true
Now we have a validate function we can reuse in all forms without needing to write a custom validation function for each.
17. Exponent Power
It is useful for a Math exponent power function:
Longhand:
Math.pow(2,3); // 8
Math.pow(2,2); // 4
Math.pow(4,3); // 64
Shorthand:
2**3 // 8
2**4 // 4
4**3 // 64
18. Converting a String into a Number
There are times when your code receives data that comes in String format but needs to processed in Numerical format. It’s not a big deal, we can perform a quick conversion.
Longhand:
const num1 = parseInt("100");
const num2 = parseFloat("100.01");
Shorthand:
const num1 = +"100"; // converts to int data type
const num2 = +"100.01"; // converts to float data type
19. Object.entries()
This is a feature that was introduced in ES8 that allows you to convert a literal object into a key/value pair array. See the example below:
const credits = { producer: 'John', director: 'Jane', assistant: 'Peter' };
const arr = Object.entries(credits);
console.log(arr);
/** Output:
[ [ 'producer', 'John' ],
[ 'director', 'Jane' ],
[ 'assistant', 'Peter' ]
]
**/
20. Object.values()
This is also a new feature introduced in ES8 that performs a similar function to Object.entries()
, but without the key part:
const credits = { producer: 'John', director: 'Jane', assistant: 'Peter' };
const arr = Object.values(credits);
console.log(arr);
/** Output:
[ 'John', 'Jane', 'Peter' ]
**/
Bonus: use === instead of ==
The ==
(or !=
) operator performs an automatic type conversion if needed. The ===
(or !==
) operator will not perform any conversion. It compares the value and the type, which could be considered faster than ==
.
[10] === 10 // is false
[10] == 10 // is true
'10' == 10 // is true
'10' === 10 // is false
[] == 0 // is true
[] === 0 // is false
'' == false // is true but true == "a" is false
'' === false // is false
Also, note that, undefined
, null
, 0, false
, NaN
, ''
(empty string) are all falsy.
21. Bitwise IndexOf
When performing a lookup using an array, the indexOf()
function is used to retrieve the position of the item you are looking for. If the item is not found, the value -1
is returned. In JavaScript, 0
is considered ‘falsy’, while numbers greater or lesser than 0
are considered ‘truthy’. As a result, one has to write the correct code like this.
Longhand:
if(arr.indexOf(item) > -1) { // Confirm item IS found
}
if(arr.indexOf(item) === -1) { // Confirm item IS NOT found
}
Shorthand:
if(~arr.indexOf(item)) { // Confirm item IS found
}
if(!~arr.indexOf(item)) { // Confirm item IS NOT found
}
The bitwise(~)
the operator will return a truthy value for anything but -1
. Negating it is as simple as doing !~
. Alternatively, we can also use the includes()
function:
if(arr.includes(item)) { // Returns true if the item exists, false //if it doesn't
}
22. Object Property Assignment
Consider the following piece of code:
let fname = { firstName : 'Black' };
let lname = { lastName : 'Panther'}
How would you merge them into one object? One way is to write a function that copies data from the second object onto the first one. Unfortunately, this might not be what you want — you may need to create an entirely new object without mutating any of the existing objects. The easiest way is to use the Object.assign
function introduced in ES6:
let full_names = Object.assign(fname, lname);
You can also use the object destruction notation introduced in ES8:
let full_names = {...fname, ...lname};
There is no limit to the number of object properties you can merge. If you do have objects with identical property names, values will be overwritten in the order they were merged.
23. Double Bitwise NOT Shorthand
Bitwise operators are one of those features you learn about in beginner JavaScript tutorials and you never get to implement them anywhere. Agree? Besides, who wants to work with ones and zeroes if you are not dealing with binary?
There is, however, a very practical use case for the Double Bitwise NOT operator. You can use it as a replacement for Math.floor()
. The advantage of the Double Bitwise NOT operator is that it performs the same operation much faster. You can read more about Bitwise operators here.
Longhand:
Math.floor(4.9) === 4 //true
Shorthand:
~~4.9 === 4 //true
24. Short-circuit Evaluation
When assigning a variable value to another variable, you may want to ensure that the source variable is not null, undefined, or empty. You can either write a long if
statement with multiple conditionals, or use a short-circuit evaluation.
Longhand:
if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
let variable2 = variable1;
}
Shorthand:
const variable2 = variable1 || 'new';
Don’t believe me? Test it yourself (paste the following code in es6console):
let variable1;
let variable2 = variable1 || 'bar';
console.log(variable2 === 'bar'); // prints true
variable1 = 'foo';
variable2 = variable1 || 'bar';
console.log(variable2); // prints foo
Do note that, if you set variable1
to false
or 0
, the value bar
will be assigned.
25. Mandatory Parameter
By default, JavaScript will set function parameters to undefined
if they are not passed a value (In short, not assigned any values). Some other languages will throw a warning or error. To enforce parameter assignment, you can use if
statement to throw an error if undefined
, or you can take advantage of the ‘Mandatory parameter shorthand’.
Longhand:
function foo(bar) {
if(bar === undefined) {
throw new Error('Missing parameter!');
}
return bar;
}
Shorthand:
mandatory = () => {
throw new Error('Missing parameter!');
}
foo = (bar = mandatory()) => {
return bar;
}
Bonus: Swap two variables
For swapping two variables, we often use a third variable. But it can be done easily with array de-structuring assignment.
Longhand:
let x = "rakshit", y = "shah"; const temp = x; x = y; y = temp;
Shorthand:
[x,y] = [y,x]
26. Convert Anything to Boolean
while developing any code you might face a situation where you need a boolean value to compare or do the true/false check. This approach will be useful in such cases!
const foo = 'some string lines'; const toBool = !!foo console.log(toBool) // true
27. Convert Anything to Number
With use of +
operator, you can achieve it.
const foo = '522' const toNumber = +foo console.log(toNumber) // 522 const toNegativeNumber = -foo console.log(toNegativeNumber) // -522
28. Convert Array to Object
const arr = [ 'foo', 'bar', 1]
const obj = { ...arr }
console.log(obj) // {0: "foo", 1: "bar", 2: 1}
29. Remove duplicate item in Array
The Set
object lets you store unique values of any type, whether primitive values or object references.
const arr = ['a', 'b', 'c', 'b', 'd'] const newArr = [... new Set(arr)] console.log(newArr) // ["a", "b", "c", "d"]
30. Comment your code often
Generally, developer hates or forgot to put comments for their developed functions, algorithms or code. Apparently, if you put comments where required, it will be helpful to your peers.
Comments are a great way to summarize a code fragment’s purpose, saving your fellow developers the time it would take to determine it on their own.
It also allows them to catch possible mistakes if the code does not complete the task it is commented to complete. In general, it’s best to leave one comment on every function.
If you’re unsure if you should leave a comment, just do it! It can always be deleted later if it’s too much clutter.
When you feel, some code is missing or needed to be done in the future, just add TODO comments.
//declares and initializes var x
Conclusion
I know that there are many other tips, tricks, and good practices, so if you have any ones to add or if you have any feedback or corrections to the ones that I have shared, please add a comment.
Don’t be selfish, share knowledge with your friends.
Always remember, “information is not knowledge.” — Albert Einstein & Rakshit Shah
I obtain an immense amount of satisfaction from helping others attain their goals and reach their potential through technology. Even if you wish to reach out and say "Hello", I sincerely appreciate all of the wonderful correspondence I receive each day from readers. You all enrich my life, and I hope I am able to do the same for you all as well.
If you find joy and value in what I do, please consider supporting my work with a donation — however much you can afford, it means and helps more than you can imagine.
You can give tips too using Buy me a coffee.
Discover more from 9Mood
Subscribe to get the latest posts sent to your email.
0 Comments