JavaScript Functions - Exercise 1
Question 1: What is a function in JavaScript?
A function is a reusable block of code that performs a specific task. Functions can take inputs called parameters, run some logic, and optionally return a value. In JavaScript, you can create them with the function keyword or with arrow-function syntax.
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("World")); // Hello, World!
A function declaration gives a function a name and defines the code it runs. Call it by writing its name followed by parentheses.
function greet() {
console.log("Hello!");
}
greet();
Parameters are the named inputs in a function definition. Arguments are the values passed to the function when it is called.
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Ada"));
return sends a value back to the code that called the function and immediately ends that function's execution.
function add(left, right) {
return left + right;
}
const total = add(2, 3);
console.log(total);
An arrow function is a shorter function syntax that uses =>. For a single expression, it returns the expression implicitly.
const square = number => number * number;
console.log(square(4));
A default parameter provides a value when the caller omits an argument or passes undefined.
function greet(name = "friend") {
return `Hello, ${name}!`;
}
console.log(greet());
A callback is a function passed to another function so it can be called later.
function runTask(task) {
return task();
}
console.log(runTask(() => "Complete"));
Variables declared with let or const inside a function are available only within that function.
function showMessage() {
const message = "Inside the function";
console.log(message);
}
showMessage();
Yes. JavaScript functions are values, so you can assign them to variables and call them through those variables.
const sayHello = function () {
return "Hello!";
};
console.log(sayHello());
Function declarations are hoisted, so they can be called before their declaration appears in the source code.
sayHello();
function sayHello() {
console.log("Hello!");
}