A function declaration lets you create a reusable block of code that does a specific task. It helps keep your code organized and easy to understand.
0
0
Function declaration in Javascript
Introduction
When you want to perform the same action multiple times without rewriting code.
When you want to break a big problem into smaller, manageable parts.
When you want to give a name to a set of instructions for clarity.
When you want to reuse code in different places in your program.
When you want to make your code easier to test and fix.
Syntax
Javascript
function functionName(parameters) { // code to run }
The function keyword starts the declaration.
The function name should be descriptive and follow naming rules (letters, numbers, _, $).
Examples
A simple function named
greet that prints a greeting.Javascript
function greet() { console.log('Hello!'); }
A function named
add that takes two numbers and returns their sum.Javascript
function add(a, b) { return a + b; }
A function that takes a
name and prints it using a template string.Javascript
function sayName(name) { console.log(`My name is ${name}`); }
Sample Program
This program defines a function multiply that returns the product of two numbers. It then calls the function with 4 and 5 and prints the result.
Javascript
function multiply(x, y) { return x * y; } const result = multiply(4, 5); console.log('4 times 5 is', result);
OutputSuccess
Important Notes
You can call a function before its declaration because of how JavaScript loads functions (hoisting).
If a function does not return a value, it returns undefined by default.
Use clear names for functions to make your code easier to read.
Summary
Function declarations create named blocks of reusable code.
They help organize code and avoid repetition.
Functions can take inputs (parameters) and return outputs.