JavaScript Function Introduction
Understanding the building blocks of JavaScript programming
🚀 What are JavaScript Functions?
Functions are reusable blocks of code that perform specific tasks. They are the fundamental building blocks of JavaScript programming, allowing you to organize and reuse code efficiently.
// This is a simple JavaScript function
function sayHello() {
return "Hello, World!";
}
// Call the function
console.log(sayHello());
Output:
Hello, World!
Key Function Concepts
Reusability
Write once, use many times
function greet(name) {
return "Hello, " + name;
}
Parameters
Accept input values
function add(a, b) {
return a + b;
}
Return Values
Send results back
function multiply(x, y) {
return x * y;
}
Organization
Keep code clean and organized
function calculateArea(radius) {
return Math.PI * radius * radius;
}
🔹 Basic Function Syntax
Here's the basic structure of a JavaScript function:
// Function declaration
function functionName() {
// Code to execute
return "result"; // Optional return statement
}
// Function call
functionName();
Example:
function welcomeMessage() {
return "Welcome to JavaScript Functions!";
}
console.log(welcomeMessage());
Welcome to JavaScript Functions!
🔹 Functions with Parameters
Functions can accept input values called parameters:
// Function with one parameter
function greetUser(name) {
return "Hello, " + name + "!";
}
// Function with multiple parameters
function calculateSum(num1, num2) {
return num1 + num2;
}
// Calling functions with arguments
console.log(greetUser("Alice"));
console.log(calculateSum(5, 3));
Output:
Hello, Alice!
8
🔹 Function Examples
Here are some practical function examples:
// Calculate rectangle area
function calculateRectangleArea(width, height) {
return width * height;
}
// Check if number is even
function isEven(number) {
return number % 2 === 0;
}
// Convert temperature
function celsiusToFahrenheit(celsius) {
return (celsius * 9/5) + 32;
}
// Usage examples
console.log(calculateRectangleArea(5, 3)); // 15
console.log(isEven(4)); // true
console.log(celsiusToFahrenheit(25)); // 77
Output:
15
true
77