JS Functions

HTML
CSS
C#
SQL

Functions

A function in JavaScript is a reusable block of code that performs a specific task or calculates a value. Functions allow you to organize your code into modular and reusable components, making your code more maintainable.

Function Declaration

JavaScript functions are defined using the function keyword. You can use a function declaration or a function expression.

Syntax to Declare Functions:

function functionName() {

     // code to be executed
}

Declared functions are not executed immediately. They are “saved for later use” and will be executed later when they are invoked.

Example:

function IqraTechnology() {

  let a = 2;
  let b = 3;
  let c = a * b;

}

Calling Functions:

The code inside a function is not executed when the function is defined. It is executed when the function is invoked. It is common to use the term “call a function” instead of “invoke a function.”

Example 1:

Example 2:

function myFunction() {

  let a = 4;
  let b = 4;
  let c = a * b;

  console.log(c);

}

myFunction();

Parameters and Arguments:

Function parameters are the names listed in the function definition, while function arguments are the real values passed to and received by the function.

Syntax:

function functionName(parameter1, parameter2, parameter3) {

  // code to be executed

}

Example:

function myFunction(a, b) {

  let c = a * b;
  console.log(c);

}

myFunction(6, 7);

Function Expressions

The JavaScript Function Expression is used to define a function inside any expression. It allows the creation of an anonymous function without a function name.

Syntax for Function Declaration:

function functionName(x, y) {

  // statements… return (z)

}

Syntax for Function Expression:

let variableName = function(x, y) {

  // statements… return (z)

};

Example:

var calSub = function(x, y) {

  let z = x – y;
  return z;

};

console.log(“Subtraction: ” + calSub(7, 4));

Arrow Functions

Arrow functions provide a more concise syntax for writing functions, especially when the function is simple and has a single statement.

Syntax:

let functionName = (parameter1, parameter2) => {
  // code to be executed
};

Example:

let myFunction = (a, b) => a * b;

Example:

let hello = () => {

  return “Hello World!”;
}

document.getElementById(“demo”).innerHTML = hello();

Shortened Example:

let hello = () => “Hello World!”;

document.getElementById(“demo”).innerHTML = hello();

It gets shorter! If the function has only one statement and the statement returns a value, you can remove the brackets and the `return` keyword. Arrow functions are especially useful when you want a more concise way to define simple functions.

Call back Functions

Sometimes you would like to have better control over when to execute a function. Callback functions allow you to do that. Suppose you want to do a calculation and then display the result.

Example:

function myDisplayer(some) {

  document.getElementById(“demo”).innerHTML = some;

}

function myFirst() {

  myDisplayer(“Hello”);

}

myFirst();

function myDisplayer(some) {

  document.getElementById(“demo”).innerHTML = some;

}

function myCalculator(num1, num2) {
 
 let sum = num1 + num2;
  myDisplayer(sum);

}

myCalculator(5, 5);

Return Statement

The `return` statement stops the execution of a function and returns a value. The value is optional; if omitted, it returns `undefined`.

Syntax: `return value;`

Example:

function myFunction(x, y) {

  let z = x * y;
  return z;

}

document.write(myFunction(4, 3));

Course Video

Examples for Practice

You have to solve all the questions given below in the editor without copy-pasting.

1. Write a JS program to Create a function called isEven that takes a number as a parameter and returns, if the “number is Even number” is even, else return “number, is odd” if it’s odd.

The task is to write a JavaScript program that defines a function called isEven. This function takes a number as a parameter and returns a message indicating whether the number is even or odd.
1. Define the Function:
Create a function called isEven that takes a single parameter, let’s call it a number.
2. Check Even or Odd:
– Inside the function, use an if-else statement to check if the number is even or odd.
– If the number is even, return the message “Number is even.”
– If the number is odd, return the message “Number is odd.”
3. Pass the argument by calling the function:
– Calls the isEven function with argument 4 and stores the result in the variable resultForEven.
– Calls the isEven function with argument 7 and stores the result in the variable resultForOdd.
4. Display Result:
Print a resultForOdd and resultForEven to the console.

Here’s an example program:

// Define the isEven function
function isEven(number) {
if (number % 2 === 0) {
return “Number is even.”;
} else {
return “Number is odd.”;
}
}

// Example usage of the function
var resultForEven = isEven(4);
var resultForOdd = isEven(7);

console.log(resultForEven); // Output: “Number is even.”
console.log(resultForOdd); // Output: “Number is odd.”

Output

2. Write a JavaScript program that defines a function called find LargestNumber which takes three numbers as parameters and returns the largest of the three. Call this function with numbers 12, 6, and 8.

The task is to write a JavaScript program that defines a function called findLargestNumber. This function takes three numbers as parameters and returns the largest of the three.
1. Define the Function:
Create a function called findLargestNumber that takes three parameters, let’s call them num1, num2, and num3.
2. Find the Largest Number:
– Inside the function, use if and else if statements to compare the three numbers and determine which one is the largest.
– Return the largest number.
3. Pass the argument by calling the function:
Calls the findLargestNumber function with the arguments 12, 6, and 8, and stores the result in the variable largestNumber.
4. Display Result:
Print the result to the console.

Here’s an example program:

// Define the findLargestNumber function
function findLargestNumber(num1, num2, num3) {
if (num1 >= num2 && num1 >= num3) {
return num1;
} else if (num2 >= num1 && num2 >= num3) {
return num2;
} else {
return num3;
}
}

// Example usage of the function
var largestNumber = findLargestNumber(12, 6, 8);

console.log(“The largest number is: ” + largestNumber); // Output: “The largest number is: 12”

Output

3. Write a function that validates a user’s password. The function should take a password as an argument and check if it contains at least 8 characters and at least one special character such as “@,$,&”. Display “Valid” or “Invalid” accordingly.

The task is to write a JavaScript function that validates a user’s password. The function should take a password as an argument and check if it meets certain criteria, such as having at least 8 characters and containing at least one special character from a given set.
1. Define the Function:
Create a function called validatePassword that takes a single parameter, let’s call it a password.
2. Check Password Criteria:
– Inside the function, use if statements to check if the password meets the specified criteria.
– Check if the password has at least 8 characters and contains at least one special character from the set {“@”, “$”, “&”}.
3. Pass the argument by calling the function:
– Calls the validatePassword function with the argument “Secure@123” and stores the result in the variable resultForValidPassword.
– Calls the validatePassword function with the argument “WeakPwd” and stores the result in the variable resultForInvalidPassword.
4. Display Result:
Use Console to Display “Valid” if the password meets the criteria, and “Invalid” otherwise.

Here’s an example program:

// Define the validatePassword function
function validatePassword(password) {
// Check if the password has at least 8 characters
if (password.length >= 8) {
// Check if the password contains at least one special character
if (password.includes(‘@’) || password.includes(‘$’) || password.includes(‘&’)) {
return “Valid”;
} else {
return “Invalid (missing special character)”;
}
} else {
return “Invalid (less than 8 characters)”;
}
}

// Example usage of the function
var resultForValidPassword = validatePassword(“Secure@123”);
var resultForInvalidPassword = validatePassword(“WeakPwd”);

console.log(resultForValidPassword); // Output: “Valid”
console.log(resultForInvalidPassword); // Output: “Invalid (missing special character)”

Output

4. Create a function that takes a string as input and counts the number of vowels in the string using string methods. Display the counts on the document.

The task is to write a JavaScript function that takes a string as input, counts the number of vowels in the string using string methods and then displays the count on the HTML document.
1. Get User Input: Use the prompt function to ask the user to enter a string.
2. Count Vowels:
– Create a function called countVowels that takes the entered string as a parameter.
– Inside the function, use a loop to go through each character of the string.
– Check if the character is a vowel (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) and increment a counter if it is.
3. Display Result on Document: Use document.write to display the count of vowels on the HTML document.

Here’s an example program:

// Define the countVowels function
function countVowels(inputString) {
var vowelCount = 0;

for (var i = 0; i < inputString.length; i++) {
var currentChar = inputString[i].toLowerCase();
if (currentChar === ‘a’ || currentChar === ‘e’ || currentChar === ‘i’ || currentChar === ‘o’ || currentChar === ‘u’) {
vowelCount++;
}
}

return vowelCount;
}

// Get user input for the string
var userInput = prompt(“Enter a string:”);

// Call the countVowels function with user input
var result = countVowels(userInput);

// Display the result on the HTML document
document.write(“<p>The number of vowels in ‘” + userInput + “‘ is: ” + result + “</p>”);

Output

5. Write a JS program to create a function that will take 5 subject marks as an input (out of 80) and using the call back function print the percentage of students get And also check the grade of the student if the student gets 70 and above print “A Grade: with percentage” if a student will get above 50 and below 70 print “B Grade” and else print Fail.
Hint:- create one function to calculate the percentage And another function to check the grade and print the output.

i. Takes 5 subject marks (out of 80) as input. ii. Calculates the percentage of the student. iii. Uses a callback function to print the percentage.
iv. Checks the grade of the student based on the calculated percentage. v. Print the grade along with the percentage.
1. Define the Functions:
– Create a function called calculatePercentage that takes an array of subject marks as a parameter and calculates the percentage.
– Create another function called checkGrade that takes the calculated percentage as a parameter and checks and prints the grade.
2. Get User Input: Use the prompt function to ask the user to enter 5 subject marks.
3. Use Callback Function:
– Pass the array of subject marks to the calculatePercentage function and use it as a callback function.
– Pass the calculated percentage to the checkGrade function and use it as a callback function.
4. Display Result: Print the grade and percentage on the HTML document.

Here’s an example program:

// Define the calculatePercentage function
function calculatePercentage(subjectMarks, callback) {
var totalMarks = 80 * subjectMarks.length;
var obtainedMarks = subjectMarks.reduce((sum, mark) => sum + mark, 0);
var percentage = (obtainedMarks / totalMarks) * 100;
callback(percentage);
}

// Define the checkGrade function
function checkGrade(percentage) {
if (percentage >= 70) {
document.write(“A Grade: ” + percentage.toFixed(2) + “%”);
} else if (percentage >= 50 && percentage < 70) {
document.write(“B Grade: ” + percentage.toFixed(2) + “%”);
} else {
document.write(“Fail”);
}
}

// Get user input for 5 subject marks
var subjectMarksInput = [];
for (var i = 1; i <= 5; i++) {
var mark = parseInt(prompt(“Enter mark for Subject ” + i + ” (out of 80):”));
subjectMarksInput.push(mark);
}

// Call the calculatePercentage function with user input as a callback
calculatePercentage(subjectMarksInput, checkGrade);

Output