Writing Your First JavaScript Functions Step by Step
Learn how to write and use simple JavaScript functions with clear explanations and examples.
JavaScript functions are blocks of code designed to perform a particular task. They are one of the fundamental building blocks of any JavaScript program. In this tutorial, we'll learn how to write your first JavaScript function step by step.
A function starts with the keyword 'function', followed by a name, a list of parameters inside parentheses, and a block of code inside curly braces. When you call a function, the code inside runs. Functions can optionally return a value back to where they were called.
function greet() {
console.log('Hello, world!');
}
greet();In this example, 'greet' is a function that prints 'Hello, world!' to the console when called by 'greet()'. If you see an error like "greet is not defined", it usually means you called the function before declaring it or misspelled the function name. Make sure your function is declared before you call it, and names match exactly.
Functions can also accept parameters, which are inputs you provide to customize what the function does. Here's how to write a function that takes a name and greets that person:
function greetPerson(name) {
console.log('Hello, ' + name + '!');
}
greetPerson('Alice');This function greets whoever's name you provide. If you forget to pass an argument when calling this function, the output will be 'Hello, undefined!'. This happens because 'name' has no value. To fix this, always pass the expected arguments when calling functions.
Functions can also return values using the 'return' keyword. This means the function gives back a result that can be used elsewhere in your code.
function add(a, b) {
return a + b;
}
const sum = add(5, 3);
console.log(sum); // Outputs: 8In the 'add' function, two numbers are passed as parameters, added, and the result is returned. If you see an error like 'Unexpected token return', it means the 'return' keyword is used outside a function or misplaced. Always place 'return' inside function blocks.
By understanding how to declare functions, pass parameters, and return values, you can start writing flexible and reusable code in JavaScript. Keep practicing by writing simple functions, and soon you'll be comfortable creating more complex programs.