Why use a function?

You can reuse code: Define the code once, and use it many times.

Let's look at some lines of code representing the process of making a sandwich:

// make a ham sandwich the old way
console.log('put a slice of bread');
console.log('put ham slice');
console.log('put another slice of bread');
console.log('A ham sandwich');

// make another ham sandwich
console.log('put a slice of bread');
console.log('put ham slice');
console.log('put another slice of bread');
console.log('A ham sandwich');

// make another? Ahh?! :-(

Define a function to make a sandwich

function sandwich() {
    console.log('put a slice of bread');
    console.log('put ham slice');
    console.log('put another slice of bread');
    console.log('You got a ham sandwich!');
}

// Call the function to make a sandwich:
sandwich();

Each time when sandwich() is called, the console will show the result of making a sandwich:

put a slice of bread
put ham slice
put another slice of bread
You got a ham sandwich!

If you like a few more sandwich, it's easy:

// make another
sandwich()
// make more, ok!
sandwich()
sandwich()
...

If you want 99 sandwich, you can easily call the function in a for loop:

for (let i = 1; i < 100; i++) { 
    sandwich();
}

Now you see? Functions provide a high degree of code reusing. Your job as a programmer is much easier with functions.

Other than reusing, function makes it possible that you can use the same code many times with different arguments, to produce different results. Let's look at the function parameters in next lesson.

results matching ""

    No results matching ""