JavaScript Basics Reference
1. What is a Function?
A function is a block of code designed to perform a specific task.
It is executed when "called" or "invoked".
Syntax:
function functionName(parameters) {
// Code to execute
}
2. Function Declaration
Example:
function greet() {
console.log("Hello World");
}
greet(); // Calls the function
3. Parameters & Arguments
Parameters: Variables listed in the function definition.
Arguments: Values passed to the function when it is called.
Example:
function greetUser(name) {
console.log("Hello " + name);
}
greetUser("Alice"); // Hello Alice
4. Return Statement
JavaScript Basics Reference
Functions can return a value.
Example:
function add(a, b) {
return a + b;
}
let sum = add(5, 3); // sum = 8
5. Function Expressions
A function can be stored in a variable.
Example:
const greet = function() {
console.log("Hi there!");
};
greet();
6. Arrow Functions
Shorter syntax for writing functions.
Example:
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
7. Default Parameters
You can set default values for parameters.
JavaScript Basics Reference
Example:
function greet(name = "Guest") {
console.log("Hello " + name);
}
greet(); // Hello Guest
8. Function Scope
Variables declared inside a function are local to that function.
Example:
function test() {
let x = 10; // local variable
console.log(x);
}
test();
// console.log(x); // Error: x is not defined