How to write a JavaScript function? Complete guide to functions in JavaScript

How to write a JavaScript function? Complete guide to functions in JavaScript

Consider the code below that calculates the average marks for Jason and Patrick:

// Marks for Jason
const marksJason = [95, 96, 97, 98, 99]

// Sum of marks for Jason
let sumJason = 0
for (let i = 0; i < marksJason.length; i++) {
    sumJason += marksJason[i]
}

// Average
const avgJason = sumJason / marksJason.length
console.log(avgJason)
//-------------------------------------------------
// Marks for Patrick
const marksPatrick = [90, 91, 92, 93, 94]

// Sum of marks for Jason
let sumPatrick = 0
for (let i = 0; i < marksPatrick.length; i++) {
    sumPatrick += marksPatrick[i]
}

// Average
const avgPatrick = sumPatrick / marksPatrick.length
console.log(avgPatrick)Code language: JavaScript (javascript)

The following is happening:

  • Marks for 5 subjects are given in an array
  • To find the total marks, a for loop is being used and the final sum is being stored in a variable
  • The final sum is divided by the length of the array to get the average
  • These steps are being done twice for Jason and Patrick

Imagine if you had to calculate the average marks for 20 students. You would have to add 12 lines of code for each one of them. There has to be a better way. And that is where functions in JavaScript come in.

If you want to code along head over to codedamn playgrounds. And if you want to access the code for this blog, head here.

What are Functions?

In the example above, you are calculating the average marks. The steps performed are the same, but the marks are different. What if you had a box that took the array of marks, and gave the average as the output without you explicitly writing the logic of calculating the average again and again?

Average Marks Function
Average Marks Function

The box can take Jason’s marks, Patrick’s marks, or any other student. For the values it is fed, it will always output the average! This box is called a function.

A function will always do the same task (in this case calculating average marks). It will run only when you ask it to. In the arrays blog, you learned to add an item to the end of the array with the push method. push is also a function! It always adds an element to the end of the array.

function functionName() {
    // code to run
}Code language: JavaScript (javascript)

Declare & Call a Function

function greeting() {
    console.log("Hello World!")
}Code language: JavaScript (javascript)

To declare a function, use the function keyword available in JavaScript. That is followed by the name of the function and square brackets: greeting(). Inside the curly braces, you write the code to run, which in this case is printing “Hello World!” to the console. And that is all you have to do to declare a function!

Function in JS
Click here to get the Code

You can see that even though the function has been declared above, there is nothing being printed inside the console. Why is that?

That is because to run a function, you have to actually call it.

Calling a Function
Click here to get the Code

To call a function, all you have to do is write down the function name along with the round brackets. This will tell JavaScript to run the code that is inside the function body. In this case, it is printing to the console.

If you don’t call a function, it just won’t run!

Arguments & Parameters in Functions

In the “Hello World!” example, let’s say you want to print, “Hello Jason!” or “Hello Patrick!” instead based on what the user wants. How would you do that? Should you write to separate functions as below?

function greetJason() {
    console.log("Hello Jason!")
}

function greetPatrick() {
    console.log("Hello Patrick!")
}Code language: JavaScript (javascript)

NO! That makes using functions completely useless because you are repeating the same code but with a different name. If only you could replace Jason with Patrick or any name the user inputs.

Well, you can! Functions can take values, not in their body inside the round brackets! The values passed in this manner are called parameters.

To pass a name to the function declare the function as follows:

function greet(name) {
    console.log(`Hello ${name}!`)
}Code language: JavaScript (javascript)

I have changed the string to a template literal. You can read more about it here.

The round brackets now have a name inside it. This is called an argument. You can replace this argument with a value!

Arguments & Parameters
Click here to get the Code

What’s happening?

  • You declare a function greet with an argument name
  • You call greet in lines 10 and 11, with values “Jason” and “Patrick”, respectively. These values are called parameters
  • JavaScript runs the code inside greet and replaces argument name, with the parameters, “Jason” and “Patrick” that you provide!

A function can have more than one argument as well! Try out:

function greet(greeting, name) {
    console.log(`${greeting} ${name}!`)
}

greet("Bonjour", "Jason")Code language: JavaScript (javascript)

Calculating the Average

Attempt to move the average marks logic into a function by yourself. Find some hints below:

  • Declare a function named average
  • Pass an argument marks to the function
  • Inside the function:
    • Create a variable, sumMarks and initialize it to 0
    • Use a for loop, to calculate the sum of all the values inside marks and store it in sumMarks
    • Calculate the average marks: sumMarks/marks.length
    • Print the average to the console
  • Call the function average and pass Jason’s marks as a parameter. Do the same for Patrick’s marks

Check out the solution below:

Calculate average marks with a function in JS
Click here to get the Code

If you have reached this point and understand whatever we have discussed till now, you are awesome! Try to write some simple functions to:

  • Calculate the area of a circle and print it on the console
  • Take a name and age of a person and print it on the console
  • Print the sum of the first ‘n’ natural numbers, with ‘n’ as the parameter

What if I ask you to calculate and print the average of the average marks of Jason and Patrick, i.e., an average of 97 & 92? How do you use the output from a function?

return Statement

The answer to the posed problem is pretty straightforward! JavaScript provides a return keyword that will enable us to utilize a function’s output in the rest of the program.

Update your function as below:

function average(marks) {
    let sumMarks = 0
    for (let i = 0; i < marksJason.length; i++) {
        sumMarks += marks[i]
    }

    let average = sumMarks / marks.length
    return average
}Code language: JavaScript (javascript)

I have replaced console.log(average) with return average. Now you can store the output of a function inside a variable and use it in your code.

To calculate the average of Jason and Patrick’s average, check out the code below:

return Statement
Click here to get the Code

It is very important to note, that once a function returns a value, any code inside the function after the return statement will be completely ignored. Try this out:

function average(marks) {
    let sumMarks = 0
    for (let i = 0; i < marksJason.length; i++) {
        sumMarks += marks[i]
    }

    let average = sumMarks / marks.length
    return average
    console.log("I am after the return statement!")
}Code language: JavaScript (javascript)

The statement, “I am after the return statement!”, will never be printed on the console.

A function can have multiple return statements as well. To see this in action, we will try to identify if a number passed to the function is odd or even.

Multiple return Statements in a Function
Click here to get the Code

What’s happening?

  • Declared a function oddEven that takes an argument num
  • num % 2 checks if the remainder is 0 when divided by 2. If it is, then the number is even, else it is odd.
  • If the number is even, return "Even", else return "Odd"

When the parameter is 6, the function returns “Even” and the else block is never executed or checked. Vice-versa is true for parameter 5.

Conclusion

That’s it for the article folks! You have learned how to declare and call functions in JavaScript. Along the way, you solved some easy but interesting problems.

Functions as a topic are not yet over. In the next blog, we will cover scoping and hoisting of JavaScript functions. We will also learn about arrow functions in JavaScript. See you then! Till then, practice, practice, and practice on codedamn playgrounds!

Sharing is caring

Did you like what Rishabh Mittal wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far

Curious about this topic? Continue your journey with these coding courses: