Functions
Functions are reusable blocks of code. They follow the DRY principle — Don't Repeat Yourself.
Function Declaration
function greet(name) {
return 'Hello, ' + name + '!'
}
console.log(greet('Alice')) // Hello, Alice!
Function Expression
const greet = function(name) {
return 'Hello, ' + name + '!'
}
console.log(greet('Bob')) // Hello, Bob!
Arrow Function
const greet = (name) => 'Hello, ' + name + '!'
// Shorter version (one parameter, one expression):
const greet = name => \`Hello, \${name}!\`
console.log(greet('Carol')) // Hello, Carol!
Naming Conventions
Use action verbs to name functions. Common prefixes:
get— return a value:getUserName()calc— calculate:calcTotal()create— create something:createUser()check— return boolean:checkIsAdmin()
Parameters vs Arguments
// 'name' is a parameter (in definition)
function greet(name) {
return \`Hello, \${name}!\`
}
// 'Alice' is an argument (in call)
greet('Alice')