JavaScript Examples
A collection of practical JavaScript examples to help you understand common patterns and use cases.
Basic Function Example
Functions are fundamental building blocks in JavaScript. They are reusable blocks of code that perform a specific task. This example shows a simple function that adds two numbers.
Functions help organize code, make it more readable, and allow for easy reuse.
Live Example
functions.js
// A simple function to add two numbers
function add(a, b) {
return a + b;
}
// Calling the function and storing the result
let sum = add(5, 10);
// Displaying the result in the console
console.log(sum); // Output: 15
// Example with a string
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Alice")); // Output: "Hello, Alice!"
Console Output
> 15
> "Hello, Alice!"
Key Concepts
Key parts of a function declaration:
| Concept | Description |
|---|---|
| function | Keyword to declare a new function. |
| add(a, b) | `add` is the function name. `(a, b)` are the parameters (inputs) the function accepts. |
| return a + b; | The `return` statement specifies the value to be returned by the function. |
| add(5, 10) | This is a function call, executing the function with arguments `5` and `10`. |