Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Parameters

Parameters make a function universal: the same calculatePrice function can price any product if you pass it the right data. A reminder of the terms: a parameter is a variable in the function declaration, an argument is the value passed in the call.

Several parameters

Parameters are listed with commas. Arguments in the call are separated with commas too:

function add(a, b) {
  return a + b;
}
 
console.log(add(2, 3)); // 5

There can be any number of parameters, but with more than three or four the function becomes awkward to use.

Order matters

Arguments go into parameters in order: the first into the first, the second into the second. Variable names in the call play no role:

function describe(name, age) {
  return `${name}, aged ${age}`;
}
 
console.log(describe('Anna', 25)); // Anna, aged 25
console.log(describe(25, 'Anna')); // 25, aged Anna

If you mix up the order, JavaScript reports no error — you simply get a wrong result.

Missing arguments

If an argument is not passed, the parameter gets the value undefined. Extra arguments, on the other hand, are simply ignored:

function greet(name) {
  return `Hello, ${name}!`;
}
 
console.log(greet());               // Hello, undefined!
console.log(greet('Anna', 'Oleg')); // Hello, Anna!

Default values

A parameter can be given a default value with =. It is used when the argument is not passed:

function greet(name = 'guest') {
  return `Hello, ${name}!`;
}
 
console.log(greet());       // Hello, guest!
console.log(greet('Anna')); // Hello, Anna!

The default also applies when undefined is passed explicitly. But null, 0 and the empty string count as normal arguments.

A parameter is a copy of the value

A parameter is a new variable inside the function. Changing it does not change the outside variable that was passed as the argument:

function addBonus(score) {
  score += 10;
  return score;
}
 
const myScore = 50;
 
console.log(addBonus(myScore)); // 60
console.log(myScore);           // 50

This is how numbers, strings and other simple values behave. Arrays and objects have a twist — it is covered in their chapters.

Common mistake

Parameters with default values go at the end of the list. If such a parameter comes first, it cannot be skipped — the argument still takes the first place:

function price(currency = '$', amount) {
  return `${currency}${amount}`;
}
 
console.log(price(100)); // 100undefined

The right order is required parameters first, then optional ones: function price(amount, currency = '$').

Thanks for reading!

Donate to the site — we work hard for you.