Write a function named square that takes a number as input and returns its square. Inside the function, declare a variable to store the result before returning it. Then log the output of the function using console.log(square(11));
Functions are reusable blocks of code designed to perform a particular task. They help make your code modular and organized.
You can define a function using the function
keyword:
function greet(name) {
return "Hello, " + name + "!";
}
Calling greet("Alice")
will return "Hello, Alice!"
.
Functions can take inputs (parameters) and return outputs.
Scope determines where variables are accessible.
Example:
function testScope() {
let localVar = "I'm local";
console.log(localVar); // works
}
console.log(localVar); // error — localVar is not defined
Proper use of scope helps prevent naming conflicts and bugs.