DEV Community

programmerabhi
programmerabhi

Posted on

function in an array , how to declare and access?

var arr = [ function fun(){ console.log("this is a funtion ");} ];
console.log(arr0 );
output:

"this is a funtion "
undefined

To get the output "this is a function", how to access array.
And do not appear undefined in output

Top comments (3)

Collapse
 
jackydev profile image
JacKyDev

var arr = [ function(){ return "this is a funtion"} ];
console.log(arr0 );

Output Console:
this is a funtion

Collapse
 
programmerabhi profile image
programmerabhi

You mean that only the anonymous function can be placed in the array.

Collapse
 
jackydev profile image
JacKyDev

You have more ways to handle functions in a Array. Any Function can include Into a Array. Array allowed all Types. Best way is to Use a pattern principel. Its a Use Case:

Want Array to handle manipulations of Data before Service called.
I Use Class Syntax for faster Sample:
Class Ainterceptor {
intercept(data){ // Do your Manipulation and Return Data }
}

Class Service{
constructor(interceptors: [new AInterceptor()])}
setUser(data){
interceptors.forEach(i => data = i.intercept(data)
saveUser(data)
}
}