Function object / NFE
Advanced Functions: Function object / NFE
In JavaScript, what type of data type is a function?
View Answer:
Can you explain why are functions Objects in JavaScript?
View Answer:
// Functions are callable objects
function sayHi(myName) {
console.log('Hi, ' + myName);
}
sayHi('JavaScript'); // Call sayHi() returns "Hi"
console.log(sayHi.name); // returns sayHi, using built-in name method.
console.log(sayHi.length); // length = 1, using build length method
What kind of naming logic does JavaScript use for functions?
View Answer:
// Regular Function
function sayHi() {
console.log('Hi');
}
console.log(sayHi.name); // sayHi
// Anonymous Function Expression
let sayHi = function () {
console.log('Hi');
};
console.log(sayHi.name); // sayHi (there's a name!)
// Named Function Expression
let sayHi = function saySomething() {
console.log('Hi');
};
console.log(sayHi.name); // saySomething (there's a name!)
// Object methods have names too:
let user = {
sayHi() {
// method
// ...
},
sayBye: function () {
// method
// ...
},
};
console.log(user.sayHi.name); // sayHi
console.log(user.sayBye.name); // sayBye
You should not confuse this question with a question about how to name a function.
What does the function length property do?
View Answer:
function f1(a) {}
function f2(a, b) {}
function many(a, b, ...more) {}
console.log(f1.length); // 1
console.log(f2.length); // 2
console.log(many.length); // 2, rest parameter not counted
Is a function property considered a variable in JavaScript?
View Answer:
What does NFE stand for in JavaScript?
View Answer:
var greet = function greeting(name) {
return "Hello, " + name + "!";
};
console.log(greet("Alice")); // Outputs: Hello, Alice!
Can you explain what a named function expression is in JavaScript?
View Answer:
let sayHi = function func(who) {
if (who) {
console.log(`Hello, ${who}`);
} else {
func('Guest'); // use func to re-call itself
}
};
sayHi(); // Hello, Guest
// But this won't work:
func(); // Error, func is not defined (not visible outside of the function)
What exactly is the purpose of a named function expression (NFE)?
View Answer:
// Named Function Expression
let sayHi = function func(who) {
if (who) {
console.log(`Hello, ${who}`);
} else {
func('Guest'); // Now all fine
}
};
let welcome = sayHi;
sayHi = null;
welcome(); // Hello, Guest (nested call works)
// Regular Function Declaration
function sayHi(name) {
console.log('Hello, ' + name);
}
let welcome = sayHi;
sayHi = null;
welcome('JavaScript'); // Hello, JavaScript
You should note that a regular function declaration can be used to achieve the same result.
How does a named function expression differ from a regular function expression?
View Answer:
What are the benefits of using named function expressions over anonymous function expressions?
View Answer:
// Example 1: Improved stack traces
var calculateSum = function sum(a, b) {
if (a + b > 10) {
throw new Error("Sum exceeds limit");
}
return a + b;
};
try {
console.log(calculateSum(5, 8));
console.log(calculateSum(7, 6));
} catch (error) {
console.log(error.stack);
}
In this example, the named function expression sum
is assigned to the variable calculateSum
. If the sum of the two numbers exceeds 10, an error is thrown. When an error occurs, the stack trace will include the function name (sum
) in the output, making it clear which function caused the error. This improves the debugging process by providing more informative stack traces.
// Example 2: Self-referencing for recursion
var factorial = function findFactorial(n) {
if (n === 0) {
return 1;
}
return n * findFactorial(n - 1);
};
console.log(factorial(5)); // Outputs: 120
In this example, the named function expression findFactorial
is assigned to the variable factorial
. The function recursively calculates the factorial of a number. By referencing itself using its own name, it can call itself repeatedly until the base case (n === 0
) is reached. The use of a named function expression facilitates recursion.
These examples demonstrate how named function expressions can provide more informative stack traces, enable self-referencing for recursion, and enhance the readability and self-documentation of the code.
Can you explain the concept of function hoisting?
View Answer:
hoistedFunction(); // Outputs: "This function has been hoisted."
function hoistedFunction() {
console.log("This function has been hoisted.");
}
What are the two-phases of function hoisting in JavaScript?
View Answer:
How do named function expressions affect the readability and maintainability of the code?
View Answer:
Can you explain the difference between a function's name property and its identifier when using named function expressions?
View Answer:
var greet = function greeting(name) {
return "Hello, " + name + "!";
};
console.log(greet.name); // Outputs the name of the named function: "greeting"
console.log(greet("Alice")); // Outputs: "Hello, Alice!"
What is the behavior of the 'this' keyword inside a named function expression?
View Answer:
var person = {
name: "Alice",
greet: function greeting() {
console.log("Hello, " + this.name + "!");
}
};
person.greet(); // Outputs: "Hello, Alice!"
What are some common use cases for named function expressions?
View Answer:
Recursion: Named Function Expression
var factorial = function findFactorial(n) {
if (n === 0) {
return 1;
}
return n * findFactorial(n - 1);
};
console.log(factorial(5)); // Outputs: 120
What is event handling with self-unbinding in relation to JavaScript function expressions?
View Answer:
var button = document.getElementById('myButton');
button.addEventListener('click', function handleClick() {
console.log('Button clicked!');
// Remove this event listener after it's executed
button.removeEventListener('click', handleClick); // <- self-unbinding
});
Are there any performance implications when using named function expressions as opposed to anonymous function expressions?
View Answer:
How does the behavior of named function expressions change when used with arrow functions?
View Answer:
// Regular Named Function Expression
var regularFunction = function namedFunction() {
console.log(namedFunction.name); // Output: namedFunction
}
regularFunction();
// Arrow Function
var arrowFunction = () => {
console.log(arrowFunction.name); // Output: arrowFunction
}
arrowFunction();
// Named Arrow Function (Not possible in JavaScript)
var namedArrowFunction = () => {
console.log(namedArrowFunction.name); // Error: namedArrowFunction is not defined
}
namedArrowFunction();
In the above example, the named function expression logs its name as expected. The unnamed arrow function logs its variable name as the function name. However, trying to give an arrow function a name (like a named function expression) results in an error because arrow functions can't be named in the same way.