JavaScript Functions
Functions are one of the most important features of JavaScript. A function is a reusable block of code that performs a specific task.
Note:
Functions make programs easier to write, understand, reuse, and maintain.
Functions help programmers:
- Reuse code.
- Reduce repetition.
- Organize programs.
- Make debugging easier.
- Improve readability.
A function is created using the function keyword.
Syntax:
function functionName(){
code here;
}
Example:
function greet(){
alert("Hello World!");
}
A function runs only when it is called.
Example:
function greet(){
alert("Welcome");
}
greet();
Output:
Welcome
Parameters allow data to be passed into a function.
Example:
function greet(name){
alert("Hello "+name);
}
greet("Rahul");
Output:
Hello Rahul
A function can accept multiple parameters.
Example:
function add(a,b){
alert(a+b);
}
add(10,20);
Output:
30
You can pass fewer or more arguments.
- Extra arguments are ignored.
- Missing arguments become undefined.
Example:
function greet(first,last){
alert(first+" "+last);
}
greet("Amit");
greet("Amit","Kumar");
A function can contain another function. The inner function can access variables of the outer function.
Example:
function greet(name){
function sayHello(){
return "Hello "+name;
}
return sayHello();
}
document.write(greet("Rohan"));
Output: Hello Rohan
Variables declared inside a function can only be accessed inside that function.
Example:
function demo(){
var x=100;
document.write(x);
}
demo();
// document.write(x); // Error
- Reduce code repetition.
- Improve readability.
- Easy to debug.
- Easy to maintain.
- Reusable code.
- Organized programming.
- Reduce program size.
A function can calculate the total marks of a student.
function totalMarks(a,b,c){
return a+b+c;
}
document.write(totalMarks(70,80,90));
Output: 240
- Functions are reusable blocks of code.
- Functions are declared using the function keyword.
- A function may have parameters.
- A function may return a value.
- Functions can call other functions.
- Anonymous and arrow functions are widely used.
- Nested functions are allowed.
- Functions improve code quality.
| Concept |
Description |
| Function |
Reusable block of code |
| Parameter |
Input value |
| Return |
Sends value back |
| Arrow Function |
Short function syntax |
| Anonymous Function |
Function without name |
- Keep functions small.
- Use meaningful function names.
- Avoid duplicate code.
- Return values whenever needed.
- Use arrow functions for short operations.
- Comment complex functions.
🧠 Quick Quiz