1 June 2017, 11:23

javascript 101 ~ funky functions part 1

Funky functions part 1.

JavaScript has its quirks and that's one of the many things I like about it, but it does have some potential gotchas that are worth noting. In the 'Funky functions' series I'll be looking at some of these quirks as well as taking a deeper dive into functions in JavaScript.

JavaScript really shines when it comes to functions and can do some really powerful things which I'm excited to explore. Like many misunderstood creatures there is often depth and complexity to be found underneath the surface.

Let's start by looking at a basic function:

In the above example we can see the structure of a function, first we write the key word 'function' --> give it a name (in this case 'basic')--> state any parameters ( in this case a and b ) --> open the body { --> what you want to do and any conditions you want to meet (none in this case) --> return the result of adding the two parameters --> }; close the body.

Then we store the result of the function in a variable called 'result'. Notice how we call the function like this 'basic( 2, 3 )' instead of a and b we now give the function something to work with. In reality 2 is assigned to a and 3 is assigned to b as the function runs.

note: when we define a function a and b are parameters and when we call a function a and b are arguments.

Now here's the interesting part there are also two implicit function parameters that are passed to functions silently. They are called arguments and this. They can be accessed just like any other parameter within the body of the function ( the do stuff part ).

The this parameter is the function context ( we'll explore this at another time ) and an arguments parameter that represents all arguments passed to the function.

note: ES6 provides a new kind of parameter the so-called rest parameter that has a prefix of three dots (...). The rest parameter allows you to represent an indefinite number of arguments as an array.

let's try something.

See the Pen Funky functions part 1 by Adam Harpur (@harps116) on CodePen.

Play around with this and remove "use strict" and you will start to see how the arguments parameter works.

a quick ES6 example

The rest parameter that has a prefix of three dots (...).Have a look:

args is an array so we can use the for of loop

In the next funky functions we will look at this and play around with the idea of context.

Some additional resources:

← JavaScript 101 ~ Better Event Handling
Node js ~ sequelize and sqlite →