Page 140 - CITS - Computer Software Application -TT
P. 140
COMPUTER SOFTWARE APPLICATION - CITS
function myFunction() {
let carName = “Volvo”;
// code here CAN use carName
}
// code here can NOT use carName
Since local variables are only recognized inside their functions, variables with the same name can be used in
different functions.
Local variables are created when a function starts, and deleted when the function is completed.
Test Yourself With Exercises
Exercise:
Execute the function named myFunction.
function myFunction() {
alert(“Hello World!”);
}
JavaScript function is a set of statements that take inputs, do some specific computation, and produce output.
A JavaScript function is executed when “something” invokes it (calls it).
Example 1: A basic javascript function, here we create a function that divides the 1st element by the second
element.
• Javascript
function myFunction(g1, g2) {
return g1 / g2;
}
const value = myFunction(8, 2); // Calling the function
console.log(value);
Output:
0 seconds of 17 secondsVolume 0%
4
You must already have seen some commonly used functions in JavaScript like alert(), which is a built-in function in
JavaScript. But JavaScript allows us to create user-defined functions also. We can create functions in JavaScript
using the keyword `function`.
Syntax:
The basic syntax to create a function in JavaScript is shown below.
functionName(Parameter1, Parameter2, ...)
{
// Function body
}
To create a function in JavaScript, we have to first use the keyword function, separated by the name of the function
and parameters within parenthesis. The part of the function inside the curly braces {} is the body of the function.
In javascript, functions can be used in the same way as variables for assignments, or calculations.
Function Invocation:
• Triggered by an event (e.g., a button click by a user).
127
CITS : IT&ITES - Computer Software Application - Lesson 37 - 46