Register to get access to free programming courses with interactive exercises

Function parameters JavaScript fundamentals

Functions can not only return values, but also take them as parameters. We have already seen the parameters of functions many times before:

// Takes parameters of any type as an input 
console.log('i am a parameter');
// Takes two string parameters as an input
// The first one shows what we're looking for, the second one — what we're changing
'google'.replace('go', 'mo'); // 'moogle'
// Takes two numeral parameters as an input
// The first one is the initial index (including), the second one is the final index (not including)
'hexlet'.slice(1, 3); // 'ex'

In this lesson, we will learn how to create functions that take parameters as an input. Imagine we need to implement a function getLastChar() that returns the last character of a string passed as a parameter to it. The function will look like this:

// Passing parameters directly without variables
getLastChar('Hexlet'); // 't'
// Passing parameters through variables
const name1 = 'Hexlet';
getLastChar(name1); // 't'
const name2 = 'Goo';
getLastChar(name2); // 'o'

From the description and code examples, we can draw the following conclusions:

  • We need to define a function getLastChar()
  • The function should take a single string parameter as an input
  • The function must return a string type value

Definition of the function:

const getLastChar = (str) => {
  // Calculate the index of the last character as a string length - 1
  return str[str.length - 1];
}

Let's analyze it. The name of the parameter (str) is given in brackets. We do not know exactly what value we are working with inside the function, so the parameters are always described as variables.

The parameter name can be anything; it has nothing to do with how the function is called. The main thing is that the name should reflect the meaning of the value contained inside. The specific value of the parameter will depend on the call to that function.

Two, three or more parameters can be specified in exactly the same way. Each parameter is separated from the other by a comma.

// Function for calculating the average number
const average = (a, b) => {
  return (a + b) / 2;
}

average(1, 5); // 3
average(1, 2); // 1.5

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY