Top 15 JavaScript Tips and Tricks to Increase your Speed and Efficiency

Most programming languages are flexible enough to allow programmers to achieve similar results in a variety of ways. JavaScript isn’t any different. JavaScript is without a doubt one of the coolest languages in the world, and it is growing in popularity by the day. With JavaScript, we frequently find multiple ways to achieve the same result, which can be perplexing at times.

Some of the applications are superior to the alternatives. With our profound expertise in JavaScript, we will happily share a few tips and tricks that would help you. Let’s get started.

1. Swap values with Array Destructuring

The destructuring assignment syntax is a JavaScript expression that allows you to extract values from arrays or properties from objects and store them in separate variables. We can also use it to quickly swap values, as shown below:

let a = 1, b = 2
[a, b] = [b, a]
console.log(a) // result -> 2
console.log(b) // result -> 1

2. Remove duplicates from an Array

This is a very simple trick. Assume we created an array with numbers, strings, and booleans, but the values are repeating themselves multiple times and we want to remove the duplicates. So here’s what we can do:

const array = [1, 3, 2, 3, 2, 1, true, false, true, ‘Kio’, 2, 3];
const filteredArray = […new Set(array)];
console.log(filteredArray) // [1, 3, 2, true, false, “Kio”]

3. Shuffle an Array

Making use of the inbuilt Math.random() method.

const list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
list.sort(() => {
    return Math.random() – 0.5;
});
// Output
(9) [2, 5, 1, 6, 9, 8, 4, 3, 7]
// Call it again
(9) [4, 1, 7, 5, 3, 8, 2, 9, 6]

4. Nullish Coalescing Operator

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined and otherwise returns its left-hand side operand.

const foo = null ?? ‘my school’;
// Output: “my school”

const baz = 0 ?? 42;
// Output: 0

5. Functional Inheritance

The process of receiving features by applying an augmenting function to an object instance is known as functional inheritance. The function provides a closure scope that can be used to keep some data private. The augmenting function uses dynamic object extension to add new properties and methods to the object instance.

They look like:

// Base function
function Drinks(data) {
  var that = {}; // Create an empty object
  that.name = data.name; // Add it a “name” property
  return that; // Return the object
};

// Function which inherits from the base function
function Coffee(data) {
  // Create the Drinks object
  var that = Drinks(data);
  // Extend base object
  that.giveName = function() {
    return ‘This is ‘ + that.name;
  };
  return that;
};

// Usage
var firstCoffee = Coffee({ name: ‘Cappuccino’ });
console.log(firstCoffee.giveName());
// Output: “This is Cappuccino”

6. Single-liner Palindrome check

Well, this is not a shorthand trick overall but it will give you a clear idea to play with strings.

function checkPalindrome(str) {
  return str == str.split(”).reverse().join(”);
}
checkPalindrome(‘naman’);
// Output: true

7. Simple Swap 2 values using Destructuring

let a = 5;
let b = 8;
[a,b] = [b,a]

[a,b]
// Output
(2) [8, 5]

8. Convert Decimal to Binary or Hexa

We can use some in-built methods like .toPrecision() or .toFixed() to achieve many functionalities while solving problems.

const num = 10;

num.toString(2);
// Output: “1010”
num.toString(16);
// Output: “a”
num.toString(8);
// Output: “12”

9. Short For Loop

You can write less code for a loop like this:

const names = [“Kio”, “Rio”, “Mac”];

// Long Version
for (let i = 0; i < names.length; i++) {
  const name = names[i];
  console.log(name);
}

// Short Version
for (let name of names) console.log(name);

10. Using length to resize and emptying an array

In javascript, we can override a built-in method called length and set its value to whatever we want.

Consider the following example:

let array_values = [1, 2, 3, 4, 5, 6, 7, 8]; 
console.log(array_values.length);
// 8 
array_values.length = 5; 
console.log(array_values.length);
// 5 
console.log(array_values);
// [1, 2, 3, 4, 5]

It can also be used in emptying an array, like this:

let array_values = [1, 2, 3, 4, 5, 6, 7,8];
console.log(array_values.length);
// 8 
array_values.length = 0;  
console.log(array_values.length);
// 0
console.log(array_values);
// []

11. Optional Chaining

The optional chaining ?. stops the evaluation if the value before ?. is undefined or null and returns undefined.

const user = {
  employee: {
    name: “Kapil”
  }
};
user.employee?.name;
// Output: “Kapil”
user.employ?.name;
// Output: undefined
user.employ.name
// Output: VM21616:1 Uncaught TypeError: Cannot read property ‘name’ of undefined

12. Arrow Functions

Although an arrow function expression is a more compact alternative to a traditional function expression, it has limitations and cannot be used in all situations. They refer to the environment in which they are defined because they have lexical scope (parental scope) and do not have their own this and arguments.

const person = {
name: ‘Kapil’,
sayName() {
    return this.name;
    }
}
person.sayName();
// Output
“Kapil”

However, 

const person = {
name: ‘Kapil’,
sayName : () => {
    return this.name;
    }
}
person.sayName();
// Output
“”

13. Rounding numbers

The toFixed() method converts a number rounding to a specified number of decimals.

var pi =3.1415;
pi = pi.toFixed(2);  // pi will be equal to 3.14

Note: toFixed() returns a string and not a number.

14. Quicker for loops compare to legacy onces

  • for and for..in gets you index by default, but you can use arr[index].
  • for..in accepts non numeric as well so avoid it.
  • forEach, for…of gets you an element directly.
  • forEach can get you an index also but for…of can’t.
  • for and for…of considers holes in array but other 2 do not.  

15. Ternary Operator is cool

You can avoid nested conditional if..elseif..elseif with ternary operators.

function Fever(temp) {
    return temp > 97 ? ‘Visit Doctor!’
      : temp < 97 ? ‘Go Out and Play!!’
      : temp === 97 ? ‘Take Some Rest!’;
}

// Output
Fever(97): “Take Some Rest!”
Fever(100): “Visit Doctor!”

Conclusion

In this article, we shared with you the top 15 tips for improving JavaScript performance. If you go ahead and implement all these changes, you will notice a significant improvement in the speed of your JavaScript web development and applications.

It may be difficult to remember all of these tips all at once, especially if you are working under a time constraint. If you require any additional assistance, please contact us. We hope you enjoyed this blog; please return to this space for more insightful content.

About Galaxy Weblinks

We specialize in delivering end-to-end software design & development services and have hands-on experience with popular front-end and back-end languages like JavaScript. Our back-end and front-end engineers also help in improving security, reliability, and features to make sure your business application scales and remain secure.

10 VS Code Shortcuts To Code Faster In 2021

VS Code is loaded with lots of features by default that makes it powerful, even without the themes and extensions.

However, even experienced developers may not be aware of these useful features. Not everyone has the time to explore every tip and trick to find the ones that help them code faster. With each new update of VS Code, new features are introduced that often remain unexplored.

Here we’ve listed the 10 most useful VS Code tricks that can help you code faster this year.

1. Multi cursor selection

Defining multiple cursors helps in editing a document in more places simultaneously. Multi-cursor mode can be used for column-mode editing. You can place as many cursors in as many places as you want in a single editor view. You can continue editing once you have your cursors placed, and all operations will be implemented to all cursors at the same time.

To set cursors above or below the current position use Ctrl+Alt+Up or Ctrl+Alt+Down. To add cursors at arbitrary positions, select a position with your mouse and use Alt+Click. You can add additional cursors to all events of the current selection with Ctrl+Shift+L. To go back to a single cursor, just hit the Escape key.

2. Open/Close terminal with one hand

It is convenient to have a pop-open terminal window in VS Code. No need to switch out to another application window to deal with the terminal. It’s also readily accessible by pressing Ctrl + (the backtick key).

What’s nice about this feature is that the shortcut is a one-hand operation, so you can open or shut the window without touching the mouse.

3. Type to find any command

From Command Palette, you have access to all of the functionality of VS Code, including keyboard shortcuts for the most common operations and any registered command, or those provided by add-ons. Press Ctrl-Shift-P and start typing.

Further, if there’s a key binding related to a given command, it’s available in the type-to-search drop-down list. So that you can cut straight to the key shortcut in the future.

4. Open the new editor window to the side

Sometimes we want to open the definition to the side so that we can use “Command + Option + Click.”

5. Github pull requests and issues 

If you are working with Github, you can install Github pull requests and issues extension to search for any project and clone a repository to the editor itself. This saves you time to go directly to github and bring it to your terminal.

6. Source Code Navigation

When we read codes or after reading the definition, we often need to jump from the source code to their definition. Here you can use the following shortcut keys to complete the source code navigation.

Go to Definition: F12

Go back: Control + –

Go Forward: Control + Shift + –

You can also use F12 to continuously jump between different definitions. When you want to go back to continue coding, you can use “ control + -” to go back, but the efficiency of doing so is too low. At this time, you can go back to coding with only one step i.e. by using the command “Go to Last Edit Location.”

7. Grid Editor Layout

Editor groups are placed in vertical columns, by default (for example, when you split an editor to open it to the side). You can easily place editor groups in any layout you like, both vertically and horizontally:

You can create empty editor groups, to support flexible layouts. There are also a predefined set of editor layouts in the new View > Editor Layout menu:

8. Code Folding

Code folding is required when the file size is big and you just want to get an overall understanding of the code.

1. To fold the innermost uncollapsed region at the cursor:

On Mac: Command+ Option + [

On Ubuntu/Windows: Ctrl + Shift + [

2. Unfold will re-open the collapsed region at the cursor:

On Mac: Command+ Option + ]

On Ubuntu/Windows: Ctrl + Shift + ]

9. See Visual Studio Code’s internal process list

Similar to any other task manager in every OS, VS Code has its own internal Process Explorer that lets you see a list of all the current subprocesses running inside the code editor. You can see every externally spawned process, extension, window, and so on. For each process, Process Explorer displays the memory usage, the CPU, and process ID.

Search for “Process Explorer” in the command palette or just select “Open Process Explorer” from the Help menu to open Process Explorer. You can right-click on a process to kill it or copy its information.

10. Remote Development

Since remote development has become the norm for developers, many have started using remote development extension packs. This comes with remote wsl, containers, and ssh, or you can separately search for an extension that lets you work inside the browser, also known as VS Codespaces.

It is split into two components – the UI component which would run on the local machine and another one is the server component, which would let you run, edit and debug your code on the remote machine. The VS Code server can run anywhere, and the remote extension will help you communicate b/w VS Code and the server.

This helps avoid having huge mono repositories, where devs would connect to a huge vm and nothing would be available on their local machine so that they can deploy changes and fixes.

Give It A Shot!

Now that you are armed with the useful productivity tricks, go ahead and give it a try. Once you get the hang of all these shortcuts, you will wonder how you survived without them. You may even blow the minds of some of your Emacs or Vim friends or co-workers with your efficient coding tricks!

Galaxy Weblinks

We specialize in delivering end-to-end software design & development services and have hands-on experience with large, medium, and startup business development requirements. Our engineers also help in improving security, reliability, and features to make sure your business application scale and remain secure.