Categories

Javascript Functions

Posted on: December 26, 2016 by Dimitar Ivanov

The JavaScript language has a great variety of definition methods for
functions. Knowing the differences between them helps to make your code
better. This article describes the syntax and discusses their strengths
and weaknesses. Its aim is to go through all traditional and modern ways
to create a function in javascript.

function declaration

The most popular way to define a function in javascript language is a
function declaration. Its syntax includes the
function keyword, followed by the function name and function
parameters enclosed in parentheses. While the parameters are optional, the
parentheses are mandatory. The function body is enclosed in curly braces.

function square(x) {
return x * x;
}
square(3); // 9

function expression

Also known as function literal, it creates a variable and store a function
into. The optional name can be used in recursive functions or by debuggers and
dev tools.

Function declarations are hoisted to the
top of their scope. This is not valid for function expressions. That's why
a function expression could not be invoked before being assigned to a
variable. And that's the main difference between them.

The Function constructor

The Function constructor creates a new
object with type of function. It syntax includes the new keyword
right before the Function keyword. Then follows a multiple
parameters (optional) and function body which are enclosed in parentheses.
However, the use of Function constructor to create functions is not recommended.

arrow functions

The ES6 fat arrow functions has some
differences compared with traditional function expressions. They have
a shorter syntax, always are anonymous, does not change the value of
this, do not own arguments object and can't
be used as constructor functions.

If you have questions about javascript functions, leave a comment below.
Thanks so much for reading.

Dimitar Ivanov

Dimitar Ivanov is a senior LAMP developer, javascript engineer, web performance-obsessed.
He is programming since 2003 and loves to build web applications.
You can find him on Twitter,
LinkedIn and
GitHub.

Subscribe to our newsletter

Join our mailing list and stay tuned! Never miss out news about Zino UI, new releases, or even blog post.