Learn JavaScript
Lesson 1 - Introduction To JavaScript
Lesson 2 - Basic JavaScript Syntax
Lesson 3 - Control Flow
Lesson 5 - Basic Data Structures
Lesson 6 - Basic String Operations
Lesson 7 - Basic Array Operations
Lesson 8 - Exception Handling
Lesson 9 - Packages
Lesson 10 - User Input
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.