Computer Science  ·  Level 6
Web Designing
Chapter 7: JavaScript functions
📚 4 Topics
⚑ What you will be able to do

By the end of this chapter, you will be able to:

  • Apply the correct structure of a JavaScript function in your code confidently.
  • Create JavaScript functions following best practices for clean and efficient coding.
  • Invoke JavaScript functions correctly within your programs to make them work smoothly.
  • Return values properly from functions to use data effectively in your applications.

Mastering these skills helps you build interactive and dynamic websites, making your work stand out in the web design trade!

7.1 JavaScript Function Structure

JavaScript functions encapsulate blocks of code designed to perform specific tasks, making them fundamental in programming for the web. Kenyan developers working on projects for institutions like Equity Bank or Jomo Kenyatta University of Agriculture and Technology rely on functions to modularize code, reduce redundancy, and improve maintainability. A clear grasp of function structure is vital for debugging, optimizing, and extending web applications effectively.

7.1.1 Components of a JavaScript Function

A JavaScript function consists of several key components that define its behavior and interaction within the program. These components work together to ensure the function executes correctly and returns expected outcomes.

Function Declaration

A function declaration introduces a named function into the program, allowing it to be called elsewhere in the code. The declaration starts with the keyword function, followed by the function's name, parentheses for optional parameters, and a block of code enclosed in curly braces. For example, a function named calculateInterest can compute interest for a banking application. Declared functions are hoisted, meaning they can be invoked before their actual declaration in the code, which aids in organizing code logically.

Function Name

The function name serves as an identifier, used to invoke the function when required. Naming conventions in JavaScript encourage descriptive, camelCase names that reflect the function’s purpose, such as validateUserInput or fetchCustomerData. Clear naming improves code readability, especially in collaborative environments like software teams at Nairobi County government IT departments.

Parameters and Arguments

Parameters are placeholders listed within the parentheses of a function declaration, representing inputs the function expects. Arguments are the actual values passed to the function when it is called. For instance, in a function calculateTax(income, rate), income and rate are parameters, while calling calculateTax(50000, 0.15) passes arguments. Proper use of parameters allows functions to handle dynamic data, essential for applications processing varied user inputs such as online shopping carts in retail businesses.

Function Body

The function body, enclosed within curly braces {}, contains the executable statements that define what the function does. This block can include variable declarations, control structures like loops and conditionals, and other function calls. The body performs the logic required to achieve the function’s goal, such as calculating a total price including tax or validating form inputs on a university admission portal.

Return Statement

Functions can return values to the caller using the return statement, which exits the function and outputs a result. For example, a function computing the sum of two numbers will return the result to be used elsewhere in the program. In Kenyan e-government portals, return statements are crucial for passing processed data back to the user interface or server for further action.

7.1.2 Syntax Variations of JavaScript Functions

JavaScript supports multiple syntactical forms for defining functions, each suited to different programming styles and use cases. Kenyan developers benefit from choosing the appropriate syntax in projects ranging from mobile banking apps to online learning management systems.

Function Declarations

The traditional way to define a function uses the function keyword, a name, parameters, and a body. This form is straightforward and widely supported across all environments. Its hoisting property allows flexible code organization, useful in large-scale applications developed by teams in organizations like the Kenya Revenue Authority.

Function Expressions

A function expression assigns a function to a variable, enabling anonymous functions and more dynamic programming patterns. For example, const greet = function(name) { return "Hello " + name; } defines a function without a name that can be passed as a value. This approach is common in event handling within interactive web pages for hotels’ booking systems.

Arrow Functions

Introduced in ES6, arrow functions provide a concise syntax for writing functions, especially useful for inline functions and callbacks. Arrow functions omit the function keyword and use => to separate parameters and body, e.g., const add = (a, b) => a + b;. They do not have their own this binding, which affects context handling in frameworks like React used by Kenyan fintech startups.

Named Function Expressions

Combining the characteristics of function expressions and named functions, named function expressions provide a function name for debugging while being assigned to a variable. This aids in stack traces during error handling, a practice adopted by software developers at Nairobi hospitals developing patient management systems.

7.1.3 Function Parameters: Defaults and Rest Parameters

Handling function inputs flexibly is critical for robust JavaScript functions, especially when dealing with optional or variable numbers of arguments in Kenyan software applications.

Default Parameters

JavaScript allows setting default values for parameters that are not provided by the caller. For example, function calculateDiscount(price, rate = 0.1) assigns a default discount rate of 10% if none is specified. This feature simplifies code by avoiding explicit checks for undefined parameters in county government revenue systems calculating service fees.

Rest Parameters

Rest parameters enable functions to accept an indefinite number of arguments as an array, denoted by three dots .... For instance, function sum(...numbers) can sum any number of inputs. This flexibility is vital in e-commerce platforms where the number of items in a cart varies dynamically.

Parameter Destructuring

Destructuring parameters allow unpacking values from arrays or objects directly within the function signature. For example, function displayUser({name, age}) extracts name and age properties from a user object. This technique leads to cleaner code in applications like educational portals managing student profiles.

7.1.4 Scope and Hoisting Within Functions

Understanding scope and hoisting is fundamental in avoiding bugs and writing predictable JavaScript functions in professional projects across Kenyan industries.

Local and Global Scope

Variables declared inside a function have local scope, accessible only within that function, while variables declared outside any function have global scope. This separation prevents unintended side effects and variable collisions in complex systems such as banking transaction processing software.

Hoisting of Function Declarations and Variables

Function declarations and variable declarations are hoisted to the top of their containing scope during compilation, meaning they can be referenced before their actual code line. However, only the declarations are hoisted, not the initializations, which can lead to undefined values if misunderstood. Kenyan developers working on county web portals must grasp hoisting to avoid runtime errors.

Block Scope with let and const

The introduction of let and const keywords provides block-level scope, limiting variable accessibility to the block they are declared in, such as within if statements or loops. This feature helps maintain cleaner and safer code, for example, in hospital management systems handling sensitive patient data.

Function Scope and Closures

Functions create their own scope, and inner functions can access variables from outer functions, forming closures. Closures enable powerful programming patterns like data encapsulation and state management, used in interactive dashboards for retail business analytics.

Practice Questions

  1. Describe the main components of a JavaScript function and explain how each contributes to the function's operation. (10 marks)
  2. Compare and contrast function declarations and function expressions in JavaScript, including their hoisting behavior. (10 marks)
  3. Explain the use of default parameters and rest parameters in JavaScript functions, providing examples relevant to Kenyan web applications. (10 marks)
  4. Discuss the concepts of scope and hoisting within JavaScript functions and how they can affect variable accessibility in a program. (10 marks)
The rest of this chapter
🔒

Create a free account to open more of this chapter.

Free: practical guides, quick cards, workplace scenarios and more.

Create a free account
🔒7.2 Creation of JavaScript function

The creation of functions in JavaScript is fundamental for structuring reusable, modular code that enhances maintainability and clarity in web applications. In Kenya's dynamic tech industry, especially among software developers working in startups or establish…

🔒7.3 Invoking of JavaScript Function

In Kenya's expanding technology landscape, particularly within software development firms and IT departments of financial institutions like KCB and Equity Bank, understanding how to invoke JavaScript functions correctly is vital. Functions form the backbone of…

🔒7.4 Returning values from functions

In JavaScript programming within Kenyan software development environments, understanding how functions return values is crucial for building dynamic and interactive web applications. Functions that return values enable developers to perform calculations, proce…

Chapter Summary

This chapter explored the essential structure of JavaScript functions, explaining how they consist of a function keyword, a name, parentheses for parameters, and a body enclosed in braces. It detailed the process of creating JavaScript functions, emphasizing the importance of clear naming and parameter definition to ensure reusability and clarity in code. The chapter then described how functions are invoked or called within a program, highlighting the role of arguments in passing data to functions during execution. Finally, it covered how functions return values back to the part of the program that called them, enabling dynamic and flexible code behavior. Understanding these concepts equips learners with the foundational skills to write modular and efficient JavaScript code. The chapter’s progression from structure to creation, invocation, and return values provides a comprehensive overview of function usage in web design programming.

Self-Assessment

🔒 PDFDownload this self-assessment, with answers

A. Written Assessment

  1. What are the main components of a JavaScript function structure? (3 marks)
  2. Identify the correct syntax for creating a function named calculateTax that takes no parameters. (MCQ)
    a) function calculateTax() { }
    b) function: calculateTax() { }
    c) var calculateTax() { }
    d) create function calculateTax() { } (2 marks)
🔒20 more in this section.

Chapter Examination Questions

🔒 PDFDownload these examination questions, with worked answers

SECTION A (40 Marks) - Answer ALL Questions

  1. Explain the basic structure of a JavaScript function and illustrate with an example relevant to a web application used by a Kenyan bank. (4 marks)
  2. Differentiate between function declaration and function expression in JavaScript. (4 marks)
🔒18 more in this section.

Chapter Practical Activities

Practical 1: Define a Basic JavaScript Function to Calculate Square of a Number

Computer Science · Level 6
Web Designing
PRACTICAL ASSESSMENT
TIME: 4 HOURS
⬇ PDFCandidate Instructions (Candidate Tool)

Type: Individual

INSTRUCTIONS TO CANDIDATE:
1.  You are required to perform the following task:
i.  Create an HTML file containing a JavaScript function named 'calculateSquare' that takes one number parameter and returns its square, with correct syntax and structure.
2.  You have been provided with the following resources for the practical task:
Tools & EquipmentMaterials
Functional computer installed with text editor (e.g., VS Code or Notepad++)
Plain paper
Pen
⬇ PDFResources Required (Cutting List)
S/NItemQuantity
1Functional computer installed with text editor (e.g., VS Code or Notepad++)1 Pc per Candidate
2Plain paper1 Pc per Candidate
3Pen1 Pc per Candidate
⬇ PDFAssessor Guide
Items to be EvaluatedMarks AvailableMarks ObtainedComments
TASK 1: Define the JavaScript function
Launched the text editor IDE
(Award 1 mark for launching the appropriate text editor or IDE)
1
Created a new HTML file with proper structure (<!DOCTYPE html>, <html>, <head>, <body>)
(Award 1 mark for correct HTML tags and 1 mark for proper nesting)
2
Declared the JavaScript function named 'calculateSquare'
(Award 1 mark for correct function keyword, 1 mark for correct function name, 1 mark for parentheses)
3
Included one parameter in the function definition
(Award 2 marks if exactly one parameter is declared)
2
Function body correctly returns the square of the parameter (e.g., return num * num;)
(Award 4 marks for correct return statement and calculation)
4
Closed the function with proper syntax (closing curly brace)
(Award 1 mark for correct function closure)
1
Included comments briefly describing the function
(Award 2 marks for meaningful comments inside or above the function)
2
Sub-Total15
TASK 2: Test and display function output
Invoked the function with a numeric argument (e.g., calculateSquare(5))
(Award 2 marks if function is invoked correctly)
2
Displayed the returned value on the web page using document.write or console.log
(Award 3 marks for correct output display)
3
Tested the function with at least two different numeric inputs
(Award 2 marks for testing with multiple inputs)
2
Sub-Total7
PRODUCT CHECKLIST
Function is syntactically correct and executes without errors
(Award 5 marks if function runs correctly and returns expected results)
5
Output correctly shows the square of input numbers as per test cases
(Award 3 marks for accurate output matching input squared)
3
Sub-Total8
GRAND TOTAL30
ASSESSMENT OUTCOME:   ☐ Competent    ☐ Not Yet Competent (competent if at least 50%)

Practical 2: Invoke a JavaScript Function Without Parameters

Computer Science · Level 6
Web Designing
PRACTICAL ASSESSMENT
TIME: 3 HOURS
⬇ PDFCandidate Instructions (Candidate Tool)

Type: Individual

INSTRUCTIONS TO CANDIDATE:
1.  You are required to perform the following task:
i.  Create an HTML file 600mm x 400mm viewport size displaying a button that invokes a previously defined JavaScript function without parameters when clicked.
2.  You have been provided with the following resources for the practical task:
Tools & EquipmentMaterials
Functional computer with internet accessPlain paper
Text editor software (e.g. Visual Studio Code, Sublime Text)
Web browser (e.g. Google Chrome, Mozilla Firefox)
⬇ PDFResources Required (Cutting List)
S/NItemQuantity
1Functional computer with internet access1 Pc per Candidate
2Text editor software (e.g. Visual Studio Code, Sublime Text)1 Pc per Candidate
3Web browser (e.g. Google Chrome, Mozilla Firefox)1 Pc per Candidate
4Plain paper1 Sheet per Candidate
⬇ PDFAssessor Guide
Items to be EvaluatedMarks AvailableMarks ObtainedComments
TASK 1: Setup and Function Invocation
Launched the text editor and created a new HTML file
(Award 2 marks for file creation and setup)
2
Defined a JavaScript function without parameters
(Award 5 marks for correct syntax and function definition)
5
Added an HTML button element to the page
(Award 3 marks for correct button element with appropriate attributes)
3
Implemented the button onclick event to invoke the JavaScript function
(Award 6 marks for correct function invocation without parameters)
6
Displayed a message or action confirming the function was called
(Award 4 marks for visible confirmation such as alert or DOM update)
4
Sub-Total20
PRODUCT CHECKLIST
HTML file runs correctly in browser with a button that calls the JavaScript function without parameters and displays confirmation
(Award 10 marks for correct working functionality and user feedback)
10
Sub-Total10
GRAND TOTAL30
ASSESSMENT OUTCOME:   ☐ Competent    ☐ Not Yet Competent (competent if at least 50%)
🔒

Free: practical guides, quick cards, workplace scenarios and more.

Create a free account
🔒Create and Invoke a JavaScript Function with ParametersPractical 3
🔒Develop a JavaScript Function to Return Computed ValuesPractical 4
🔒Develop a JavaScript Function to Calculate the Total Price with TaxPractical 5
🔒Invoke Multiple JavaScript Functions Sequentially in a Web PagePractical 6
🔒Create Nested JavaScript Functions to Calculate Total and Average MarksPractical 7
🔒Create JavaScript functions returning different data typesPractical 8
🔒Demonstrate JavaScript Function Hoisting with Pre-Declaration InvocationPractical 9
🔒Create and invoke an anonymous JavaScript functionPractical 10
Flashcards 20 cards Study deck ▾
Question
1

↻ Tap card to reveal answer
🔒

18 more in this section.

Create a free account
Test Yourself 19 questions Start quiz ▾
0%
0 / 2
🔒

17 more in this section.

Create a free account
Am I competent?

At the start of this chapter we promised you would be able to:

  • Apply the correct structure of a JavaScript function in your code confidently.
  • Create JavaScript functions following best practices for clean and efficient coding.
  • Invoke JavaScript functions correctly within your programs to make them work smoothly.
  • Return values properly from functions to use data effectively in your applications.

Tick each one you can genuinely do.

So, are you there yet?

You're competent when you can confidently do 50% or more of what this chapter promised.

Sign in to record how you're doing.