Lesson 18 of 30 – JavaScript Functions
53%

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.
Why Use Functions?

Functions help programmers:

  • Reuse code.
  • Reduce repetition.
  • Organize programs.
  • Make debugging easier.
  • Improve readability.
Defining a Function

A function is created using the function keyword.

Syntax:
function functionName(){
code here;
}
Example:
function greet(){
alert("Hello World!");
}
Calling a Function

A function runs only when it is called.

Example:
function greet(){
alert("Welcome");
}

greet();

Output:

Welcome

Function Parameters

Parameters allow data to be passed into a function.

Example:
function greet(name){
alert("Hello "+name);
}

greet("Rahul");

Output:

Hello Rahul

Multiple Parameters

A function can accept multiple parameters.

Example:
function add(a,b){
alert(a+b);
}

add(10,20);

Output:

30

Arguments in Functions

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");
Nested Functions

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

Function Scope

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
Advantages of Functions
  • Reduce code repetition.
  • Improve readability.
  • Easy to debug.
  • Easy to maintain.
  • Reusable code.
  • Organized programming.
  • Reduce program size.
Real-Life Example

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

Key Points
  • 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.
Quick Revision
Concept Description
Function Reusable block of code
Parameter Input value
Return Sends value back
Arrow Function Short function syntax
Anonymous Function Function without name
Best Practices
  • 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

Which keyword is used to define a function in JavaScript?