JavaScript

 Why setting a function in a variable in JavaScript?

April 16, 2022

 Why setting a function in a variable in JavaScript?

In this article, you’ll learn why encapsulating a function in a variable can be a good strategy when you program in JavaScript.

function in a variable in JavaScript thumb

Hey you programmer, ok? Let’s learn the advantage of adding functions to variables in JavaScript!

First it is necessary to understand the concept of hoisting in JavaScript

Basically due to this feature, variables and functions are identified first in the code, but they are not initialized.

Take a look:

console.log(a);
var a = 10;

The console.log output will return as undefined, and notice that the variable “a” had not been declared yet, but by hoisting it has already been identified and the software will declare it later

So considering hoisting this is possible:

x();

function x() {
 console.log('teste');
}

The function will be hoisted to the top and we are able to execute it before it is actually created in the code

Thus causing a maintenance and evolution problem in the code

Assigning the function to a variable, we will not be able to use it until the point where it was declared is traversed

Take a closer look:

x();

var x = function() {
 console.log('teste');
}

Here the function will not be executed, thus having to respect the moment in which it is declared in the code, we will need to change the invocation of “x” to a line under the function

This will make the code less confusing for anyone who will later analyze and debug it.

This is the biggest differentiator when using functions in variables: the scope visibility

Conclusion

In this article we learned why setting a function in a variable in JavaScript is applied

We added an extra validation in the code, as it will have to respect the execution to be able to execute a function

This makes the code more standardized and easier to maintain.

Do you want to learn more about JavaScript and web development? Click here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x