How to Create Function in JavaScript: Syntax and Examples
In JavaScript, you create a function using the
function keyword followed by a name, parentheses (), and curly braces {} containing the code to run. You can also create functions using arrow syntax with () => {} for shorter code.Syntax
A JavaScript function is created using the function keyword, followed by the function name, parentheses () for parameters, and curly braces {} enclosing the code block. Parameters are optional and allow you to pass values into the function.
Example parts:
- function: keyword to declare a function
- name: the function's identifier
- parameters: inputs inside parentheses, separated by commas
- body: code inside curly braces that runs when the function is called
javascript
function greet(name) { console.log('Hello, ' + name + '!'); }
Example
This example shows a function named greet that takes a name parameter and prints a greeting message. It demonstrates how to define and call a function.
javascript
function greet(name) { console.log(`Hello, ${name}!`); } greet('Alice');
Output
Hello, Alice!
Common Pitfalls
Common mistakes include forgetting parentheses when calling a function, missing curly braces, or not passing required parameters. Another pitfall is confusing function declaration with function expression or arrow functions.
Also, avoid naming functions with reserved words or starting names with numbers.
javascript
/* Wrong: missing parentheses when calling */ function sayHi() { console.log('Hi!'); } sayHi; // Does nothing /* Right: call with parentheses */ sayHi();
Output
Hi!
Quick Reference
| Syntax | Description |
|---|---|
| function name(params) { code } | Declare a named function |
| const name = function(params) { code } | Function expression assigned to a variable |
| const name = (params) => { code } | Arrow function syntax |
| name() | Call a function |
Key Takeaways
Use the function keyword followed by name and parentheses to create a function.
Call functions with parentheses to run their code.
Parameters let you pass data into functions.
Arrow functions provide a shorter syntax for creating functions.
Avoid common mistakes like missing parentheses or curly braces.