JavaScript Fundamentals #3

I want to preface this post by saying that these Javascript “Fundamentals” posts really aren’t about the fundamentals, but really about the intricacies and under-the-hood principles that make Javascript such a powerful language. Specifically, these are topics that I found interesting that changes my perspective on JavaScript programming and why it is such a cool language.

I learned a bit more about functions and how they are used to make JavaScript coding much “safer”.

First, what is the difference between a function statement and a function expression? Don’t they do the same thing? Under the hood, they do not!

This is a function statement


function greet(name) {...}
 

And this is a function expression


var greetFunc = function(name) {...}
 

The function statement basically puts an invocable function statement into memory. It is called by invoking “greet();”. Nothing really special about that.

On the other hand, a function expression is interesting because it stores a function as an object! This allows for a lot of flexibility with the object. However, there is something interesting that we can do with this, and that is called an Immediately Invoked Function Expression.


var greetFunc = function(name) {
 return "hi";
}();
 

This is an Immediately Invoked Function Expression, signified by the ‘()’ at the end of the function declaration. Basically, when this line is passed in the syntax analyzer, it is called immediately. Instead of a function object being stored in the greetFunc variable, we have the string “hi”. But what if instead, we put in another function declaration as the return? We have what is called closures.


var greetFunc = function(name) {
 return function(whattosay) {
  console.log(whattosay + ' ' + name);
 }
}('Pedro');
 

Now in this piece of code, greetFunc is a function object of the returned function object! If we pass in something like


 greetFunc('Good evening');
 

we get a string “Good evening Pedro”. The “Pedro” string object is saved into the function object, and that is called a closure. Where the JavaScript engine will ensure that a function has access to the variables it is supposed to in its execution context.

This is all I have for now about the power of functions and closures! I’m hoping to explore more deeply into this topic, and hopefully you could get something out of this and contribute.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s