WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

JavaScript · Basic · question 7 of 100

What is the purpose of a function in JavaScript?

📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

In JavaScript, a function is a block of code that can be defined once and called multiple times. Functions are used to encapsulate a set of instructions, which can be executed with different arguments or input values. They can also return a value or modify external variables or objects.

Functions in JavaScript are first-class citizens, meaning that they can be treated like any other value. They can be assigned to variables, passed as arguments to other functions, and returned as values from functions.

Functions can be defined in several ways in JavaScript. The most common way is to use the function keyword, followed by the function name, a list of parameters enclosed in parentheses, and a block of code enclosed in curly braces.

Syntax:

    function functionName(parameter1, parameter2, ...) {
        // Code to be executed
    }

Example:

    function addNumbers(a, b) {
        return a + b;
    }
    
    var result = addNumbers(3, 4);
    console.log(result); // Outputs 7

Functions can also be defined as function expressions, which are assigned to variables like any other value.

Syntax:

    var functionName = function(parameter1, parameter2, ...) {
        // Code to be executed
    };

Example:

    var addNumbers = function(a, b) {
        return a + b;
    };
    
    var result = addNumbers(3, 4);
    console.log(result); // Outputs 7

In addition to these basic functions, JavaScript also supports arrow functions, which provide a shorter syntax for defining functions.

Syntax:

    var functionName = (parameter1, parameter2, ...) => {
        // Code to be executed
    };

Example:

    var addNumbers = (a, b) => a + b;
    
    var result = addNumbers(3, 4);
    console.log(result); // Outputs 7

Functions in JavaScript are often used to create reusable code, to implement complex logic, or to handle events and user interactions in web applications. They are an essential part of the language and are used extensively in both front-end and back-end development.

In summary, the purpose of a function in JavaScript is to encapsulate a set of instructions that can be executed multiple times with different input values or arguments. Functions are a powerful and versatile feature of the language and are essential for building complex applications.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic JavaScript interview — then scores it.
📞 Practice JavaScript — free 15 min
📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

All 100 JavaScript questions · All topics