COMPUTER SCIENCE CAFÉ
  • WORKBOOKS
  • BLOCKY GAMES
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY
  • WORKBOOKS
  • BLOCKY GAMES
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY
JAVASCRIPT | FUNCTIONS
ON THIS PAGE
SECTION 1 | DECLARING AND CALLING A FUNCTION
SECTION 2 | LOCAL AND GLOBAL VARIABLES
​SECTION 3 | RETURN STATEMENTS
SECTION 4 | SAMPLE PROGRAM
SECTION 5 | CODING CHALLENGE
ALSO IN THIS TOPIC
GETTING STARTED
 ​VARIABLES & USER INPUT
 OPERATORS
CONDITIONALS (IF STATEMENTS)
​ITERATION (LOOPS)
ARRAYS (LISTS)
YOU ARE HERE | FUNCTIONS

FURTHER JAVASCRIPT

Picture
WHAT ARE FUNCTIONS
A function in JavaScript is a reusable block of code designed to perform a specific task. It's like a mini-program within your main program. Functions are defined by the function keyword, followed by a name, and a set of parentheses (). The code to be executed by the function is placed within curly braces { }.

    
In this example, greet is the name of the function, and the code inside the curly braces is the body of the function.
WHY DO WE USE FUNCTION
Functions promote cleaner, more efficient, and more scalable code. They are fundamental building blocks in JavaScript and most other programming language. Functions serve several essential purposes in programming:
  • Modularity: Functions allow you to break down complex tasks into smaller, more manageable pieces. This modular approach makes your code more organized and easier to understand.
  • Reusability: Once a function is defined, it can be called multiple times from different parts of your program. This means you can write a piece of code once and reuse it, rather than repeating the same code in multiple places.
  • Maintainability: If you need to make a change to a specific task your program performs, you only have to update the function that handles that task. This centralized approach makes your code easier to maintain and debug.
  • Abstraction: Functions can hide the complexity of certain operations. When you use a function, you don't always need to know how it works internally. You just need to know what it does (its purpose) and how to use it.
  • Parameterisation: Functions can take inputs, known as parameters, allowing them to process different data and produce different outputs based on those inputs.
SECTION 1 | DECLARING AND CALLING A FUNCTION
A function is declared (created) using the function keyword, followed by a unique function name, a set of parentheses () (which can contain parameters), and a block of code enclosed in curly braces { }.
  • function: This keyword indicates the start of a function declaration.
  • functionName: This is the name you give to the function. It should be descriptive and follow JavaScript naming conventions (camelCase is common).
  • parameters: These are optional inputs the function can accept. Multiple parameters are separated by commas.
For example, a function to add two numbers might look like this
Code Editor

    
In this example, addNumbers is the function name, and num1 and num2 are parameters.

Once a function is declared, it doesn't run automatically. To execute the code inside a function, you need to call or invoke it. This is done by using the function name followed by parentheses ().

    
When calling the function addNumbers in the code above we used the following:
  • functionName: This is the name of the function you want to call.
  • arguments: These are the values you pass into the function's parameters, in this example 5 and 3. Like parameters, multiple arguments are separated by commas.
​
REMEMBER | When you are passing arguments to a function, the function needs to be set up to receive them as parameters. Similarly, if a function is declared with parameters, you must provide the corresponding arguments when calling that function.
SECTION 2 | LOCAL AND GLOBAL VARIABLES
A local variable is a variable that is declared within a function. It is local to that function, meaning it can only be accessed and modified inside that function. Once the function completes its execution, the local variable is destroyed, and its memory is freed up. This ensures that local variables do not interfere with other parts of the code and provides a level of encapsulation.
CORRECT STRUCTURE USED

    
A global variable is a variable that is declared outside of any function. It is accessible from any part of the code, including within functions. While global variables offer convenience because they can be accessed anywhere, they should be used judiciously. Over-reliance on global variables can lead to code that is hard to maintain and debug, as any function can potentially change the value of a global variable.
WRONG STRUCTURE USED

    
Interplay between Local and Global Variables:
  • Variable Shadowing: If a local variable has the same name as a global variable, the local variable will "shadow" or "override" the global variable within that function. This means that any reference to that variable name inside the function will refer to the local variable, not the global one.
  • Modifying Global Variables: Functions can modify global variables if they reference them directly. This can lead to unintended side effects, especially if multiple functions modify the same global variable.

Best Practices
  • Limit the use of global variables. Instead, prefer passing values to functions as parameters and returning results.
  • If you must use global variables, give them descriptive names to indicate their global nature and avoid accidental re-declarations.
  • Always declare variables with let, const, or var to specify their scope. Not doing so will implicitly create a global variable, even if it's inside a function.
SECTION 4 | RETURN STATEMENTS
The return keyword is used in a function to specify the value that the function should produce and give back to the part of the program where the function was called. Once a return statement is executed, the function's execution stops, and control is returned to the calling location with the specified value.

To return a value from a function, you use the return keyword followed by the value or expression you want to return. You need to remember when you return a value from a function you also need to receive the return elsewhere in your code.

The code below shows the function being called and on the same line as the function is called the variable 'result' receives the return when the calculation is returned from the function.

    
The return statement is a powerful tool in functions, allowing them to produce values that can be used in various ways throughout your code. By understanding and effectively using the return keyword, you can make your functions more versatile and your code more expressive.
SECTION 4 | SAMPLE PROGRAM
This program exemplifies a simple yet practical application of a text-based calculator built using JavaScript. And can be broken down into 4 clear steps:
  • The calculator prompts the user to choose an arithmetic operation (addition, subtraction, multiplication, or division)
  • Then allows the user to input the numbers they wish to operate on.
  • Preforms the calculation needed
  • Outputs the result to the user
By breaking the program down it is easy to manage each stage in 4 simple functions. It uses function chaining, where each function, after executing its designated task, calls the next function in the sequence, passing along the necessary data.

This approach shows efficient data flow between functions and  demonstrates the concept of function encapsulation, where each function is responsible for a specific task, making the code modular and easy to follow. 
    TEXT BASED CALCULATOR
    
        
    Picture
    SIMPLE EXPENSE TRACKER
    OBJECTIVES
    Create a program that allows a user to track their expenses. The user should be able to add an expense, view all expenses, and calculate the total amount spent. Use functions for each menu option.

    TASKS
    1: Add an Expense
    • Prompt the user for the name of the expense (e.g., "Groceries", "Rent", "Utilities").
    • Prompt the user for the amount of the expense.
    • Store the expense name and its amount.
    2: View All Expenses
    • Display a list of all added expenses along with their amounts.
    3: Calculate the Total
    • Calculate and display the total amount spent based on all the expenses added.
    4: User Menu - Provide a menu for the user where they can choose to:
    • Add an expense.
    • View all expenses.
    • Calculate the total amount spent.
    • Exit the program.

    Hints
    • Use an array to store the expenses.
    • Each expense can be an object with properties for the name and amount.
    • Use functions to encapsulate the logic for each menu option.

    SAMPLE OUTPUT
    Welcome to the Expense Tracker!

    Menu:
    1. Add an Expense
    2. View All Expenses
    3. Calculate Total Amount Spent
    4. Exit

    Choose an option: 1

    Enter the name of the expense: Groceries
    Enter the amount: 50

    Expense added successfully!

    Menu:
    1. Add an Expense
    2. View All Expenses
    3. Calculate Total Amount Spent
    4. Exit

    Choose an option: 2

    Expenses:
    - Groceries: $50

    Menu:
    ... (and so on)
    Picture
    NAVIGATION
    GETTING STARTED
     ​VARIABLES & USER INPUT
     OPERATORS
    CONDITIONALS (IF STATEMENTS)
    ​ITERATION (LOOPS)
    ARRAYS (LISTS)
     FUNCTIONS

    FURTHER JAVASCRIPT
    Picture
    SUGGESTIONS
    We would love to hear from you
    SUBSCRIBE 
    To enjoy more benefits
    We hope you find this site useful. If you notice any errors or would like to contribute material then please contact us.