JavaScriptFunctions & Scope
JavaScript Functions
Learn JavaScript functions, how to define and call them, use parameters and return values, and understand why functions are essential for clean and reusable code.
What are Functions in JavaScript?Link to this section
Functions are reusable blocks of code designed to perform a specific task. Instead of writing the same logic repeatedly, functions allow you to write it once and reuse it wherever needed.
Functions make code:
- Cleaner
- More readable
- Easier to maintain
- Easier to debug
Why Functions are Important?Link to this section
In real-world applications, programs can have thousands of lines of code. Functions help break large programs into smaller, manageable pieces.
They are heavily used in:
- Web applications
- APIs
- Frameworks like React and Node.js
- EaEnterprise-level systems
Function DeclarationLink to this section
A function declaration defines a function using the function keyword.
Explanation:
The function is defined but not executed until it is called.
Calling a FunctionLink to this section
To execute a function, you must call it using its name followed by parentheses.
Function ParametersLink to this section
Parameters are values passed to a function to make it dynamic and flexible.
Calling the function:
Return StatementLink to this section
The return statement sends a value back to the caller and stops function execution.
Using the returned value:
note
A function can return only one value, but that value can be an object or array.
Function ExpressionLink to this section
Functions can also be stored in variables. This is called a function expression.
tip
Function expressions are commonly used in modern JavaScript and frameworks.
Arrow FunctionsLink to this section
Arrow functions provide a shorter syntax for writing functions and were introduced in ES6.
note
Arrow functions handle this differently, which is important in advanced JavaScript topics.
Functions as Reusable LogicLink to this section
Functions allow developers to follow the DRY principle (Don’t Repeat Yourself).
Instead of repeating logic, functions help centralize behavior, making applications scalable and professional.
Check Your Understanding
Question 1 of 5What is the main purpose of a function?
Simple Function
Write a function that prints your name....
Parameter Practice
Create a function that accepts two numbers and prints their sum....
Return Value
Write a function that returns the square of a number....
Arrow Function
Convert a normal function into an arrow function....
Real-World Scenario
Create a function that calculates the final price after applying a discount....
