A function is a named block of code you can run again and again. You already used console.log(); now you will write your own.
function greet(name) {
return `Namaste, ${name}!`;
}
console.log(greet("Sita"));
console.log(greet("Hari"));
Output:
Namaste, Sita!
Namaste, Hari!
Values go in through parameters (name) and come back out with return.
function area(length, width) {
return length * width;
}
console.log(area(12, 9));
console.log(area(3, 4) + area(2, 2));
Output:
108
16
Arrow functions
A shorter way to write functions. For one-line functions the return is implied.
const double = n => n * 2;
const add = (a, b) => a + b;
console.log(double(21));
console.log(add(5, 7));
Output:
42
12
Default values
function priceWithTax(price, rate = 13) {
return price + (price * rate) / 100;
}
console.log(priceWithTax(1000));
console.log(priceWithTax(1000, 5));
Output:
1130
1050
A function that decides
function grade(marks) {
if (marks >= 80) return "Distinction";
if (marks >= 60) return "First division";
if (marks >= 40) return "Pass";
return "Fail";
}
console.log([91, 64, 45, 20].map(grade));
Output:
[ 'Distinction', 'First division', 'Pass', 'Fail' ]
A good function does one clear job and has a clear name. If you are copying and pasting the same lines, that is a sign to make a function.
Try it yourself
- Write
isEven(n)that returns true or false. - Write
average(numbers)for an array of numbers. - Rewrite
doubleas a normal function using thefunctionkeyword.
Next lesson: JavaScript in a web page.

Comments
Loading comments…