Simple function called
greeting
that shows the following message:
Hello, my name is john
using
alert
built-in function. Then we can call the function by typing the function name followed by parenthesis:
greeting();
function greeting() {
    alert('Hello, my name is john');
}
greeting();
The same function with more flexibility. We pass the parameter
name
to the function, so it can be called for different users. When we call the function, we need to pass a string, as an argument
greeting('John');
function greeting(name) {
    alert('Hello, my name is ' + name);
}
greeting('John');
The same function with several parameters. We added another parameter
age
to the function
function greeting(name, age) {
    alert('Hello, my name is ' + name + ' and I am ' + age + ' years old');
}
greeting('John', 25);
The following function returns value, so that we can use the function in expressions
function doubleMe(number) {
    return 2*number;
}
console.log(3*doubleMe(50));  // 300
We can assign default values to parameters if they are not passed when the function gets called
function aboutMe(profession = 'student', name, city = 'Tbilisi' ) {
    console.log('I am a ' + profession + ' from ' + city + ' and my name is ' + name);
}
aboutMe(undefined, 'Valeri');
by Valeri Tandilashvili
4 years ago
JavaScript
Functions
The 10 Days of JavaScript
1
Pro tip: use ```triple backticks around text``` to write in code fences