Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 4 - Functions

4.1 Defining Functions

In JavaScript, you can define a function using the function keyword, followed by the function name and parentheses (). The code block to be executed is enclosed in curly braces {}.

Have a look at the following line of code:

console.log("Good Morning, Alex");

This will greet your friend Alex.

Now, think you have five friends. How do you greet them?

You might think to write some code as follows:

console.log("Good Morning, Alex");
console.log("Good Morning, John");
console.log("Good Morning, David");
console.log("Good Morning, Felix");
console.log("Good Morning, Ethan");

However, there is a very easy and smart way to do this. Follow the below example:

function greet(name) {
 console.log("Hello, " + name);
}

greet("Alex");
greet("John");
greet("David");
greet("Felix");
greet("Ethan");

In the above example, we declared a function greet() that takes a name to greet. You don't have to write the line console.log("Good Morning, Alex"); for each of your friends. All you need is to pass their name to the greet() function.