Développeur Web - OC - Fabien
👨‍👦

What's an argument ?

 
Let's say you want to make a function displayAllNames() display all names in an array
function displayAllNames() { for (let elem of array) { console.log(elem.name) } }
 
Cool. You have a fonction. Now you need an array, right ? 😉Let's say you have 2 students
const array = [ { name: 'remi', age: 23, location: 'paris' }, { name: 'julie', age: 50, location: 'angers' } ]
 
Great. Now you can simply use the function to display all names
const array = [...] function displayAllNames() { ... } displayAllNames() // When executing this file, you would get all names from students array
 
The problem is: what if you want to display names from mutiple arrays ?
Imagine that now, you have a SECOND array of students:
const array2 = [ { name: 'paul', age: 30, location: 'marseille' }, { name: 'caroline', age: 45, location: 'brest' } ]
 
How would you display names from BOTH arrays ?
Until now, our function displayAllNames() only works for one array at a time (in our example, with a variable called array)
That's where you should use arguments.
const array = [...] const array2 // here, we say 'ok, this function needs something to work. This will be called array' function displayAllNames(array) { ... } // here, we say 'ok, display names from array' displayAllNames(array) // here, we say 'ok, display names from array1' displayAllNames(array1)
 
Now you see why we need arguments. It keeps you from having to repeat code.
You can simply call the same function, this time with a different argument.
 
Metaphore time ❤️: Imagine you have a robot that could make juice out of fruits. It would work the same way. One time, you would give it apples to get juice. Another time, you would give it peaches to get juice. pressFruit(apple) then pressFruit(peach)
 
 
badge