Appearance
JavaScript Functions Course
Introduction
JavaScript functions are one of the foundational building blocks in the language, allowing developers to encapsulate blocks of code into reusable units. Functions enable you to create modular, maintainable, and readable code. By invoking functions, you can execute the same code multiple times without redundancy, which is essential for efficient programming.
In this course, we will delve into the intricacies of JavaScript functions, exploring their syntax, types, and applications. We'll start by understanding what functions are and why they are crucial in programming. Functions act like a recipe in a cookbook: once you have the instructions, you can recreate the dish anytime you want, without needing to rewrite the recipe each time. This analogy helps highlight their importance in avoiding repetitive code.
Moreover, we'll look at various examples to illustrate how functions operate in real-world scenarios. For instance, think of a function as a coffee machine: you input water and coffee beans, press a button (invoke the function), and the machine (function) processes these inputs to produce coffee. In programming, inputs are known as parameters, and the output is the return value of the function.
Throughout this course, we'll cover different types of functions such as named functions, anonymous functions, and arrow functions. We will also explore advanced concepts like callbacks, closures, and higher-order functions. By the end of this course, you should be comfortable creating and using functions in JavaScript to solve complex problems efficiently.
Key Takeaways
- Functions are reusable blocks of code that perform a specific task.
- They help in making code more modular, maintainable, and efficient.
- Understanding various types of functions and their applications is crucial for advanced JavaScript programming.
Main Content
What is a Function?
A function in JavaScript is a set of statements that performs a task or calculates a value. It is defined by the function
keyword, followed by a name, parameters enclosed in parentheses, and a block of code enclosed in curly braces. Functions allow programmers to write code once and reuse it multiple times, which is vital for reducing redundancy and improving code maintainability.
For example, consider a simple addition function:
javascript
function add(a, b) {
return a + b;
}
1
2
3
2
3
In this function, add
is the function name, a
and b
are parameters, and return a + b;
is the block of code that gets executed when the function is called. You can call this function as many times as needed with different arguments to get the sum of two numbers.
Think of a function as a black box: you provide inputs (parameters), and it processes these to give you an output (return value). This concept is analogous to a vending machine—you select your item (invoke the function) and input your money (parameters), and the machine gives you your snack (return value).
Key Takeaways
- A function consists of a name, parameters, and a block of code.
- Functions help avoid code repetition and are essential for modular programming.
- They can return values, making them versatile tools in programming.
Function Declarations and Expressions
In JavaScript, you can define functions in two primary ways: function declarations and function expressions. A function declaration is a straightforward way to define a function, using the function
keyword followed by the function name and parameters. This type of function is hoisted, meaning it can be called before it is defined in the code.
For example:
javascript
function greet(name) {
return `Hello, ${name}!`;
}
1
2
3
2
3
On the other hand, a function expression involves defining a function and assigning it to a variable. These functions are not hoisted, meaning they must be defined before they are called.
Example of a function expression:
javascript
const greet = function(name) {
return `Hello, ${name}!`;
};
1
2
3
2
3
Imagine function declarations as a well-known public figure who is recognized everywhere, even if they arrive late. In contrast, function expressions are like a newcomer who needs an introduction before they can participate in the conversation.
Key Takeaways
- Function declarations are hoisted, allowing them to be called before they appear in the code.
- Function expressions are not hoisted and must be defined before use.
- Both types of functions are useful in different programming scenarios.
Arrow Functions
Arrow functions, introduced in ES6, provide a more concise syntax for writing function expressions. They are particularly useful for writing short functions and are a popular choice in modern JavaScript development.
Consider the previous greet
function written as an arrow function:
javascript
const greet = (name) => `Hello, ${name}!`;
1
Arrow functions do not have their own this
context, which makes them ideal for certain use cases like array operations or when you don't want the function to have its own binding to this
.
Imagine arrow functions as text shorthand in a chat: they convey the same message with fewer characters, streamlining communication without losing meaning.
Key Takeaways
- Arrow functions offer a concise syntax for defining function expressions.
- They do not have their own
this
context, making them suitable for certain functional programming tasks. - Arrow functions enhance readability and are widely used in modern JavaScript.
Advanced Concepts: Callbacks, Closures, and Higher-Order Functions
As you advance in JavaScript, you'll encounter more complex function concepts such as callbacks, closures, and higher-order functions. These concepts enable more sophisticated programming patterns and solutions.
Callbacks are functions passed into another function as an argument and executed inside that function. They are commonly used for asynchronous programming, such as handling events or API calls.
Example of a callback:
javascript
function fetchData(callback) {
setTimeout(() => {
callback('Data loaded');
}, 1000);
}
1
2
3
4
5
2
3
4
5
Closures are functions that capture variables from their surrounding scope, allowing them to remember the values even after the outer function has finished execution. This feature is useful for data encapsulation and creating private variables.
Example of a closure:
javascript
function counter() {
let count = 0;
return function() {
count += 1;
return count;
};
}
const increment = counter();
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
Higher-Order Functions are functions that take other functions as arguments or return them as results. They are a cornerstone of functional programming and enable powerful abstractions like map, filter, and reduce.
Example of a higher-order function:
javascript
function applyOperation(a, b, operation) {
return operation(a, b);
}
function multiply(x, y) {
return x * y;
}
applyOperation(5, 3, multiply);
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
These advanced concepts can be likened to tools in a craftsman's toolbox, each serving a specific purpose and offering unique capabilities to solve problems creatively.
Key Takeaways
- Callbacks allow asynchronous execution and are fundamental in event-driven programming.
- Closures enable data encapsulation and can create persistent state.
- Higher-order functions support functional programming patterns and abstractions.
Conclusion
By understanding JavaScript functions, you gain the ability to write more efficient and organized code. Functions not only help reduce repetition but also allow for complex operations to be broken down into manageable parts. Whether you're dealing with simple computations or advanced asynchronous tasks, mastering functions is key to becoming a proficient JavaScript developer.
## JavaScript Functions Examples
Hello World Function ★☆☆
javascript
function sayHello() {
console.log("Hello, World!");
}
sayHello();
1
2
3
4
5
2
3
4
5
Explanation:
This is the most basic example of a JavaScript function. The sayHello
function is defined without any parameters and outputs "Hello, World!" to the console when called.
Adding Two Numbers ★☆☆
javascript
function addNumbers(num1, num2) {
return num1 + num2;
}
console.log(addNumbers(5, 10)); // Output: 15
1
2
3
4
5
2
3
4
5
Explanation:
This function takes two parameters, num1
and num2
, and returns their sum. This demonstrates how to pass arguments to a function and use the return
statement.
Default Parameters ★☆☆
javascript
function greet(name = "Guest") {
console.log("Hello, " + name + "!");
}
greet(); // Output: Hello, Guest!
greet("Alice"); // Output: Hello, Alice!
1
2
3
4
5
6
2
3
4
5
6
Explanation:
The greet
function demonstrates the use of default parameters. If a value for name
is not provided when the function is invoked, it defaults to "Guest".
Function Expression ★☆☆
javascript
const multiply = function(a, b) {
return a * b;
};
console.log(multiply(3, 4)); // Output: 12
1
2
3
4
5
2
3
4
5
Explanation:
Here, a function expression is used to define a function that multiplies two numbers. This function is stored in a variable named multiply
.
Arrow Function ★☆☆
javascript
const square = (x) => x * x;
console.log(square(5)); // Output: 25
1
2
3
2
3
Explanation:
This example shows a concise arrow function that calculates the square of a number. Arrow functions provide a more concise syntax compared to traditional function expressions.
Immediately Invoked Function Expression (IIFE) ★★☆
javascript
(function() {
console.log("This is an IIFE");
})();
1
2
3
2
3
Explanation:
An Immediately Invoked Function Expression (IIFE) is a function that runs as soon as it is defined. This is useful for code that needs to be executed immediately and avoids polluting the global scope.
Rest Parameters ★★☆
javascript
function sumAll(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sumAll(1, 2, 3, 4)); // Output: 10
1
2
3
4
5
2
3
4
5
Explanation:
The sumAll
function uses the rest parameter syntax (...numbers
) to accept any number of arguments, which are then summed using the reduce
method.
Callback Function ★★☆
javascript
function fetchData(callback) {
setTimeout(() => {
callback("Data received!");
}, 1000);
}
fetchData(message => {
console.log(message);
});
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
Explanation:
This example illustrates a simple callback function. The fetchData
function simulates an asynchronous operation using setTimeout
and calls the provided callback function with a message once the operation is complete.
Higher-Order Function ★★★
javascript
function applyOperation(a, b, operation) {
return operation(a, b);
}
function subtract(x, y) {
return x - y;
}
console.log(applyOperation(10, 5, subtract)); // Output: 5
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
Explanation:
A higher-order function is a function that takes another function as an argument. applyOperation
is a higher-order function that applies a given operation to two numbers.
Closure Example ★★★
javascript
function createCounter() {
let count = 0;
return function() {
count += 1;
return count;
};
}
const counter = createCounter();
console.log(counter()); // Output: 1
console.log(counter()); // Output: 2
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
Explanation:
This example demonstrates a closure. The inner function maintains access to the count
variable even after the outer function (createCounter
) has completed execution, allowing count
to be incremented with each call.
Factorial Using Recursion ★★★
javascript
function factorial(n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(5)); // Output: 120
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
Explanation:
The factorial
function is a classic example of recursion, where a function calls itself to solve a problem. The base case is when n
is less than or equal to 1, at which point the recursion stops.
Lexical Scoping of 'this' in Arrow Function ★★★
javascript
const person = {
name: "John",
greet: function() {
setTimeout(() => {
console.log("Hello, " + this.name);
}, 1000);
}
};
person.greet(); // Output: Hello, John
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
Explanation:
Arrow functions do not have their own this
context; they inherit this
from the enclosing scope. This example shows how an arrow function inside a setTimeout
inherits this
from the greet
method of the person
object.
Anonymous Function ★★★
javascript
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled); // Output: [2, 4, 6, 8]
1
2
3
4
5
6
2
3
4
5
6
Explanation:
An anonymous function is used here with the map
method to double each number in an array. Anonymous functions are useful for short, one-time use cases.
Recursive Sum ★★★
javascript
function recursiveSum(arr) {
if (arr.length === 0) {
return 0;
}
return arr[0] + recursiveSum(arr.slice(1));
}
console.log(recursiveSum([1, 2, 3, 4])); // Output: 10
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
Explanation:
This function uses recursion to calculate the sum of an array. Each call to recursiveSum
processes the first element of the array and calls itself with the rest of the array.
Local vs. Global Scope ★★★
javascript
let globalVar = "I am global";
function checkScope() {
let localVar = "I am local";
console.log(globalVar); // Output: I am global
console.log(localVar); // Output: I am local
}
checkScope();
// console.log(localVar); // Error: localVar is not defined
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
Explanation:
This example shows the difference between local and global scope. localVar
is only accessible within the checkScope
function, while globalVar
is accessible anywhere in the script.
Block Scope with let and const ★★★
javascript
function testBlockScope() {
if (true) {
let blockScopedVar = "I am block scoped";
console.log(blockScopedVar); // Output: I am block scoped
}
// console.log(blockScopedVar); // Error: blockScopedVar is not defined
}
testBlockScope();
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
Explanation:
This example demonstrates block scope using let
. Variables declared with let
or const
within a block ({}
) are not accessible outside that block.
Function Hoisting ★★★
javascript
console.log(hoistedFunction()); // Output: Hoisting works!
function hoistedFunction() {
return "Hoisting works!";
}
1
2
3
4
5
2
3
4
5
Explanation:
In JavaScript, function declarations are hoisted to the top of their containing scope. This means you can call the function before its declaration in the code.
Asynchronous Callback ★★★
javascript
function fetchDataAsync(callback) {
setTimeout(() => {
callback("Async data received!");
}, 2000);
}
fetchDataAsync(data => {
console.log(data);
});
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
Explanation:
This example illustrates an asynchronous callback using setTimeout
. The callback function is executed after the delay, simulating a delay in data retrieval.
Chaining Promises with Functions ★★★
javascript
function firstPromise() {
return Promise.resolve("First result");
}
function secondPromise(result) {
return Promise.resolve(result + " and Second result");
}
firstPromise()
.then(result => secondPromise(result))
.then(finalResult => console.log(finalResult)); // Output: First result and Second result
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
Explanation:
This example shows how functions can be used to chain promises. Each function returns a promise, and the results are passed along the chain using then
.
Using Functions to Create Modules ★★★
javascript
const counterModule = (function() {
let count = 0;
return {
increment: function() {
count++;
console.log(count);
},
reset: function() {
count = 0;
console.log("Counter reset");
}
};
})();
counterModule.increment(); // Output: 1
counterModule.increment(); // Output: 2
counterModule.reset(); // Output: Counter reset
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Explanation:
This example demonstrates how functions can be used to create modules. The counterModule
uses an IIFE to encapsulate private state (count
) and exposes public methods (increment
and reset
) to interact with that state.
## JavaScript Functions Exercises
Simple Greeting Function ★☆☆
javascript
function greet() {
return "Hello!";
}
console.log(greet()); // Output: Hello!
1
2
3
4
5
2
3
4
5
Explanation:
This exercise focuses on creating a simple function that returns a greeting message. It reinforces the understanding of function declaration and invocation without parameters.
Function with Two String Parameters ★☆☆
javascript
function fullName(firstName, lastName) {
return firstName + " " + lastName;
}
console.log(fullName("Jane", "Doe")); // Output: Jane Doe
1
2
3
4
5
2
3
4
5
Explanation:
In this task, students will create a function that takes two string parameters and returns them concatenated with a space. It helps practice using parameters and the return statement.
Calculate Rectangle Area ★☆☆
javascript
function rectangleArea(length, width) {
return length * width;
}
console.log(rectangleArea(5, 3)); // Output: 15
1
2
3
4
5
2
3
4
5
Explanation:
This exercise requires the creation of a function to calculate the area of a rectangle given its length and width. It reinforces basic arithmetic operations within functions.
Default Parameter for Discount ★☆☆
javascript
function calculateTotal(price, discount = 0) {
return price - (price * (discount / 100));
}
console.log(calculateTotal(100)); // Output: 100
console.log(calculateTotal(100, 10)); // Output: 90
1
2
3
4
5
6
2
3
4
5
6
Explanation:
Here, students will implement a function that calculates the total price after applying a discount, using a default parameter for the discount. This exercise emphasizes the use of default parameters.
Function Expression for Division ★☆☆
javascript
const divide = function(a, b) {
return a / b;
};
console.log(divide(10, 2)); // Output: 5
1
2
3
4
5
2
3
4
5
Explanation:
Students will define a function expression to perform division. This task highlights the difference between function declarations and expressions.
Arrow Function for Triple ★☆☆
javascript
const triple = (n) => n * 3;
console.log(triple(4)); // Output: 12
1
2
3
2
3
Explanation:
This exercise introduces arrow functions, requiring students to write a concise function that triples a given number.
IIFE for Immediate Log ★★☆
javascript
(function() {
console.log("Immediately Invoked!");
})();
1
2
3
2
3
Explanation:
Students will learn about IIFE by implementing a function that logs a message immediately upon definition. This exercise stresses the importance of function scope and immediate execution.
Sum with Rest Parameters ★★☆
javascript
function sum(...nums) {
return nums.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // Output: 15
1
2
3
4
5
2
3
4
5
Explanation:
Here, students will create a function using rest parameters to sum an arbitrary number of numbers. This task focuses on advanced parameter handling.
Synchronous Callback ★★☆
javascript
function processData(data, callback) {
callback(data * 2);
}
function logResult(result) {
console.log(result);
}
processData(5, logResult); // Output: 10
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
Explanation:
This exercise involves writing a function that processes data using a synchronous callback function, reinforcing the concept of callback functions.
Higher-Order Function with Math Operation ★★★
javascript
function performOperation(x, y, operation) {
return operation(x, y);
}
function add(x, y) {
return x + y;
}
console.log(performOperation(3, 7, add)); // Output: 10
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
Explanation:
In this task, students will create a higher-order function that accepts another function as a parameter to perform a math operation, emphasizing the concept of higher-order functions.
Closure for Counter ★★★
javascript
function counter() {
let count = 0;
return function() {
count++;
return count;
};
}
const myCounter = counter();
console.log(myCounter()); // Output: 1
console.log(myCounter()); // Output: 2
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
Explanation:
Students will implement a closure that maintains a private count variable, returning it via an inner function. This exercise focuses on closures and their practical applications.
Recursive Countdown ★★★
javascript
function countdown(n) {
if (n < 0) return;
console.log(n);
countdown(n - 1);
}
countdown(5); // Output: 5 4 3 2 1 0
1
2
3
4
5
6
7
2
3
4
5
6
7
Explanation:
This task requires writing a recursive function to count down from a given number to zero. It emphasizes understanding of base and recursive cases in recursion.
Arrow Function with Lexical 'this' ★★★
javascript
const team = {
name: "Developers",
members: ["Alice", "Bob"],
teamSummary: function() {
this.members.forEach((member) => {
console.log(`${member} is on team ${this.name}`);
});
}
};
team.teamSummary(); // Output: Alice is on team Developers; Bob is on team Developers
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
Explanation:
Students will explore lexical scoping of this
in arrow functions by implementing a function that outputs team member information. It reinforces the behavior of this
in arrow functions.
Anonymous Function in Event Handler ★★★
javascript
document.querySelector('button').addEventListener('click', function() {
console.log('Button clicked!');
});
1
2
3
2
3
Explanation:
This exercise involves using an anonymous function as an event handler for a button click, reinforcing the use of anonymous functions in practical applications.
Recursive Function for Fibonacci ★★★
javascript
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
console.log(fibonacci(6)); // Output: 8
1
2
3
4
5
6
2
3
4
5
6
Explanation:
Students will create a recursive function to compute the nth Fibonacci number, focusing on recursion and understanding base cases.
Block Scope with let and const ★★★
javascript
function testScope() {
if (true) {
const blockScoped = "Inside block";
console.log(blockScoped); // Output: Inside block
}
// console.log(blockScoped); // Error: blockScoped is not defined
}
testScope();
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
Explanation:
This task emphasizes block scope by requiring a function that demonstrates variable scoping with let
and const
inside an if
block.
Hoisting with Function Expressions ★★★
javascript
// console.log(nonHoisted()); // Error: nonHoisted is not defined
const nonHoisted = function() {
return "Function expressions are not hoisted!";
};
1
2
3
4
5
2
3
4
5
Explanation:
Students will learn the difference in hoisting behavior between function declarations and expressions, demonstrating that function expressions are not hoisted.
Asynchronous Callback with setTimeout ★★★
javascript
function delayedMessage(callback) {
setTimeout(() => {
callback("This is delayed");
}, 1500);
}
delayedMessage((message) => {
console.log(message);
});
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
Explanation:
This exercise involves using setTimeout
to simulate an asynchronous operation, with a callback function handling the delayed message.
Chaining Functions with Promises ★★★
javascript
function stepOne() {
return Promise.resolve("Step 1 complete");
}
function stepTwo(previous) {
return Promise.resolve(previous + "; Step 2 complete");
}
stepOne()
.then(stepTwo)
.then(result => console.log(result)); // Output: Step 1 complete; Step 2 complete
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
Explanation:
Students will chain functions using promises, understanding how promise resolution flows through then
calls.
Module Pattern with Functions ★★★
javascript
const calculatorModule = (function() {
let total = 0;
return {
add: function(num) {
total += num;
return total;
},
reset: function() {
total = 0;
return total;
}
};
})();
console.log(calculatorModule.add(5)); // Output: 5
console.log(calculatorModule.reset()); // Output: 0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Explanation:
This task demonstrates using functions to create a module pattern, encapsulating private data and exposing public methods for interaction.
Recursive Array Flattening ★★★
javascript
function flattenArray(arr) {
return arr.reduce((acc, val) =>
Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), []
);
}
console.log(flattenArray([1, [2, [3, 4], 5], 6])); // Output: [1, 2, 3, 4, 5, 6]
1
2
3
4
5
6
7
2
3
4
5
6
7
Explanation:
Students will implement a recursive function to flatten a nested array, reinforcing recursion and array manipulation skills.
These exercises are designed to progressively build a deeper understanding of JavaScript functions, starting from the basics and advancing to more complex concepts like closures, recursion, and asynchronous programming.
## JavaScript: Functions
Quiz about: "JavaScript: functions"
Question 1:
What is the main purpose of a function in JavaScript?
markdown
A. To store multiple values
B. To execute a block of code when invoked
C. To define a variable
D. To declare an object
E. To loop through arrays
1
2
3
4
5
2
3
4
5
Correct Answer: B. To execute a block of code when invoked
Question 2:
Which of the following is the correct syntax to declare a function named myFunction
?
markdown
A. `function myFunction() {}`
B. `myFunction function() {}`
C. `def myFunction() {}`
D. `function: myFunction() {}`
E. `declare function myFunction() {}`
1
2
3
4
5
2
3
4
5
Correct Answer: A. function myFunction() {}
Question 3:
How do you invoke a function named calculate
?
markdown
A. `calculate{}`
B. `call calculate`
C. `invoke calculate()`
D. `calculate()`
E. `execute calculate()`
1
2
3
4
5
2
3
4
5
Correct Answer: D. calculate()
Question 4:
What will be the output of the following function call?
javascript
function add(a, b) {
return a + b;
}
console.log(add(2, 3));
1
2
3
4
2
3
4
markdown
A. `23`
B. `5`
C. `undefined`
D. `NaN`
E. `null`
1
2
3
4
5
2
3
4
5
Correct Answer: B. 5
Question 5:
What is the default value of a JavaScript function parameter if not explicitly defined?
markdown
A. `null`
B. `undefined`
C. `0`
D. `NaN`
E. `false`
1
2
3
4
5
2
3
4
5
Correct Answer: B. undefined
Question 6:
How can you define a function with default parameters?
javascript
function multiply(a, b = 1) {
return a * b;
}
1
2
3
2
3
What is the output when multiply(5)
is called?
markdown
A. `5`
B. `0`
C. `NaN`
D. `undefined`
E. `1`
1
2
3
4
5
2
3
4
5
Correct Answer: A. 5
Question 7:
Which of the following statements correctly describes a function expression?
markdown
A. A function defined as part of an object
B. A function stored in a variable
C. A function with no parameters
D. A function that returns no value
E. A function that is never invoked
1
2
3
4
5
2
3
4
5
Correct Answer: B. A function stored in a variable
Question 8:
What is an IIFE (Immediately Invoked Function Expression)?
markdown
A. A function that runs only once
B. A function that runs as soon as it is defined
C. A function that runs after a delay
D. A function that requires no parameters
E. A function that returns immediately
1
2
3
4
5
2
3
4
5
Correct Answer: B. A function that runs as soon as it is defined
Question 9:
Which of the following is the correct syntax for an arrow function?
markdown
A. `() => {}`
B. `function => {}`
C. `=> function {}`
D. `function() => {}`
E. `=> {}`
1
2
3
4
5
2
3
4
5
Correct Answer: A. () => {}
Question 10:
What is the main advantage of using arrow functions?
markdown
A. They are faster to execute
B. They automatically bind `this` to the surrounding code
C. They don't require parentheses
D. They can have multiple return statements
E. They are always asynchronous
1
2
3
4
5
2
3
4
5
Correct Answer: B. They automatically bind this
to the surrounding code
Question 11:
Which of the following is an example of a higher-order function?
javascript
function map(arr, func) {
let result = [];
for (let i = 0; i < arr.length; i++) {
result.push(func(arr[i]));
}
return result;
}
1
2
3
4
5
6
7
2
3
4
5
6
7
What does this function do?
markdown
A. It maps a value to an array
B. It transforms each element of an array using a function
C. It filters elements of an array
D. It reduces an array to a single value
E. It sorts an array
1
2
3
4
5
2
3
4
5
Correct Answer: B. It transforms each element of an array using a function
Question 12:
What does a callback function do?
markdown
A. It calls another function
B. It is passed as an argument to another function
C. It returns a function
D. It is only used in asynchronous code
E. It executes code in the global scope
1
2
3
4
5
2
3
4
5
Correct Answer: B. It is passed as an argument to another function
Question 13:
Which of the following best describes a closure in JavaScript?
markdown
A. A loop inside a function
B. An object returned by a function
C. A function having access to variables in its outer scope
D. A function declared inside another function
E. A function with no parameters
1
2
3
4
5
2
3
4
5
Correct Answer: C. A function having access to variables in its outer scope
Question 14:
How does block scope differ from function scope?
markdown
A. Block scope is only available in ES6 and later
B. Block scope refers to variables declared with `var`
C. Function scope is limited to `let` and `const`
D. Block scope applies to variables declared within a block, like `if` or `for`
E. Block scope does not exist in JavaScript
1
2
3
4
5
2
3
4
5
Correct Answer: D. Block scope applies to variables declared within a block, like if
or for
Question 15:
What is recursion in programming?
markdown
A. A function that calls itself
B. A function that loops indefinitely
C. A function that returns nothing
D. A function that executes conditionally
E. A function that never terminates
1
2
3
4
5
2
3
4
5
Correct Answer: A. A function that calls itself
Question 16:
In a recursive function, what is the purpose of a base case?
markdown
A. To start the recursion
B. To define the function
C. To stop the recursion
D. To optimize performance
E. To handle errors
1
2
3
4
5
2
3
4
5
Correct Answer: C. To stop the recursion
Question 17:
Which of the following is true about local and global scope?
markdown
A. Local variables are accessible anywhere in the code
B. Global variables can be accessed from anywhere in the code
C. Local and global scopes are the same
D. Variables declared in a function are global
E. Global variables cannot be modified
1
2
3
4
5
2
3
4
5
Correct Answer: B. Global variables can be accessed from anywhere in the code
Question 18:
How do you define a function with rest parameters?
javascript
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
1
2
3
2
3
What does this function do?
markdown
A. It sums all arguments passed to it
B. It multiplies all arguments passed to it
C. It concatenates all arguments into a string
D. It returns the first argument
E. It returns the number of arguments
1
2
3
4
5
2
3
4
5
Correct Answer: A. It sums all arguments passed to it
Question 19:
Which statement is true regarding synchronous and asynchronous callbacks?
markdown
A. Synchronous callbacks run in parallel
B. Asynchronous callbacks block the execution
C. Asynchronous callbacks run after the main code is finished
D. Synchronous callbacks are non-blocking
E. Both run at the same time
1
2
3
4
5
2
3
4
5
Correct Answer: C. Asynchronous callbacks run after the main code is finished
Question 20:
What is the output of the following code?
javascript
(function() {
var a = b = 5;
})();
console.log(b);
1
2
3
4
2
3
4
markdown
A. `5`
B. `undefined`
C. `ReferenceError`
D. `TypeError`
E. `NaN`
1
2
3
4
5
2
3
4
5
Correct Answer: A. 5