JS Functions

Functions in JavaScript

In JavaScript, a function is like a mini-program inside your main program. It’s a block of code that performs a specific task or action. Functions help you avoid writing the same code again and again. Instead, you can write the code once and use it multiple times.

Why Use Functions?

• Reusable: Write code once and use it whenever needed.
• Easy to Manage: Makes your program easy to read and organize.
• Flexible: You can use the same function with different values to get different results.

Explanation:

• function: Keyword that declares a function.
• functionName: Name of the function (you use this to call the function later).
• Parentheses(): This tells that it is a function.
• parameter1, parameter2: Parameters (inputs) that the function will use. These are optional, and
  a function can have no parameters.
• { }: The function body where the logic is defined.
• return: Optionally returns a value from the function to the caller. If no return statement is used,
   the function returns undefined by default.

Basic Structure of a Function

Here’s how a simple function looks:

function functionName(parameter1, parameter2) {
    // Code logic here
    return result; // This is optional
}

Example of a Simple Function

function multiply() {
    let a = 4;
    let b = 4;
    let c = a * b;
    console.log(c);
}

multiply(); // This runs the function

Output:
Explanation:

1. Function Declaration: The function multiply is created.
2. Calculations Inside Function: It multiplies a and b (both set to 4), giving 16.
3. Printing the Result: console.log(c) prints 16 to the console.
4. Calling the Function: When multiply() is called, it runs and prints 16.

Arrow Functions

Arrow functions are just another way to write functions, but they are shorter and simpler.

Syntax

const functionName = (parameters) => {
    // Code here
    return result; // Optional
};

Example

const greet = () => “Hello World!”;
document.getElementById(“demo”).innerHTML = greet();

Output
Explanation:

• Arrow Function: greet is a short function that returns “Hello World!”.
• Display in HTML: This code finds the HTML element with id=”demo” and sets its content to “Hello World!”.

Callback Functions

A callback function is a function that you pass as an argument to another function. The second function can call (or “callback”) the first function at the right time. This is often used for things that take time, like waiting for data or for the user to finish typing.

Example of a Callback Function

function greetUser(name, callback) {
    console.log(“Hello, ” + name + “!”);
    callback();
}

function sayGoodbye() {
    console.log(“Goodbye!”);
}

greetUser(“Saad”, sayGoodbye);

Output
Explanation:

1. Main Function: greetUser takes a name and a callback function as input.
2. Executing Callback: greetUser first says “Hello, Saad!” and then calls the sayGoodbye function.
3. Callback Action: sayGoodbye prints “Goodbye!”.

The Return Statement

The return statement lets a function send a value back to the place where it was called. This way, functions can give answers, not just perform actions.

Syntax

return value;

Example

function add(a, b) {
    return a + b;
}

let result = add(3, 4);
console.log(result); // Output: 7

Output
Explanation:

1. Returning a Value: The function adds two numbers and returns the result.
2. Using the Result: The add(3, 4) function call returns 7, which is saved in the result and printed to the console.

Course Video

Practice Scenarios

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

6. Create a Function to Check Palindrome Strings

Objective:
• Create a function that checks whether a given string is a palindrome (i.e., the string reads the same backward as forward).
• The function should ignore spaces, punctuation, and letter case to determine if the string is a palindrome.
• Display whether the string is a palindrome or not on the HTML document using document.write.
Steps to Implement:
1. Get User Input: Prompt the user to enter a string.
2. Check for Palindrome:
o Create a function called checkPalindrome that accepts the string as input.
o Remove spaces, punctuation, and convert the string to lowercase for comparison.
o Check if the cleaned string is the same forward and backward.
3. Display Result on Document: Display whether the string is a palindrome or not on the webpage.

Here’s an example program:

function checkPalindrome(str) {
    let cleanedStr = str.replace(/[^a-zA-Z0-9]/g, ”).toLowerCase(); // Remove non-alphanumeric characters and lowercase the string
    let reversedStr = cleanedStr.split(”).reverse().join(”); // Reverse the cleaned string

    if (cleanedStr === reversedStr) {
        document.write(“The string is a palindrome.”);
    } else {
        document.write(“The string is not a palindrome.”);
    }
}

// Prompt the user for input (string)
let userString = prompt(“Enter a string to check if it’s a palindrome:”);
checkPalindrome(userString);

Output

7.Create a Function to Calculate the Factorial of a Number

Objective:
• Create a function that takes a number as input and calculates its factorial.
• The factorial of a number n is the product of all positive integers less than or equal to n (i.e., n! = n * (n-1) * (n-2) * … * 1).
• Display the factorial result on the document using document.write.
Steps to Implement:
1. Get User Input: Prompt the user to enter a number.
2. Calculate Factorial:
o Create a function called calculateFactorial that accepts the number as input.
o Use a loop to multiply the number by all integers smaller than it (down to 1).
3. Display Result on Document: Use document.write() to display the factorial on the webpage.

Here’s an example program:

function calculateFactorial(n) {
    let factorial = 1;

for (let i = 1; i <= n; i++) {
    factorial *= i; // Multiply current number with the factorial result
}

    // Display the result on the webpage
    document.write(“The factorial of ” + n + ” is: ” + factorial);
}

// Prompt the user for input (number)
let number = prompt(“Enter a number to calculate its factorial:”);
calculateFactorial(Number(number)); // Convert the input to a number

Output

8. Create a Function to Sort an Array of Numbers in Ascending Order

Objective:
• Create a function that takes an array of numbers as input and sorts the array in ascending order (from smallest to largest).
• Display the sorted array on the HTML document using document.write.
• Additionally, ensure that the function handles arrays of different sizes and works for both positive and negative numbers.
Steps to Implement:
1. Get User Input: Use the prompt() function to ask the user to enter a series of numbers separated by commas (e.g., “5, 12, -3, 8”).
2. Sort the Numbers:
o Create a function called sortNumbersAscending that accepts the array of numbers as input.
o Use JavaScript’s built-in .sort() method to sort the numbers in ascending order.
3. Display Sorted Array: After sorting the array, use document.write() to display the sorted array on the webpage.

Here’s an example program:

function sortNumbersAscending(numbers) {
    // Sort the numbers in ascending order using the .sort() method
    numbers.sort((a, b) => a – b);

    // Display the sorted array on the webpage
    document.write(“Sorted Array in Ascending Order: ” + numbers.join(‘, ‘) + “<br>”);
}

// Prompt the user to enter numbers (comma-separated)
let userInput = prompt(“Enter numbers separated by commas (e.g., 5, 12, -3, 8):”);

// Convert the input string into an array of numbers
let numbersArray = userInput.split(‘,’).map(Number);

// Call the function to sort the numbers
sortNumbersAscending(numbersArray);

Output