Home > Net >  Javascript closures in generat ID
Javascript closures in generat ID

Time:06-16

var generateID=function() {
    var prefix="uid-";
    var count=0;

    return function(){
        count =1;
        console.log(prefix count)
    }
}
var create = generateID();

console.log(create());
console.log(create());
console.log(create());

Expected output: uid-1 uid-2 uid-3

Help me in undefined error part in output.

CodePudding user response:

create doesn't return anything so if you console.log(create()) it prints undefined

var generateID=function() {
    var prefix="uid-";
    var count=0;

    return function(){
        count =1;
        console.log(prefix count)
    }
}
var create = generateID();

create()
create()
create()

var generateID2 = function() {
    var prefix="uid-";
    var count=0;

    return function(){
        count =1;
        return prefix count
    }
}
var create2 = generateID2();

console.log(create2())
console.log(create2())
console.log(create2())

CodePudding user response:

The create function does not return any value. This is why console.log(create()); calls log undefined.

return function() {
    count =1;
    return prefix count;
}
  • Related