13. Functions

Que.1 Create one function with zero parameter having a console statement;

  function func() {
      console.log("Hello, world!");
  }
      
  // Call the func function to output the message to the console
  func();                
        

Que.2 Create one function which takes two values as a parameter and print the sum of them as "Sum of 3, 4 is 7"

  function printSum(a, b) {
    const sum = a + b;
    console.log(`Sum of ${a}, ${b} is ${sum}`);
  }
  printSum(3, 4); // Output: Sum of 3, 4 is 7
        

Que.3 Create one arrow function

  // Example arrow function
  const square = (num) => num * num;
  console.log(square(5)); // Output: 25

        

Que.4 Print output:

  var x = 21;
  var girl = function () {
      console.log(x);
      var x = 20;
  };
  girl ();
        

Output: undefined

Que.5 Print output:

  var x = 21;
  girl ();
  console.log(x)
  function girl() {
      console.log(x);
      var x = 20;
  };            
        

Output:   undefined
21

Que.6 Print output:

  var x = 21;
  a();
  b();
  
    function a() {
      
     x = 20;
    console.log(x);
  };
   function b() {
      
      x = 40;
     console.log(x);
  };
        

Output:   20
40

Que.7 Write a function that accepts parameter n and returns factorial of n

  function factorial(n) {
    // Check if n is negative or not
    if (n < 0) {
      return "Error: Factorial of a negative number does not exist.";
    }
    // If n is 0 or 1, return 1
    else if (n === 0 || n === 1) {
      return 1;
    }
    // Otherwise, calculate the factorial using recursion
    else {
      return n * factorial(n - 1);
    }
  }
  console.log(factorial(5)); // 120
        

Que.8 Guess the Output

  function FindSum(a, b){
      return a + b;
  }
  
  function DisplayData(data, batch){
      console.log(`i am from ${data} and My batch is EA${batch}`)
  }
  
  DisplayData("PrepBytes", FindSum(10, 9));
        

Output:   i am from PrepBytes and My batch is EA19

Que.9 Guess the output

  Abc();
  const Abc = function(){
      let value = 20;
      console.log(value);
  }
        

Output:   ReferenceError: Cannot access 'Abc' before initialization

Que.10 Guess the output

  var a = 10;
  (function (){
      console.log(a);
      var a = 20;
  })();
        

Output:   undefined

Que.11 Guess the output

  const greet =  function(name){
      return function(m){    
          console.log(`Hi!! ${name}, ${m}`);
      }
  }  
  const greet_message = greet('EA19');
  greet_message("Welcome To PrepBytes")
        

Output:   Hi!! EA19, Welcome To PrepBytes

Back
Next