5 Progressed JavaScript Methods You Should Know
Tags: Javascript Development, Javascript Tips, JavaScript, Web Development, Programming

Are you looking for more JavaScript techniques?

If so, you’re in the right place.

In this article, I’ll show you 5 advanced JavaScript techniques I’m using to improve the quality of my codebase.

Let’s get right into it.

1. Closure

Closure is an important technique in Javascript. It means that an inner function always has access to the variables and parameters of its outer function, even after the outer function has returned.

We use closure to protect data that we don’t want to expose to the outer scope.

Let’s say you want to increase a counter variable one unit every time a button is clicked. Something like:

<button onclick=”increaseCounter()”>Increase Counter</button>

Simply, we can use a global to finish the task:

let counter = 0;function increaseCounter() {

counter++;

}

The problem is that the the counter variable can be change directly without calling increaseCounter() function.

So, let’s move the counter variable into the function:

function increaseCounter() {

let counter = 0;

counter++;

}

Nah, the counter variable will be reset to 0 every time the function is called.

It’s when closure comes into play:

const increaseCounter = (function() {

let counter = 0;



return function() {

counter = counter + 1;

console.log(counter);

};

})();

The IIFE run only once and initialize the counter variable with 0 then returns a function that can access the counter variable. So, when you call increaseCounter() , it will update the counter as expected.

2. Function Binding

I bet you used to face the problem where a this is not the this you expect. Specifically, when you pass a object method as a callback, this is lost. See the example below:

let book = {

title: ‘Learn JavaScript’,

printTitle() {

console.log(`Book’s title: ${this.title}`);

}

}setTimeout(book.printTitle, 1000); // Book’s title: undefined

The printed text we expect is Book’s title: Learn JavaScript but we got Book’s title: undefined . It’s because the program doesn’t know about this anymore. The context is lost now.

To solve this problem, we can use function binding technique.

let book = {

title: ‘Learn JavaScript’,

printTitle() {

console.log(`Book’s title: ${this.title}`);

}

}let printTitle = book.printTitle.bind(book);setTimeout(printTitle, 1000); // Book’s title: JavaScript

I wrote a detailed article about function binding. If you want to know more about this technique, you should check out the article:

3. Tasks Scheduling

JavaScript gives you two simple ways to schedule tasks execution:

setInterval() runs a task repeatedly at a certain interval of time:

function sayHello() {

console.log(‘Hello from the other side!’);

}setInterval(sayHello, 1000);

In the snippet above, the sayHello() function is executed repeatedly after every 1000ms.

setTimeout() runs a task once after a certain interval of time:

function sayHello() {

console.log(‘Hello from the other side!’);

}setTimeout(sayHello, 1000);

Now, the sayHello() function will run only once after 1000ms.

4. Recursion

Some tasks in programming are extremely hard to solve in traditional ways. They require a lot of logic and thinking. However, it’s much easier if you apply the recursion technique. This is a technique that breaks a big task into several smaller and simpler tasks of the same kind which you can understand without too much thinking.

You will know the recursion technique is using when you see a function’s calling itself.

For example, we will write a function that takes x , and n as parameters and returns the value of multiplying x by itself n times.

For the traditional approach, we will use loop statement:

function pow(x, n) {

let result = 1; for (let i = 0; i < n; i++) {

result = result * x;

} return result;

}console.log(pow(3, 5)); // 243

And when we apply recursion approach, it’ll be like this:

function pow(x, n) {

if (n === 1) {

return x;

} else {

return x * pow(x, n — 1);

}

}console.log(pow(3, 5)); // 243

When n === 1 , the result is so obvious. There’s nothing much to talk about here because pow(x, 1) will return x .

If n is greater than 1 , then we use our common sense in math to represent pow(x, n) as x * pow(x, n — 1) (example: x⁷ = x * x⁶). And we keep taking a step back like that until n === 1 .

The above is just a simple example of recursion that you can also easily implement in a traditional way. In your programming life, however, you will come across tasks that you would prefer to solve by using recursion for the sake of simplicity.

Of course, you can convert a recursion implementation to an iterative counterpart. But it will require a lot of effort in some cases. Not to mention your code will be ugly and hard to read.

Last but not least, recursion may harm the performance if you use it carelessly. So, use it wisely.

5. Define Namespaces

The more code you add to your project, the more chances for conflicts to happen.

One of the best ways to avoid conflicts is by using namespaces. This is a technique that allows you to wrap a part of your code under a unique name.

The simplest example of namespacing you may know but don’t realize it is objects:

let animal = {

move: () => {

console.log(‘Move!’);

},

jump: () => {

consle.log(‘Jump!’);

}

};

In the example, move() and jump() functions are namespaced under animal . To call them, we use animal.move() and animal.jump() .

In real world projects with big source code files, the way we use namespaces will be like this:

if (typeof APP === “undefined”) {

APP = {};

APP.ANIMAL = {};

}APP.ANIMAL.move = () => {

console.log(‘Move’);

};APP.ANIMAL.jump = () => {

console.log(‘Jump’);

};APP.ANIMAL.move(); // Move

APP.ANIMAL.jump(); // Jump

By creating a unique namespace like that, you can avoid all annoying conflicts.

Conclusion

Above are 5 JavaScript techniques I want to introduce you to improve the quality of your code. It would be great if you can apply them to your real projects.

Do you know other cool techniques? Please let me know in the comment below.

Hope you enjoy this article.