Current Affairs updated daily
KalviGavaniKalviGavani
Class 11 · Tamil Nadu State Board

Javascript Functions Exercise Solutions | KalviGavani

TN Class 11 Computer Applications Javascript Functions exercise solutions — function definition, parameters, return value, built-in functions, scope, recursive functions, MCQ and long answers.

Updated 16 June 202616 min read

Chapter 16 — Javascript Functions: Exercise Solutions Guide

Welcome to the complete exercise solutions for Chapter 16: Javascript Functions from the Samacheer Kalvi Class 11 Computer Applications textbook. This page covers every textbook exercise question with detailed answers, code examples, and exam-focused tips. Solve each exercise on your own first, then use this guide to verify your answers and deepen your understanding.


Key Concepts (Quick Recap)

TermDefinition
FunctionA named block of reusable code that performs a specific task
Function DeclarationDefining a function using the function keyword followed by a name
Function ExpressionAssigning an anonymous function to a variable, e.g. var add = function(a,b){…}
ParameterA variable listed in the function definition that receives a value
ArgumentThe actual value passed to a function when it is called
Return StatementSends a value back to the caller and exits the function
Calling / InvokingExecuting a function by using its name followed by parentheses
Built-in FunctionA function pre-defined in JavaScript, ready to use without writing code
alert()Displays a pop-up dialog box with a message and an OK button
prompt()Displays a dialog that asks the user for input and returns the entered string
confirm()Displays a dialog with OK and Cancel; returns true or false
parseInt()Converts a string to an integer number
parseFloat()Converts a string to a floating-point number
isNaN()Returns true if the value is Not-a-Number
toString()Converts a value to its string representation
toFixed(n)Formats a number to n decimal places and returns a string
eval()Evaluates a string as JavaScript code
User-defined FunctionA function created by the programmer to perform a custom task
Local ScopeVariables declared inside a function are accessible only within that function
Global ScopeVariables declared outside any function are accessible everywhere in the program
Recursive FunctionA function that calls itself to solve a problem by breaking it into smaller sub-problems
Anonymous FunctionA function without a name, often assigned to a variable or used as a callback
HoistingJavaScript moves function declarations to the top of their scope during execution
ScopeThe region of code where a variable is visible and accessible

I. Choose the Correct Answer (MCQ)

1. Which keyword is used to define a function in JavaScript?

  • (a) func
  • (b) function ✓
  • (c) def
  • (d) fun
ExplanationJavaScript uses the function keyword to declare functions. func and fun are not valid keywords. def is used in Python, not JavaScript.

2. What does the return statement do in a function?

  • (a) Prints a value to the console
  • (b) Sends a value back to the caller and exits the function ✓
  • (c) Declares a variable
  • (d) Calls another function
ExplanationThe return statement sends the result of the function back to wherever the function was called and immediately stops further execution within that function.

3. Which of the following is a built-in function in JavaScript?

  • (a) calculate()
  • (b) myFunction()
  • (c) parseInt() ✓
  • (d) processData()
ExplanationparseInt() is a pre-defined JavaScript function that converts a string to an integer. The other options are user-defined function names.

4. What will isNaN("Hello") return?

  • (a) false
  • (b) true ✓
  • (c) undefined
  • (d) NaN
ExplanationisNaN() returns true if the value cannot be converted to a valid number. The string "Hello" is not a number, so the result is true.

5. A variable declared inside a function using var has which scope?

  • (a) Global scope
  • (b) Local scope ✓
  • (c) Block scope
  • (d) Module scope
ExplanationVariables declared with var inside a function are local to that function. They cannot be accessed outside the function. Note: var does not have block scope; only let and const do.

6. Which built-in function displays a dialog box that asks the user for input?

  • (a) alert()
  • (b) confirm()
  • (c) prompt() ✓
  • (d) console.log()
Explanationprompt() displays a dialog with a text field where the user can type input. alert() only shows a message, and confirm() shows OK/Cancel without a text field.

7. What is the output of parseInt("42.5")?

  • (a) 42.5
  • (b) 42 ✓
  • (c) "42.5"
  • (d) NaN
ExplanationparseInt() parses a string and returns an integer. It stops at the decimal point, so parseInt("42.5") returns 42. To get 42.5, use parseFloat().

8. What value does a function return if it has no return statement?

  • (a) null
  • (b) 0
  • (c) undefined ✓
  • (d) "" (empty string)
ExplanationWhen a function finishes execution without encountering a return statement, JavaScript automatically returns undefined.

II. Very Short Answer Questions (2 Marks)

1. What is a function?

A function is a named, reusable block of code designed to perform a specific task. It allows programmers to write code once and call it multiple times, making programs modular, readable, and easier to maintain. Functions can accept input (parameters) and can return a value to the caller.


2. How do you define a function in JavaScript?

A function is defined using the function keyword, followed by the function name, parentheses for parameters, and curly braces containing the function body.

Syntax:

function functionName(parameter1, parameter2) {
    // function body
    return value;
}

Example:

function sayHello() {
    document.write("Hello, welcome to JavaScript!");
}

3. What is a return statement?

The return statement is used inside a function to send a value back to the place where the function was called. When return is executed, the function stops running immediately and the specified value is passed to the caller. If no return statement is present, the function returns undefined.

function square(n) {
    return n * n;
}
var result = square(5); // result is 25

4. What is scope in JavaScript?

Scope determines the accessibility or visibility of variables in different parts of the code. There are two main types:

  • Local scope: Variables declared inside a function are accessible only within that function.
  • Global scope: Variables declared outside any function are accessible from anywhere in the program.
var x = 10;            // Global scope
function test() {
    var y = 20;        // Local scope
    document.write(x); // 10 — accessible
    document.write(y); // 20 — accessible
}
document.write(x);     // 10 — accessible
// document.write(y);  // ERROR — y is not accessible here

5. What is the difference between a parameter and an argument?

ParameterArgument
Variable listed in the function definitionActual value passed when calling the function
Acts as a placeholderIs the real data the function works with
Defined at the time of function creationSupplied at the time of function call
function add(a, b) { // a and b are parameters
    return a + b;
}
var result = add(3, 5); // 3 and 5 are arguments

6. What is a recursive function?

A recursive function is a function that calls itself within its own body to solve a problem by breaking it into smaller, identical sub-problems. Every recursive function must have a base condition (stopping criterion) to prevent infinite recursion.

function factorial(n) {
    if (n === 0) {         // Base condition
        return 1;
    }
    return n * factorial(n - 1); // Recursive call
}
document.write(factorial(5)); // 120

III. Short Answer Questions (3 Marks)

1. Explain function declaration with an example.

A function declaration (also called a function definition or function statement) defines a named function using the function keyword. It consists of:

  • The function keyword
  • A unique function name
  • A parameter list inside parentheses (can be empty)
  • A function body enclosed in curly braces
  • An optional return statement
// Function declaration
function calculateArea(length, breadth) {
    var area = length * breadth;
    return area;
}

// Calling the function
var result = calculateArea(10, 5);
document.write("Area = " + result); // Area = 50

Key points:

  • Function declarations are hoisted — they can be called before they appear in the code.
  • The function name is required and must follow JavaScript naming rules.
  • Parameters act as local variables within the function body.

2. Explain any three built-in functions with examples.

JavaScript provides several built-in functions that are ready to use without any definition:

1. alert() — Displays a pop-up message:
alert("Welcome to our website!");
2. prompt() — Asks the user for input:
var name = prompt("Enter your name:");
document.write("Hello, " + name);
3. parseInt() — Converts a string to an integer:
var num = parseInt("42");
document.write(num + 8); // 50
Answer

Other useful built-in functions include parseFloat(), isNaN(), confirm(), toString(), toFixed(), and eval().


3. Explain local scope and global scope with examples.

Global Scope: A variable declared outside any function has global scope. It can be accessed and modified from any part of the program, including inside functions.

Local Scope: A variable declared inside a function using var, let, or const has local scope. It exists only within that function and is destroyed when the function finishes execution.

var globalVar = "I am global"; // Global scope

function demo() {
    var localVar = "I am local"; // Local scope
    document.write(globalVar);  // Accessible — "I am global"
    document.write(localVar);   // Accessible — "I am local"
}

demo();
document.write(globalVar);  // Accessible — "I am global"
// document.write(localVar); // ERROR — localVar is not defined here

Important: If a variable is declared inside a function without var, it becomes global (which is a bad practice and should be avoided).


4. Write a JavaScript function to check whether a given number is even or odd.

function checkEvenOdd(number) {
    if (number % 2 === 0) {
        document.write(number + " is an Even number");
    } else {
        document.write(number + " is an Odd number");
    }
}

// Calling the function
checkEvenOdd(10); // 10 is an Even number
checkEvenOdd(7);  // 7 is an Odd number

Logic: The modulus operator % returns the remainder of division. If number % 2 equals 0, the number is even; otherwise, it is odd.


IV. Long Answer Questions (5 Marks)

1. Explain the different ways to define functions in JavaScript with examples.

JavaScript supports multiple ways to define functions:

1. Function Declaration (Named Function): The most common way using the function keyword with a name. These are hoisted.

function greet(name) {
    return "Hello, " + name + "!";
}
document.write(greet("Student")); // Hello, Student!

2. Function Expression (Anonymous Function): A function is assigned to a variable. The function has no name of its own. These are NOT hoisted.

var square = function(n) {
    return n * n;
};
document.write(square(6)); // 36

3. Function Expression (Named): A named function is assigned to a variable. Useful for recursion and debugging.

var factorial = function fact(n) {
    if (n <= 1) return 1;
    return n * fact(n - 1); // Calls itself by name
};
document.write(factorial(5)); // 120

4. Arrow Function (ES6): A shorter syntax for writing functions. Does not have its own this context.

var add = (a, b) => a + b;
document.write(add(3, 7)); // 10

5. Immediately Invoked Function Expression (IIFE): A function that runs as soon as it is defined.

(function() {
    document.write("This runs immediately!");
})();

Key Differences:

FeatureFunction DeclarationFunction Expression
Hoisted?YesNo
Can be called before definition?YesNo
Name required?YesOptional

2. Write JavaScript functions for the four arithmetic operations (add, subtract, multiply, divide) and demonstrate their usage.

// Function to add two numbers
function add(a, b) {
    return a + b;
}

// Function to subtract two numbers
function subtract(a, b) {
    return a - b;
}

// Function to multiply two numbers
function multiply(a, b) {
    return a * b;
}

// Function to divide two numbers
function divide(a, b) {
    if (b === 0) {
        return "Error: Division by zero is not allowed";
    }
    return a / b;
}

// Accepting input from the user
var num1 = parseInt(prompt("Enter the first number:"));
var num2 = parseInt(prompt("Enter the second number:"));

// Displaying results
document.write("<h3>Arithmetic Operations</h3>");
document.write(num1 + " + " + num2 + " = " + add(num1, num2) + "<br>");
document.write(num1 + " - " + num2 + " = " + subtract(num1, num2) + "<br>");
document.write(num1 + " * " + num2 + " = " + multiply(num1, num2) + "<br>");
document.write(num1 + " / " + num2 + " = " + divide(num1, num2) + "<br>");

Sample Output (for num1 = 20, num2 = 5):

20 + 5 = 25 20 - 5 = 15 20 * 5 = 100 20 / 5 = 4

Important: The divide() function includes a check for division by zero, which is undefined in mathematics and causes an error in JavaScript if not handled.


3. Explain recursive functions in detail with the factorial example.

A recursive function is a function that calls itself within its own body. Recursion solves a problem by breaking it into smaller, simpler instances of the same problem until a base case is reached.

Essential components of recursion: 1. Base condition (stopping case): The condition under which the function stops calling itself. Without it, the function would recurse infinitely. 2. Recursive step: The part where the function calls itself with a modified argument, moving closer to the base condition.

Example — Factorial of a number:

The factorial of n (written as n!) is the product of all positive integers from 1 to n.

Formulan! = n (n-1) (n-2) ... 1
  • Base condition: 0! = 1
function factorial(n) {
    // Base condition
    if (n === 0) {
        return 1;
    }
    // Recursive step
    return n * factorial(n - 1);
}

// Calling the function
document.write("5! = " + factorial(5)); // 120

How it works — step by step execution of factorial(5):

CallReturns
factorial(5)5 * factorial(4)
factorial(4)4 * factorial(3)
factorial(3)3 * factorial(2)
factorial(2)2 * factorial(1)
factorial(1)1 * factorial(0)
factorial(0)1 (base condition reached)

Now the results cascade back:

  • factorial(1) = 1 * 1 = 1
  • factorial(2) = 2 * 1 = 2
  • factorial(3) = 3 * 2 = 6
  • factorial(4) = 4 * 6 = 24
  • factorial(5) = 5 * 24 = 120

Advantages of recursion:

  • Makes code shorter and easier to read for problems that have a natural recursive structure (factorial, Fibonacci, tree traversal).
  • Reduces the need for complex loops.

Disadvantages of recursion:

  • Uses more memory because each recursive call adds to the call stack.
  • Can cause a stack overflow if the base condition is missing or incorrect.
  • Generally slower than iterative solutions due to function call overhead.

Common Mistakes to Avoid

1. Forgetting the return statement: If you write a function that should produce a result but forget return, the function returns undefined. Always verify that your function returns the intended value.

2. Confusing parameters and arguments: Remember, parameters are the placeholders in the function definition; arguments are the actual values you pass when calling the function.

3. Missing parentheses when calling a function: Writing greet refers to the function object itself, while greet() actually calls the function. These are completely different.

4. Scope confusion — accessing local variables outside the function: Variables declared inside a function with var cannot be used outside that function. Trying to do so causes a ReferenceError.

5. Declaring variables without var inside a function: If you write x = 10 inside a function without var, x becomes a global variable, which can lead to unexpected bugs. Always use var, let, or const.

6. Infinite recursion — forgetting the base condition: A recursive function without a base condition calls itself forever, causing a stack overflow error. Always define when the recursion should stop.

7. Using parseInt() when parseFloat() is needed: parseInt("3.14") returns 3, not 3.14. Use parseFloat() when you need to preserve decimal values.

8. Overusing eval(): The eval() function executes arbitrary strings as code, which is a serious security risk and should be avoided in production code.

9. Passing the wrong number of arguments: JavaScript does not enforce the number of arguments. If you pass fewer than expected, missing parameters become undefined. If you pass more, the extras are ignored.


Exam Checklist

  • [ ] Can define a function using the function keyword with correct syntax
  • [ ] Can distinguish between function declaration and function expression
  • [ ] Understand the difference between parameters and arguments
  • [ ] Can use the return statement and explain what happens without it
  • [ ] Know how to call / invoke a function with and without arguments
  • [ ] Can list and use built-in functions: alert(), prompt(), confirm(), parseInt(), parseFloat(), isNaN(), toString(), toFixed(), eval()
  • [ ] Can explain local scope vs global scope with code examples
  • [ ] Understand variable hoisting and function hoisting
  • [ ] Can write a recursive function with a proper base condition
  • [ ] Can write user-defined functions for arithmetic operations, even/odd check, factorial, etc.
  • [ ] Can identify and fix common errors: missing return, scope issues, infinite recursion
  • [ ] Can trace the execution of a recursive function step by step
  • [ ] Understand anonymous functions and function expressions
  • [ ] Can write functions that accept user input via prompt() and display output via document.write() or alert()

Frequently Asked Questions

Use the function keyword followed by the function name, parentheses for parameters, and curly braces for the body. Example: function greet() { alert('Hello'); }
← Browse all Class 11 Exercise Solutions

More exercise solutions