Page 142 - CITS - Computer Software Application -TT
P. 142
COMPUTER SOFTWARE APPLICATION - CITS
const x = square(4); // x gets the value 16
console.log(x);
Output
16
Functions as Variable Values:
Functions can be used the same way as you use variables.
Example:
// Function to convert Fahrenheit to Celsius
function to Celsius (fahrenheit) {
return (fahrenheit - 32) * 5/9;
}
// Using the function to convert temperature
let temperatureInFahrenheit = 77;
let temperatureInCelsius = toCelsius(temperatureInFahrenheit);
let text = “The temperature is “ + temperatureInCelsius + “ Celsius”;
Arrow Function:
It is one of the most used and efficient methods to create a function in JavaScript because of its comparatively
easy implementation. It is a simplified as well as a more compact version of a regular or normal function expression
or syntax.
Syntax:
let function_name = (argument1, argument2 ,..) => expression
Example 4: This example describes the usage of the Arrow function.
• Javascript
const a = [“Hydrogen”, “Helium”, “Lithium”, “Beryllium”];
const a2 = a.map(function (s) {
return s.length;
});
console.log(“Normal way “, a2); // [8, 6, 7, 9]
const a3 = a.map((s) => s.length);
console.log(“Using Arrow Function “, a3); // [8, 6, 7, 9]
Output
Normal way [ 8, 6, 7, 9 ]
Using Arrow Function [ 8, 6, 7, 9 ]
Function Parameters:
Till now, we have heard a lot about function parameters but haven’t discussed them in detail. Parameters
are additional information passed to a function. For example, in the above example, the task of the function
calcAddition is to calculate the addition of two numbers. These two numbers on which we want to perform the
addition operation are passed to this function as parameters. The parameters are passed to the function within
parentheses after the function name and separated by commas. A function in JavaScript can have any number of
parameters and also at the same time, a function in JavaScript can not have a single parameter.
Example 4: In this example, we pass the argument to the function.
• Javascript
129
CITS : IT&ITES - Computer Software Application - Lesson 37 - 46