Twitter | Facebook | Instagram | YouTube | LinkedIn

Home >> Blog >>

How To Write A JavaScript Function

By Adam Patel on May 16th, 2021

black flat screen computer monitor

A function is a bunch of code that runs when called.

Below is the code for the basic structure of a Javascript function.

function nameOfFunction(){
      // write the code here
}

Let’s break it down:

We start with the word ‘function’, followed by a space. This is so that the system knows we’re writing a function.

Next, we have the name of the function written in ‘JavaScript case’ (Don’t Google this – it’s not an official term, just my name for it). It’s not imperative, but it is a well respected convention in Javascript circles. All you do is write the first word in lowercase, followed by camel case for every additional word. No spaces.

Immediately after the name of the function is a pair of brackets like this: (). If the function takes arguments, these must be stated between the brackets. An argument is any type of input data the function requires in order to ‘work’ – for example if you made a function that determines whether a number is divisible by 6 or not, you’d have to provide the number as an argument, for the function to work. The code would look like this:

function divisibeBySeven(num){
        // code here
}

Immediately after the brackets are a pair of curly braces. It is between these curly braces where the Javascript function code will be written.

JavaScript functions can be used for standard programming tasks, for example finding the lowest number in a sequence or fizzbuzz or whatever, as well as DOM manipulation, which is, on the whole, unique to JavaScript.