DEV Community

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

Posted on • Edited on

1

#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.

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay