How to Write Your First JavaScript Function
A beginner-friendly guide to creating simple functions in JavaScript.
Functions are one of the most important building blocks in JavaScript. They allow you to group code into reusable blocks, so you can run the same set of instructions whenever you want without rewriting the code. In this tutorial, you will learn how to write your very first JavaScript function.
A function in JavaScript is defined using the function keyword, followed by a name, parentheses (), and curly braces {}. Inside the curly braces, you write the code you want to run each time the function is called. Functions can also accept inputs, called parameters, and can return a value back to where they were called.
function greet() {
console.log('Hello, world!');
}
greet(); // This calls the function and prints 'Hello, world!'In the example above, the function greet is defined to print 'Hello, world!' to the console. You call the function by writing its name followed by parentheses. This runs the code inside the function. If you forget the parentheses, like just writing greet, the function won't run — it will only refer to the function definition itself.