Functions

Learn about function declarations, expressions, and arrow functions in JavaScript.

Present State

Functions are fundamental building blocks in JavaScript that allow you to encapsulate reusable code. They can be declared in multiple ways such as function declarations, function expressions, and arrow functions. Each has unique syntax and behavior, especially regarding the handling of the this keyword.

Code Example

Example showing different ways to define functions:

JavaScript Functions Example

// Function Declaration
function greet(name) {
  return `Hello, ${name}!`;
}

// Function Expression
const greetExpr = function(name) {
  return `Hi, ${name}!`;
};

// Arrow Function
const greetArrow = (name) => `Hey, ${name}!`;

// Usage
console.log(greet("Alice"));
console.log(greetExpr("Bob"));
console.log(greetArrow("Charlie"));
          

This code demonstrates:

  • Defining functions using declarations and expressions.
  • Creating concise arrow functions with implicit return.
  • Invoking functions with arguments.

Description

Functions in JavaScript allow you to group statements that perform a task or calculate a value:
  • Function Declaration: Traditional way to declare functions, hoisted to the top of their scope.
  • Function Expression: Functions assigned to variables, not hoisted.
  • Arrow Functions: Introduced in ES6, offer a shorter syntax and lexical this binding.
Functions help in modularizing code, improving readability, and enabling code reuse.

Applications

  • Event Handlers: Functions used as callbacks for user actions like clicks.
  • Data Processing: Encapsulate logic for calculations or transformations.
  • Modular Code: Breaking complex programs into smaller, manageable pieces.
  • Functional Programming: Use of functions as first-class citizens for advanced patterns.

Multiple Choice Questions

Q1: Which type of function is hoisted in JavaScript?

  • A. Function Declaration
  • B. Function Expression
  • C. Arrow Function
  • D. None of the above

Answer: A. Function Declaration

Q2: Arrow functions differ from regular functions mainly because:

  • A. They do not have their own this
  • B. They cannot take parameters
  • C. They are hoisted
  • D. They must always use curly braces

Answer: A. They do not have their own this

Q3: Which syntax is a function expression?

  • A. function foo() {}
  • B. const foo = function() {}
  • C. const foo = () => {}
  • D. Both B and C

Answer: D. Both B and C

Q4: What will the following arrow function return? () => 5 + 3

  • A. 8
  • B. A function
  • C. NaN
  • D. Syntax Error

Answer: B. A function