Function Expressions - JavaScript Questions
JavaScript Fundamentals: Function Expressions
Can a function be classified as a function, an object, or both?
View Answer:
Interview Response: In JavaScript, a function is both a function and an object. It can be called and passed around like any other object.
Technical Response: In JavaScript, functions are first-class objects because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions get called. In simple terms, they are Function objects.
What is the purpose of using a function expression?
View Answer:
Interview Response: A function expression is used to assign a function to a variable, allowing for encapsulation and reuse of the function.
Code Example:
// Function expression
const addNumbers = function(a, b) {
return a + b;
};
// Using the function expression
const result = addNumbers(5, 7);
console.log(result); // Output: 12
How do you declare a named function expression?
View Answer:
Interview Response: To declare a named function expression in JavaScript, assign a function to a variable using the function keyword followed by a name.
Code Example:
// Named Function Expression
const factorial = function factorial(n) {
if (n === 0 || n === 1) {
return 1;
} else {
return n * factorial(n - 1);
}
};
// Using the named function expression
const result = factorial(5);
console.log(result); // Output: 120
How do you declare an anonymous function expression?
View Answer:
Interview Response: You can declare an anonymous function expression by assigning a function to a variable without giving the function a name.
Code Example:
// Anonymous Function expression
const addNumbers = function(a, b) {
return a + b;
};
// Using the Anonymous function expression
const result = addNumbers(5, 7);
console.log(result); // Output: 12
What distinguishes using a function declaration from a function expression?
View Answer:
Interview Response: A function declaration is a statement that declares a function in the current scope, while a function expression defines a function as a value assigned to a variable or property.
Technical Response: Function declarations load before any code executes, while Function expressions load only when the interpreter passes the right side of the expression. A global Function Declaration is visible in the whole script, no matter where.
Function Declarations are functions declared as a separate statement in the main code flow. Function Expressions are functions created inside an expression or another syntax construct.
Function Declarations are functions declared as a separate statement in the main code flow. Function Expressions are functions created inside an expression or another syntax construct.
Code Example: Function Declaration
sayHi('John'); // Hello, John
function sayHi(name) {
console.log(`Hello, ${name}`);
}
Code Example: Function Expression
sayHi('John'); // error!
let sayHi = function (name) {
// (*) no magic any more
console.log(`Hello, ${name}`);
};
In this example, the function declaration is hoisted to the top of it's scope, while the function expression is not and results in an error.
How do function declarations and function expressions differ in terms of page loading behavior in JavaScript?
View Answer:
Interview Response: Function declarations are loaded before any code is executed, while function expressions are only loaded when their defining line is reached.
What is hoisting, and how does it affect function declarations?
View Answer:
Interview Response: Hoisting is the default behavior of moving all hoist-able declarations to the top of the current scope.
Technical Response: Hoisting refers to the availability of function declarations and variables (with var) “at the top” of your code instead of only after they get created. The function objects are initialized immediately and available everywhere in your code.
What is the difference between using a function declaration versus a function expression?
View Answer:
Interview Response: You can use function declarations to create a function in the global scope. A function expression limits where a function gets used, keeps your global scope light, and maintains a clean syntax.
Technical Response: You should use function declarations when you want to create a function on the global scope and make it available throughout your code. Use function expressions to limit where the function is available, keep your global scope light, and maintain clean syntax.
What is the difference between a named and anonymous function expression?
View Answer:
Interview Response: Named function expressions have identifiers, providing benefits like recursion and improved debugging through clear naming. Anonymous function expressions lack names, offering shorter, self-contained code and preventing unintended name conflicts in the scope.
Describe a function expression’s code structure and behavior?
View Answer:
Interview Response: Function expressions are anonymous or named functions assigned to variables. They accept parameters, execute code within a body, and are invoked upon calling the variable. They also enable modularity and support functional programming paradigms.
Technical Response: The function expression structure explicitly creates and assigns a variable to the function. A function name can get omitted, making it an anonymous function. If a name is assigned, the name gets localized to the function. The function expression can also assign parameters, if necessary. The expression body, like regular functions, encloses the actions that the function performs.
Code Example: Function Expression
const getRectArea = function (width, height) {
return width * height;
};
console.log(getRectArea(3, 4)); // returns 12
Are functions values in JavaScript? If yes, can you explain?
View Answer:
Interview Response: Yes, functions can be considered or termed as values in JavaScript, because they can be assigned to variables, passed as arguments, and returned from other functions.
Code Example:
// Assigning function to a variable
let greet = function() {
console.log("Hello World");
};
// Storing function in data structure
let arr = [function() { return "Hello Array"; }];
console.log(arr[0]()); // Output: Hello Array
// Passing function as an argument
function executeFunction(func) {
console.log(func());
}
executeFunction(greet);
// Returning a function
function createAdder(x) {
return function(y) {
return x + y;
};
}
let add5 = createAdder(5);
console.log(add5(3)); // Output: 8
Why is there a semicolon at the end of a function expression?
View Answer:
Interview Response: A function expression uses a semi-colon because we declare it by assignment, and all assignments must use a semi-colon to terminate the statement.
Technical Response: A Function Expression gets used inside a statement as a value, and it is not a code block but rather an assignment. The semicolon ( ; ) is recommended at the end of statements, no matter what the value is. So, the semicolon is not related to the Function Expression itself, and it just terminates the statement.
Code Example:
let sayHi = function () {
// ...
}; // <-- semicolon here closes out the statement.
note
There’s no need for a semicolon ( ; ) at the end of code blocks and syntax structures that use them like if { ... }, for { }, function f { } etc.
What is a callback function in JavaScript?
View Answer:
Interview Response: A callback function gets passed into another function as an argument; it gets invoked inside the outer function to complete a routine or action.
Code Example: Callback Function
function greeting(name) {
console.log('Hello ' + name);
}
function processUserInput(callback) {
var name = prompt('Please enter your name.');
callback(name);
}
processUserInput(greeting); // function is calling the greeting.
Can a function declaration be removed from the global scope, or would a function expression be better suited for managing the intended tasks?
View Answer:
Interview Response: Function declarations cannot be isolated from the global scope by default. However, using function expressions within an Immediately Invoked Function Expression (IIFE), a module, or inside block-scoped constructs provides better encapsulation, scope control, and prevents global scope pollution, offering a more suitable approach.
Technical Response: Yes, in strict mode, when a Function Declaration is within a code block, it is visible everywhere inside that block. But not outside of it. CAUTION: This can lead to erroneous outcomes.
A function expression is a better alternative to implementing code in this fashion because a function expression can be initialized and invoked in the global scope regardless of where the function statement resides. A function declaration does not have the benefit of that feature.
A function expression is a better alternative to implementing code in this fashion because a function expression can be initialized and invoked in the global scope regardless of where the function statement resides. A function declaration does not have the benefit of that feature.
Code Example: Erroneous Use
let age = prompt('What is your age?', 18);
// conditionally declare a function
if (age < 18) {
function welcome() {
console.log('Hello!');
}
} else {
function welcome() {
console.log('Greetings!');
}
}
// ...use it later
welcome(); // Error: welcome is not defined
Code Example: Proper Implementation
let age = prompt('What is your age?', 18);
let welcome;
if (age < 18) {
welcome = function () {
console.log('Hello!');
};
} else {
welcome = function () {
console.log('Greetings!');
};
}
welcome(); // ok now
Can a function declaration be called earlier than it is defined?
View Answer:
Interview Response: Yes, a Function Declaration is visible in the whole script, no matter where it is. As soon as it initializes, it is available.
Technical Response: Yes, a global Function Declaration is visible in the whole script, no matter where it is. When JavaScript prepares to run the script, it first looks for global Function Declarations and creates the functions. We can think of it as an “initialization stage”. And after all Function Declarations are processed, the code is executed. So, it has access to these functions. Function expressions do not have this capability, which is an important factor when choosing between the two.
Code Example: Function Declaration, it works…
sayHi('John'); // Function invoked before it is defined: returns Hello, John.
function sayHi(name) {
console.log(`Hello, ${name}`);
}
Code Example: Function Expression, ah man we broke it…
sayHi('John'); // error: we called it too early.
let sayHi = function (name) {
// no magic any more
console.log(`Hello, ${name}`);
};
Can you call a function expression before it is defined?
View Answer:
Interview Response: No, you cannot call a function expression before it's defined, as they are not hoisted like function declarations, resulting in a reference error if attempted.
When should you use a Function Declaration vs. a Function Expression?
View Answer:
Interview Response: We should consider a function declaration syntax first because it gives us more freedom in organizing our code, and we can call it when it initializes. We use a function expression when a function declaration does not suit our needs or for encapsulation.
Technical Response: When we need to declare a function, the first thing to examine is the Function Declaration syntax. It allows us to structure our code more freely because we may call such functions before they are declared.
That's also better for readability because function f(...); is more straightforward to find in the code than let f = function(...);. Function declarations are more visually appealing.
...However, if a Function Declaration is not appropriate for whatever reason, or if a conditional declaration is required, a Function Expression should be utilized.
That's also better for readability because function f(...); is more straightforward to find in the code than let f = function(...);. Function declarations are more visually appealing.
...However, if a Function Declaration is not appropriate for whatever reason, or if a conditional declaration is required, a Function Expression should be utilized.
Can you pass a function expression as an argument to another function?
View Answer:
Interview Response: In JavaScript, you can pass a function expression as an argument to another function, enabling higher-order functions and promoting functional programming concepts such as callbacks and event handling.
Code Example:
Here's an example that demonstrates passing a function expression as an argument to another function.
function calculate(operation, a, b) {
return operation(a, b);
}
let add = function(x, y) {
return x + y;
};
let multiply = function(x, y) {
return x * y;
};
console.log(calculate(add, 5, 3)); // Output: 8
console.log(calculate(multiply, 5, 3)); // Output: 15
In the example above, the calculate
function takes an operation
parameter, which is expected to be a function. We pass different function expressions (add
and multiply
) as the operation
argument when calling calculate
, allowing it to perform addition and multiplication accordingly.
What is the scope of a function expression?
View Answer:
Interview Response: The scope of a function expression is determined by where it is defined, which can be in the global scope or inside another function.
How do you create a self-invoking function expression?
View Answer:
Interview Response: You can create a self-invoking function expression by wrapping a function expression in parentheses and immediately invoking it. Using self-invoking function expressions, also known as Immediately Invoked Function Expressions (IIFE), is a common approach for creating isolated scopes, preventing global scope pollution, and executing one-time setup tasks.
Code Example:
(function() {
let myFunction = function() {
console.log('Hello, JavaScript!')
}
myFunction(); // Hello, JavaScript!
})();
What is the value of the 'this' keyword inside a function expression?
View Answer:
Interview Response: The value of the 'this' keyword inside a function expression depends on how the function is called. If the function is called as a method of an object, 'this' refers to the object. Otherwise, 'this' refers to the global object or undefined, it all depends on the mode the function is being called.
Code Example:
const obj = {
language: 'JavaScript',
sayHello: function() {
console.log(`Hello, ${this.language}!`);
}
};
obj.sayHello(); // Output: Hello, JavaScript!
const greeting = obj.sayHello;
greeting(); // Output: Hello, undefined! (or the global object, depending on strict mode)