Lesson 7 of 15
Functions
Functions
Functions are reusable blocks of code. Declare them with the function keyword:
function add(a, b) {
return a + b;
}
console.log(add(3, 4)); // 7
console.log(add(10, 20)); // 30
Default Parameters
Parameters can have default values, used when the caller omits the argument:
function greet(name, greeting) {
if (greeting === undefined) greeting = "Hello";
return greeting + ", " + name + "!";
}
console.log(greet("Alice")); // Hello, Alice!
console.log(greet("Bob", "Hi")); // Hi, Bob!
Or with the shorthand default syntax:
function greet(name, greeting = "Hello") {
return greeting + ", " + name + "!";
}
Return Values
Every function returns a value. Without an explicit return, it returns undefined.
function square(n) {
return n * n;
}
console.log(square(5)); // 25
console.log(square(12)); // 144
Your Task
Write function power(base, exp) that returns base raised to the power exp. Use a loop — do not use Math.pow.
JavaScript loading...
Loading...
Click "Run" to execute your code.