Computer ScienceChapter 3: Programming Fundamentals
3.4.8 Functions
Function:
Explanation level
This topic explains what functions are in JavaScript, how to define and call them, how to pass arguments, and how to return values.
Definition
Function: A function is a set of lines which occurs in the code quite often that can be segmented once, and called again and again. This way, rewriting the same set of code for similar results can be eliminated.
Core Concept
A function is like a recipe in a cookbook. Instead of writing out all the steps for making a cake every time you want one, you just write the recipe once and then refer to it by name whenever you need it. In programming, a function is a block of code that you write once and can use (call) many times. This saves you from repeating the same code, makes your program shorter, and helps organize your code into meaningful, reusable pieces. Functions can take inputs (arguments) and can give back a result (return value).
Detailed Explanation
Why Use Functions?
Through functions, different sets of code can be separated resulting in fewer lines of code, assigning them meaningful names based on their functionality. This leads to efficiently managing a large computer program.
- Avoid repeating the same code.
- Give meaningful names to blocks of code.
- Make large programs easier to manage.
- Programming languages provide built-in functions like `prompt()`, `alert()`, etc.
- When a function is called, the caller does not necessarily need to know the code behind that function to use it.
Defining and Calling a Function
A function has a name through which it is identified and called. Additionally, a function can have arguments which are variables local to that function and their lifespan is limited to the said function. Variables outside functions are global variables and can be accessed anywhere from the program.
Syntax: ```javascript function functionName(argument1, argument2) { // code to execute } ```
Example: Function with No Arguments
Recall the earlier program where we defined a function, namely `msgSure()`, and whenever the button is pressed, an alert pops up asking "Are you sure?". In line 4 of the said code, we used the 'function' reserved word to define and name it. However, on line 11, we called the same function just with its name.
```html <html> <head> <script type="text/javascript"> function msgSure() { alert("Are You Sure???") } </script> </head> <body> Do You Mind, CLICKING on the Button - <input type="button" onclick="msgSure()" value="Be Sure"> </body> </html> ```
Output: When the "Be Sure" button is clicked, an alert box appears saying "Are You Sure???".
- `function msgSure() { ... }` defines a function named `msgSure`.
- The function takes no arguments.
- `onclick="msgSure()"` calls the function when the button is clicked.
Function with Arguments
A function can accept arguments (inputs) that it uses inside its body.
Example: ```html <html> <head> <script type="text/javascript"> function msgSure(currency, amount) { alert("Are You Sure, you gave me "+currency+". "+amount+"?") } </script> </head> <body> Do You Mind, CLICKING on the Button - <input type="button" onclick="msgSure('Rupees', 5000)" value="Be Sure"> </body> </html> ```
Output: When the button is clicked, an alert appears: "Are You Sure, you gave me Rupees. 5000?"
- `function msgSure(currency, amount)` defines a function with two arguments: `currency` and `amount`.
- When called with `msgSure('Rupees', 5000)`, `currency` becomes `'Rupees'` and `amount` becomes `5000`.
- The function uses these values in the alert message.
Function Returning a Value
A function can return a value using the `return` keyword. This allows the function to compute something and send the result back to where it was called.
Example: ```html <html> <body> <script type="text/javascript"> function calcBill(bill, amount_rcyd) { document.write("Your Balance is: "); return(amount_rcyd - bill); } var balance = calcBill(2345, 5000); document.write(balance); </script> </body> </html> ```
Output: Your Balance is: 2655
- `function calcBill(bill, amount_rcyd)` defines a function with two arguments.
- Inside, it prints "Your Balance is: " and then returns `amount_rcyd - bill`.
- `var balance = calcBill(2345, 5000);` calls the function, which returns 2655, and assigns it to `balance`.
- `document.write(balance);` displays 2655.
Key Point: An important point to note is that line 5 prints inside the function, and line 10 displays the result outside the scope of the function. A similar approach can be used for testing the values of a function, when frequently occurring sets of code are selected to form a new function.
Local vs Global Variables
| Type | Scope | Description |
|---|---|---|
| Local Variable | Inside function | Declared inside a function; only accessible within that function |
| Global Variable | Outside function | Declared outside any function; accessible anywhere in the program |
Example: ```javascript var globalVar = "I am global"; // Global variable
function myFunction() { var localVar = "I am local"; // Local variable document.write(globalVar); // Accessible document.write(localVar); // Accessible }
myFunction(); // document.write(localVar); // Error: localVar is not defined outside ```
Built-in Functions
Programming languages provide built-in functions that you can use without defining them.
| Function | Purpose |
|---|---|
| `alert()` | Displays an alert box |
| `prompt()` | Takes user input |
| `document.write()` | Writes to the webpage |
| `parseInt()` | Converts a string to an integer |
| `parseFloat()` | Converts a string to a floating-point number |
Benefits of Functions
- Reusability: Write once, use many times.
- Organization: Break complex programs into smaller, manageable pieces.
- Readability: Meaningful names make code easier to understand.
- Maintenance: Fix or update code in one place.
- Abstraction: Callers don't need to know how the function works internally.
Intermediate Level
A function is a reusable block of code that performs a specific task. It is defined with the `function` keyword and a name, and can accept arguments (inputs) and return a value. Functions help avoid code repetition, organize programs, and improve readability. Arguments are local to the function; variables outside are global. Built-in functions like `alert()`, `prompt()`, and `document.write()` are provided by JavaScript. Functions can be called multiple times, and the caller doesn't need to know the internal implementation—just the name, arguments, and return value.
Important Points
- - Function = reusable block of code.
- - Defined with `function` keyword.
- - Can take arguments (inputs).
- - Can return a value with `return`.
- - Local variables: inside function; global variables: outside.
- - Built-in functions: `alert()`, `prompt()`, `document.write()`.
- - Benefits: reusability, organization, readability, maintenance.
- - Example: `function calcBill(bill, amount_rcyd) { return(amount_rcyd - bill); }`.
Remember
- - Function: `function name() { ... }`.
- - Call: `name();`.
- - Arguments: `function name(arg1, arg2) { ... }`.
- - Return: `return value;`.
- - Local: Inside function.
- - Global: Outside function.
- - Built-in: `alert()`, `prompt()`, `document.write()`.
- - Example: `calcBill(2345, 5000)` returns `2655`.
Common Mistakes
- - Forgetting to call the function: Defining it is not enough; you must call it.
- - Missing parentheses in call: `msgSure` vs `msgSure()`.
- - Forgetting `return`: Without it, the function returns `undefined`.
- - Using a local variable outside its scope: Causes an error.
- - Confusing arguments and parameters: Parameters are in the definition; arguments are in the call.
- - Overwriting global variables: Be careful with variable names inside functions.
Quick Revision
A function is a reusable block of code that performs a specific task. It is defined with the `function` keyword and a name, and can accept arguments and return a value. Functions help avoid repetition, organize code, and improve readability. Local variables are inside the function; global variables are outside. Built-in functions like `alert()`, `prompt()`, and `document.write()` are provided by JavaScript.
60-Second Revision
- Function: Reusable block of code.
- Define: `function name() { ... }`.
- Call: `name();`.
- Arguments: Inputs.
- Return: Output.
- Local: Inside function.
- Global: Outside function.
- Built-in: `alert()`, `prompt()`, `document.write()`.
- Key Point: Functions make code reusable, organized, and easier to maintain.
Did you understand this topic?
Your answer is saved with your learning record. It does not mark the topic as mastered.
Quick revision
Revision Zone
Review the key facts, formulas and checks before you move on.3.4.8 Functions
Sticky Notes · Quick Revision
Key Point 1
- Function: `function name() { ... }`.
Key Point 2
- Call: `name();`.
Key Point 3
- Arguments: Inputs to the function.
Key Point 4
- Return: Output from the function.
Key Point 5
- Local: Inside function.
Key Point 6
- Global: Outside function.
Key Point 7
- Built-in: `alert()`, `prompt()`, `document.write()`.
Key Point 8
- Example: `calcBill(2345, 5000)` returns `2655`.
Same supplied content as this Notes page (shared canonical source).