Functions - JavaScript Interview Questions
JavaScript Fundamentals: JavaScript Functions
Can you name at least three types of functions in JavaScript?
View Answer:
Regular Function:
function greeting(name) {
return `Hello, ${name}!`;
}
console.log(greeting("John")); // Outputs: Hello, John!
Arrow Function:
const greeting = (name) => `Hello, ${name}!`;
console.log(greeting("John")); // Outputs: Hello, John!
Anonymous Function:
setTimeout(function() {
console.log("This is an anonymous function!");
}, 1000);
What is the definition of a JavaScript Function?
View Answer:
function square(x) {
return x * x;
}
square(10); // 100
Can you describe the basic structure of a JavaScript function declaration?
View Answer:
function name(parameters) {
...body...
}
What is one of the primary purposes of JavaScript functions?
View Answer:
function showMessage(name) {
console.log('Hello, ' + name);
}
showMessage('John'); // Hello, John
showMessage('Jane'); // Hello, Jane
Is there a limitation on variables declared inside a function?
View Answer:
function showMessage() {
let message = "Hello, I'm JavaScript!"; // local variable
console.log(message);
}
showMessage(); // Hello, I'm JavaScript!
console.log(message); // <-- Error! The variable is local to the function.
Can functions access variables outside the function body?
View Answer:
let userName = 'John';
function showMessage() {
userName = 'Bob'; // (1) changed the outer variable
let message = 'Hello, ' + userName;
console.log(message);
}
console.log(userName); // John before the function call
showMessage(); // Hello, Bob modified through invocation
console.log(userName); // Bob, the value was modified by the function
What is a Global variable?
View Answer:
let globalVar = "I am a global variable";
function showGlobalVar() {
console.log(globalVar); // Outputs: I am a global variable
}
showGlobalVar();
What is the Modern JavaScript rule for using Global Variables?
View Answer:
What is the difference between a parameter and a argument in JavaScript?
View Answer:
// 'x' and 'y' are parameters in this function declaration
function add(x, y) {
return x + y;
}
// '5' and '7' are arguments in this function invocation
console.log(add(5, 7)); // Outputs: 12
In the add
function, x
and y
are parameters. When we call add(5, 7)
, 5
and 7
are the arguments.
Can you explain how to use parameters in functions?
View Answer:
function showMessage(from, text) {
// arguments: from, text
console.log(from + ': ' + text);
}
showMessage('Ann', 'Hello!'); // Ann: Hello! (*)
showMessage('Ann', "What's up?"); // Ann: What's up? (**)
What happens when a function argument does not get provided?
View Answer:
function showMessage(from, text) {
// arguments: from, text
console.log(from + ': ' + text);
}
showMessage('Ann'); // "Ann: undefined"
How is a default function parameter evaluated in JavaScript?
View Answer:
function showMessage(from, text = anotherFunction()) {
// anotherFunction() only executed if text is not given
// the result becomes the value of text
}
Is there a way to check for an omitted function parameter and return a new value?
View Answer:
function showMessage(text) {
if (text === undefined) {
text = 'empty message';
}
console.log(text);
}
showMessage(); // empty message
// Or we could use the || operator
// if text parameter is omitted or "" is passed, set it to 'empty'
function showMessage(text) {
text = text || 'empty';
...
}
Can you implement multiple occurrences of the return statement in a single function?
View Answer:
function checkAge(age) {
if (age >= 18) {
return true;
} else {
return confirm('Do you have permission from your parents?');
}
}
let age = prompt('How old are you?', 18);
if (checkAge(age)) {
console.log('Access granted');
} else {
console.log('Access denied');
}
Why is not recommended to use multiple return statements in JavaScript?
View Answer:
Is it possible to use a return statement without a value?
View Answer:
function showMovie(age) {
if (!checkAge(age)) {
return;
}
console.log('Showing you the movie'); // (*)
// ...
}
What does a return statement with an empty value output?
View Answer:
function doNothing() {
/* empty */
}
console.log(doNothing() === undefined); // true
// An empty return is also the same as return undefined:
function doNothing() {
return;
}
console.log(doNothing() === undefined); // true
What is the most important thing to remember when using a return statement?
View Answer:
function multiply(a, b) {
let result = a * b;
// this return statement provides the intended output and ends the function
return result;
}
console.log(multiply(5, 3)); // Outputs: 15
What are good naming practices for function names?
View Answer:
showMessage(..) // shows a message
getAge(..) // returns the age (gets it somehow)
calcSum(..) // calculates a sum and returns the result
createForm(..) // creates a form (and usually returns it)
checkPermission(..) // checks a permission, returns true/false
What are best practices for the creation of a function?
View Answer:
Should there be a separation of the concerns in functions?
View Answer:
function showPrimes(n) {
nextPrime: for (let i = 2; i < n; i++) {
for (let j = 2; j < i; j++) {
if (i % j == 0) continue nextPrime;
}
console.log(i); // a prime
}
}
function showPrimes(n) {
for (let i = 2; i < n; i++) {
if (!isPrime(i)) continue;
console.log(i); // a prime
}
}
function isPrime(n) {
for (let i = 2; i < n; i++) {
if (n % i == 0) return false;
}
return true;
}
What is a callback function in JavaScript?
View Answer:
function greeting(name) {
console.log(`Hello, ${name}!`);
}
function processUserInput(callback) {
let name = prompt('Please enter your name.');
callback(name);
}
processUserInput(greeting); // Outputs: Hello, [entered name]!
What is a higher-order function in JavaScript?
View Answer:
// A higher-order function 'operate' that takes a function as an argument
function operate(a, b, operation) {
return operation(a, b);
}
// Functions that can be passed as arguments
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
console.log(operate(5, 3, add)); // Outputs: 8
console.log(operate(5, 3, multiply)); // Outputs: 15
In this code, the operate
function is a higher-order function. It accepts two numbers and a function as arguments, and returns the result of applying the function to the numbers. The add
and multiply
functions can be passed as arguments to the operate
function.
What is a closure in JavaScript?
View Answer:
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
console.log('outerVariable:', outerVariable);
console.log('innerVariable:', innerVariable);
}
}
const newFunction = outerFunction('outside');
newFunction('inside'); // Outputs: outerVariable: outside, innerVariable: inside
In this code, innerFunction
is a closure that is defined inside outerFunction
and has access to outerFunction
's variables and parameters. Even when outerFunction
has returned and its execution context is gone, innerFunction
still has access to outerVariable
due to closure.
What is a pure function in JavaScript?
View Answer:
function add(a, b) {
return a + b;
}
console.log(add(5, 3)); // Outputs: 8
console.log(add(5, 3)); // Outputs: 8
In this code, add is a pure function. Given the same arguments (5 and 3), it will always return the same result (8). It doesn't rely on or modify any external state or variables, making it predictable and consistent.
What are the benefits of using pure functions in JavaScript?
View Answer:
What are Side-Effects in JavaScript functions?
View Answer:
let count = 1;
function increaseCount(value) {
count = count + value; // Modifying global variable 'count' is a side effect
}
increaseCount(5);
console.log(count); // Outputs: 6
In this code, the increaseCount
function modifies the global variable count
, which is a side effect. The function is therefore not pure, because it changes state outside its scope.
Can a function declaration be called earlier than it is defined?
View Answer:
Here's a JavaScript code example that demonstrates how function declarations can be invoked before they are defined due to hoisting.
// Function invocation before declaration
console.log(greet('John')); // Outputs: Hello, John!
// Function declaration
function greet(name) {
return `Hello, ${name}!`;
}
In this code, the greet
function is called before it's defined. But because JavaScript hoists function declarations, it works without any errors.
What is the scope of data in a function?
View Answer:
What is the purpose of the “this” keyword in JavaScript?
View Answer:
// Define an object
const person = {
name: "John",
age: 30,
greet: function() {
console.log("Hello, my name is " + this.name + " and I am " + this.age + " years old.");
}
};
// Call the greet method
person.greet();