Function Basics — JS Technical Interview Questions & Answers
Declaring, calling and returning values from functions.
Function Basics
- Declaring, calling and returning values from functions.
- function add(a, b) { return a + b; } add(2, 3) is 5. If you forget return, you get undefined. Arrow: const add = (a, b) => a + b;
- Parameters are inputs. Arguments are the values you pass. Default: function hi(name = 'student').
- Trap: missing return. Trap: this inside an arrow vs a method — learn that with DOM later.
Technical Interview Tip: function add(a,b){ return a+b } Don’t forget return.
Code Examples for Function Basics
Function Basics — working example
function greet(name = "friend") {
return "Hi " + name;
}
const shout = function (msg) {
return msg.toUpperCase();
};
(function () {
console.log("IIFE ran");
})();
function mapNums(nums, fn) {
const out = [];
for (const n of nums) out.push(fn(n));
return out;
}
console.log(greet("Ada"), shout("js"));
console.log(mapNums([1, 2], (n) => n * 2));
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(4));Function Basics — functions take parameters, can be expressions/IIFEs/callbacks, and recurse with a base case. Pure functions avoid side effects.
How to Explain Function Basics to an Interviewer
What if you omit return?
The function gives undefined