Part 14: Closure JS Interview exercise 👩🏻‍🏫

Swati Redhu
2 min readAug 7, 2023

--

Get ready for an exciting adventure into the world of JavaScript closures! By mastering closures through simple exercises, you’ll level up your JavaScript skills and discover their true potential. So, let’s dive in and explore closures together!

If you don not have understanding of Closures, I highly recommend to go through below articles first.

- Part 11: Closures in JS 🤷🏻‍♀️

- Part 12: setTimeout + Closures Interview Questions 🤓

-Part 13: Closure JS Interview Questions 🤯

Let’s get started.

function outerFunction() {
var outerVariable = "Hi, ";
function innerFunction(name) {
console.log(outerVariable + name); // What is logged?
}
return innerFunction;
}

var inner = outerFunction();
inner("Closure");
function outer() {
var x = 10;
function inner() {
console.log(x); // What is logged?
}
return inner;
}
var innerFunc = outer();
innerFunc();
function outer() {
var x = 10;
function inner() {
console.log(x); // What is logged?
}
var x = 20;
return inner;
}
var innerFunc = outer();
innerFunc();
function outer() {
var x = 10;
function inner() {
var y = 12;
console.log(x+y); // What is logged?
}
return inner;
}
var innerFunc = outer();
innerFunc();
var a = 1; 
function b() {
a = 10;
return;
function a() {}
}
b();
console.log(a); // What is logged?

function test() {
console.log(a); // What is logged?
console.log(foo()); // What is logged?

var a = 1;
function foo() {
return 2;
}
}

test();
var a = 1; 

function someFunction(number) {
function otherFunction(input) {
return a;
}

a = 5;

return otherFunction;
}

var firstResult = someFunction(19); // What is firstResult?
var result = firstResult(12); // What is result?
var fullname = 'Daisy Doe';
var obj = {
fullname: 'Vera Singh',
prop: {
fullname: 'Amar Akbar Anthony',
getFullname: function() {
return this.fullname;
}
}
};

console.log(obj.prop.getFullname());

var test = obj.prop.getFullname;

console.log(test()); // What is logged?

For practise, visit the github exercise repo

I value your feedback! If you found this article helpful in unraveling the mysteries of closures and enhancing your JavaScript knowledge, I’d love to hear from you. Feel free to share your thoughts and let me know if this content has made a positive impact on your coding journey. Your appreciation fuels my commitment to creating valuable content for my readers!

⭐️ Happy Coding. ⭐️

Hopefully, you learned something today! Before you go:

🚀👉 Clear your JS basics and find an amazing job

--

--

Swati Redhu

A developer attempting to learn the fundamentals and putting it here so that others could benefit from it.