JavaScript functions

Functions are famously called first-class citizens of the JavaScript world. Functions can smoothly be treated as a variable, 

For example, if we execute this in a browser:

function myFunction(a, b) {
  return a * b;
}
var x = myFunction;
console.log(x(3,4));

It will log 12. The declaration of myFunction makes it a 'value', which is assigned to a variable 'x'. Notice that there are no parenthesis in that assignment.
Next, we have a log that invokes myFunction by applying the parenthesis () operator on the variable. The log statement logs the return value of myFunction, which is the product of 3 and 4.

Let's say we forget the parenthesis:
console.log(x);
This will log the function itself! Try it out in your browser by enabling the console display via the 'developer tools' option.

Of course, this will just call the function normally:
var x = myFunction(3,4);
It's just the application of the () operator to call a function.


Comments

  1. This article gives a clear introduction to how JavaScript functions can be treated as first-class values. The example demonstrates how a function can be assigned to a variable and then invoked through that variable, while leaving out the parentheses results in the function itself being logged rather than executed.

    The distinction between referencing a function and calling it is an important concept when working with JavaScript. Developers looking to strengthen these fundamentals can explore JavaScript Course in Chennai, particularly for building a stronger understanding of functions and other core language features.

    ReplyDelete
  2. The comparison with function pointers is also interesting because it encourages readers to think about how functions can be passed around and used as values. Continuing with structured practice through JavaScript Training in Chennai can help reinforce these concepts through broader JavaScript development exercises.

    ReplyDelete

Post a Comment

Popular posts from this blog

Polymorphism

Data Schema and Blobs

JavaScript data-types