0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Functions returning functions

Last updated at Posted at 2019-12-13
function interviewQuestion(job){
  if(job === 'designer'){
    return function(name){
      console.log(name + ', can you please explain what UX design is?');
    }
  } else if (job === 'teacher'){
    return function(name){
      console.log('What subject do you teach, ' + name + '?');
    }
  } else {
    return function(name){
      console.log('What do you do?');
    }
  }
}

// A function is assigned to teacherQuestion since interviewQuestion returns a function
var teacherQuestion = interviewQuestion('teacher');
teacherQuestion('John'); // 'What subject do you teach, John?'
interviewQuestions('teacher')('John') // 'What subject do you teach, John?'

This is possible because functions are always first class functions. The functions are infact an object.

A language is said to have first class functions when the functions can be treated like any other variable. These first class functions can be assgined to a variable, passed to a function as an argument or be returned from a function.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?