Assignments Of Day 7: Functions in JavaScript

Rashmi Mishra
0

 Assignments Of Day 7: Functions in JavaScript

Assignment 1: Create a Simple Function

Task: Write a function called greetUser that accepts a name as a parameter and prints "Hello, [name]!" to the console.

Solution:

javascript

Copy code

function greetUser(name) {

    console.log("Hello, " + name + "!");

}

 

greetUser("Alice");  // Output: Hello, Alice!

greetUser("Bob");    // Output: Hello, Bob!

Explanation:
The function greetUser takes one parameter name and prints a greeting message using string concatenation.


Assignment 2: Sum of Two Numbers

Task: Write a function named addNumbers that takes two numbers as parameters and returns their sum.

Solution:

javascript

Copy code

function addNumbers(a, b) {

    return a + b;

}

 

let result = addNumbers(3, 5);

console.log(result);  // Output: 8

Explanation:
The addNumbers function returns the sum of two parameters a and b. The result is assigned to result and printed to the console.


Assignment 3: Function with Default Parameter

Task: Write a function called multiply that accepts two numbers. If the second number is not provided, it should default to 1. The function should return the product of the two numbers.

Solution:

javascript

Copy code

function multiply(a, b = 1) {

    return a * b;

}

 

console.log(multiply(4, 5));  // Output: 20

console.log(multiply(7));     // Output: 7 (default b = 1)

Explanation:
The multiply function uses a default parameter b = 1. If the second argument is not provided, the default value 1 is used.


Assignment 4: Function Expression

Task: Create a function expression that calculates the area of a rectangle. The function should accept length and width as parameters and return the area.

Solution:

javascript

Copy code

const calculateArea = function(length, width) {

    return length * width;

};

 

console.log(calculateArea(5, 10));  // Output: 50

Explanation:
This is a function expression assigned to the variable calculateArea. The function calculates the area by multiplying the length and width.


Assignment 5: Return an Array of Even Numbers

Task: Write a function called evenNumbers that accepts a number n as a parameter and returns an array containing all even numbers from 0 to n.

Solution:

javascript

Copy code

function evenNumbers(n) {

    let evens = [];

    for (let i = 0; i <= n; i++) {

        if (i % 2 === 0) {

            evens.push(i);

        }

    }

    return evens;

}

 

console.log(evenNumbers(10));  // Output: [0, 2, 4, 6, 8, 10]

Explanation:
The function evenNumbers uses a for loop to check if the number is even (i % 2 === 0). If it is, the number is added to the evens array, which is returned at the end.


Assignment 6: Factorial Function

Task: Write a recursive function named factorial that accepts a number n and returns the factorial of that number.

Solution:

javascript

Copy code

function factorial(n) {

    if (n === 0 || n === 1) {

        return 1;

    }

    return n * factorial(n - 1);

}

 

console.log(factorial(5));  // Output: 120

Explanation:
The factorial function calls itself recursively, reducing n by 1 until it reaches the base case (either n === 0 or n === 1), at which point it returns 1. Then, the function multiplies n by the result of factorial(n - 1).


Assignment 7: Checking for Even or Odd

Task: Write a function called checkEvenOdd that accepts a number n and returns whether it is even or odd.

Solution:

javascript

Copy code

function checkEvenOdd(n) {

    if (n % 2 === 0) {

        return "Even";

    } else {

        return "Odd";

    }

}

 

console.log(checkEvenOdd(10));  // Output: Even

console.log(checkEvenOdd(7));   // Output: Odd

Explanation:
The checkEvenOdd function checks if the number n is divisible by 2. If it is, it returns "Even", otherwise it returns "Odd".


Assignment 8: Local and Global Variables

Task: Write a function scopeTest that demonstrates local and global variable scopes. The function should print the value of a global variable and a local variable.

Solution:

javascript

Copy code

let globalVar = "I am global";  // Global variable

 

function scopeTest() {

    let localVar = "I am local";  // Local variable

    console.log(globalVar);  // Can access global variable

    console.log(localVar);   // Can access local variable

}

 

scopeTest();  // Output: I am global, I am local

console.log(globalVar);  // Output: I am global

// console.log(localVar);  // Error: localVar is not defined

Explanation:

  • globalVar is a global variable, accessible inside and outside the function.
  • localVar is a local variable, accessible only inside the function scopeTest.

Assignment 9: Returning the Largest of Three Numbers

Task: Write a function findMax that accepts three numbers and returns the largest one.

Solution:

javascript

Copy code

function findMax(a, b, c) {

    return Math.max(a, b, c);

}

 

console.log(findMax(5, 10, 3));  // Output: 10

console.log(findMax(12, 8, 19)); // Output: 19

Explanation:
The function findMax uses the built-in Math.max() function to return the largest of the three numbers.


Assignment 10: Function with Multiple Parameters

Task: Write a function personInfo that accepts firstName, lastName, and age, and returns a message with the person's full name and age.

Solution:

javascript

Copy code

function personInfo(firstName, lastName, age) {

    return `My name is ${firstName} ${lastName}, and I am ${age} years old.`;

}

 

console.log(personInfo("John", "Doe", 25));  // Output: My name is John Doe, and I am 25 years old.

Explanation:
The personInfo function accepts three parameters (firstName, lastName, and age) and returns a string containing the full name and age.


Summary of Solutions

  • Functions are reusable blocks of code that help you avoid code duplication and improve program structure.
  • Functions can be defined using function declarations and function expressions.
  • Functions can accept parameters, process them, and return values.
  • Scope determines the accessibility of variables. Local variables exist within functions, while global variables are accessible throughout the program.

These assignments cover the core concepts of functions, parameters, return values, and scope, helping you to strengthen your understanding of JavaScript functions.


Let me know if you need further clarifications or more assignments!

4o mini

You said:

more

ChatGPT said:

ChatGPT

Here are more assignments on JavaScript functions with solutions for you:


Assignment 11: Convert Celsius to Fahrenheit

Task: Write a function called celsiusToFahrenheit that converts a temperature from Celsius to Fahrenheit. The formula for conversion is:
F=C×95+32F = C \times \frac{9}{5} + 32F=C×59​+32

Solution:

javascript

Copy code

function celsiusToFahrenheit(celsius) {

    return (celsius * 9/5) + 32;

}

 

console.log(celsiusToFahrenheit(0));    // Output: 32

console.log(celsiusToFahrenheit(100));  // Output: 212

Explanation:
The function celsiusToFahrenheit takes one parameter celsius and applies the conversion formula to return the Fahrenheit value.


Assignment 12: Factorial Using Loop

Task: Write a function called factorialUsingLoop that calculates the factorial of a number using a for loop.

Solution:

javascript

Copy code

function factorialUsingLoop(n) {

    let result = 1;

    for (let i = 1; i <= n; i++) {

        result *= i;

    }

    return result;

}

 

console.log(factorialUsingLoop(5));  // Output: 120

Explanation:
The function uses a for loop to multiply the numbers from 1 to n to calculate the factorial.


Assignment 13: Reverse a String

Task: Write a function reverseString that accepts a string and returns the reversed string.

Solution:

javascript

Copy code

function reverseString(str) {

    return str.split('').reverse().join('');

}

 

console.log(reverseString("hello"));  // Output: "olleh"

Explanation:
The function splits the string into an array of characters using split(''), reverses the array using reverse(), and then joins the array back into a string using join('').


Assignment 14: Palindrome Check

Task: Write a function isPalindrome that accepts a string and returns true if the string is a palindrome, otherwise false. A palindrome is a word that reads the same forward and backward (e.g., "madam").

Solution:

javascript

Copy code

function isPalindrome(str) {

    let reversed = str.split('').reverse().join('');

    return str === reversed;

}

 

console.log(isPalindrome("madam"));  // Output: true

console.log(isPalindrome("hello"));  // Output: false

Explanation:
The function checks if the original string is equal to its reversed version to determine if it's a palindrome.


Assignment 15: Sum of Array Elements

Task: Write a function sumArray that accepts an array of numbers and returns the sum of all the numbers.

Solution:

javascript

Copy code

function sumArray(arr) {

    let sum = 0;

    for (let i = 0; i < arr.length; i++) {

        sum += arr[i];

    }

    return sum;

}

 

console.log(sumArray([1, 2, 3, 4]));  // Output: 10

Explanation:
The function loops through each element of the array and adds it to the sum variable, which is then returned.


Assignment 16: Check Prime Number

Task: Write a function isPrime that checks whether a given number is prime. A prime number is a number greater than 1 that is divisible only by 1 and itself.

Solution:

javascript

Copy code

function isPrime(n) {

    if (n <= 1) {

        return false;

    }

    for (let i = 2; i <= Math.sqrt(n); i++) {

        if (n % i === 0) {

            return false;

        }

    }

    return true;

}

 

console.log(isPrime(7));   // Output: true

console.log(isPrime(10));  // Output: false

Explanation:
The function checks if n is divisible by any number from 2 to sqrt(n). If it is, the function returns false, indicating n is not prime. Otherwise, it returns true.


Assignment 17: Fibonacci Sequence

Task: Write a function fibonacci that returns the first n numbers of the Fibonacci sequence.

Solution:

javascript

Copy code

function fibonacci(n) {

    let fib = [0, 1];

    for (let i = 2; i < n; i++) {

        fib.push(fib[i - 1] + fib[i - 2]);

    }

    return fib;

}

 

console.log(fibonacci(5));  // Output: [0, 1, 1, 2, 3]

Explanation:
The function initializes an array with the first two Fibonacci numbers (0 and 1) and then calculates the subsequent numbers by adding the last two elements of the array.


Assignment 18: Count Occurrences of a Character

Task: Write a function countOccurrences that takes a string and a character as parameters and returns the number of times the character appears in the string.

Solution:

javascript

Copy code

function countOccurrences(str, char) {

    let count = 0;

    for (let i = 0; i < str.length; i++) {

        if (str[i] === char) {

            count++;

        }

    }

    return count;

}

 

console.log(countOccurrences("hello", "l"));  // Output: 2

Explanation:
The function iterates through each character in the string and counts how many times the specified character appears.


Assignment 19: Merge Two Arrays

Task: Write a function mergeArrays that takes two arrays as parameters and returns a new array that contains the elements of both arrays.

Solution:

javascript

Copy code

function mergeArrays(arr1, arr2) {

    return arr1.concat(arr2);

}

 

console.log(mergeArrays([1, 2], [3, 4]));  // Output: [1, 2, 3, 4]

Explanation:
The concat() method is used to merge two arrays, returning a new array containing the elements of both input arrays.


Assignment 20: Remove Duplicates from Array

Task: Write a function removeDuplicates that accepts an array and returns a new array with duplicate values removed.

Solution:

javascript

Copy code

function removeDuplicates(arr) {

    return [...new Set(arr)];

}

 

console.log(removeDuplicates([1, 2, 3, 1, 2, 4]));  // Output: [1, 2, 3, 4]

Explanation:
The function uses a Set to store unique values, as Set automatically removes duplicate values. The ... spread operator is used to convert the Set back into an array.


Summary of Solutions

  • These assignments focus on creating functions to solve common problems such as converting units, calculating sums, checking conditions, and manipulating arrays.
  • Functions can be used to simplify repetitive tasks and improve code modularity and reusability.
  • In JavaScript, you can pass parameters to functions and return values, making them flexible tools for structuring logic.
  • Functions can also be used to handle more complex tasks like recursion, generating sequences, and working with arrays.



Post a Comment

0Comments

Post a Comment (0)