DEV Community

Cover image for #1 Understanding Functions in JavaScript
Salihu Kutiriko Abubakar.
Salihu Kutiriko Abubakar.

Posted on • Updated on

#1 Understanding Functions in JavaScript

Introduction
Functions are a fundamental building block in JavaScript, allowing you to write reusable and modular code. A function is a block of code designed to perform a particular task. It helps in organizing code and making it reusable.

//Function Syntax
function functionName(parameters) {
 // code to be executed 
}
//Function Declaration
function greet() {
 console.log('Hello, world!'); 
}
//Function Expression
const greet = function() {
 console.log('Hello, world!'); 
}
//Arrow Functions
//Arrow functions, introduced in ES6, provide a shorter syntax.
const greet = () => {
 console.log('Hello, world!'); 
}
//Parameters
//Functions can take parameters, which are values you pass to the function.
//They are also dynamic and reusable
const greet = function(name) {
 console.log('Hello, ' + name + '!'); 
}
greet('Alice'); // Output: Hello, Alice!
greet('Mike'); // Output: Hello, Mike!
//Default Parameter
//Functions can take default parameters.
const greet = function(name = 'Guess') {
 console.log('Hello, ' + name + '!'); 
}
greet(); // Output: Hello, Guess!
//If greet('Alice') contains a value, then the value takes priority.
//Output: Hello, Alice
//Function return value
//Functions can return values using then 'return' statement.
const add = (a,b) => {
 return a + b; 
}
add(5, 3)//Output: 8
Enter fullscreen mode Exit fullscreen mode

Functions are powerful tools for writing clean and efficient code. Keep practicing and experimenting with different types of functions.

Top comments (0)