Interview Questions Answers.ORG
Interviewer And Interviewee Guide
Interviews
Quizzes
Home
Quizzes
Interviews Scripting language Interviews:AngularJSAngularJS DeveloperChrome FrameDojoExpert Developer JavaScriptExpert JavaScript DeveloperExt CoreEXT-GWTExt-JSFront End Developer (AngularJS)JQuery DeveloperjQuery MobileJQuery ProgrammerJQuery UIMooToolsPrototype FrameworkQooxdooScriptingSencha TouchSizzle Selector EngineSWFObjectWeb Font LoaderXMLHttpRequest
Copyright © 2018. All Rights Reserved
Expert Developer JavaScript Interview Question:
Explain JavaScript closures by example?
Submitted by: Administrator► The closure is a local variable of a function which remains alive after the function has returned.
► Closure combines a function with a local variable available at the time of creating closure.
► For example :
function wish(msg)
{
console.log(msg);
}
function greeting(name, occasion)
{
return name + ", Happy " + occasion;
}
var message = greeting ("Arpit", "Birthday");
// Pass it explicitly to wish
wish(message);
► By using closure we can simplify above code.
function greeting (name, occasion)
{
var msg = name + ", Happy " + occasion;
return function wish()
{
console.log(msg);
};
}
// create the closure
var wisharpit = greeting ("Arpit", "Birthday");
// use the closure
wisharpit ();
► Here wish function is nested within the greeting, so closure can access the local variable of greeting which are name, occasion and msg.
Submitted by:
► Closure combines a function with a local variable available at the time of creating closure.
► For example :
function wish(msg)
{
console.log(msg);
}
function greeting(name, occasion)
{
return name + ", Happy " + occasion;
}
var message = greeting ("Arpit", "Birthday");
// Pass it explicitly to wish
wish(message);
► By using closure we can simplify above code.
function greeting (name, occasion)
{
var msg = name + ", Happy " + occasion;
return function wish()
{
console.log(msg);
};
}
// create the closure
var wisharpit = greeting ("Arpit", "Birthday");
// use the closure
wisharpit ();
► Here wish function is nested within the greeting, so closure can access the local variable of greeting which are name, occasion and msg.
Submitted by:
Copyright 2007-2024 by Interview Questions Answers .ORG All Rights Reserved.
https://InterviewQuestionsAnswers.ORG.
https://InterviewQuestionsAnswers.ORG.