0
0
Javascriptprogramming~5 mins

Why functions are needed in Javascript

Choose your learning style9 modes available
Introduction

Functions help us organize code into small, reusable pieces. They make programs easier to read, fix, and reuse.

When you want to repeat the same task many times without writing the same code again.
When you want to break a big problem into smaller, easier steps.
When you want to share code with others or use it in different parts of your program.
When you want to keep your code clean and easy to understand.
When you want to test parts of your program separately.
Syntax
Javascript
function functionName(parameters) {
  // code to run
}

Functions start with the keyword function, followed by a name and parentheses.

Code inside curly braces { } runs when you call the function.

Examples
This function prints 'Hello!' when called.
Javascript
function sayHello() {
  console.log('Hello!');
}
This function adds two numbers and gives back the result.
Javascript
function add(a, b) {
  return a + b;
}
Sample Program

This program uses a function to greet different people by name. It shows how functions help reuse code.

Javascript
function greet(name) {
  console.log('Hello, ' + name + '!');
}

greet('Alice');
greet('Bob');
OutputSuccess
Important Notes

Functions keep your code DRY (Don't Repeat Yourself).

They make it easier to fix bugs because you only change code in one place.

Summary

Functions let you reuse code easily.

They help break big tasks into smaller steps.

Functions make your code cleaner and easier to understand.