Is it possible to run a function without giving it an object?

Viewed 58

I'm wondering if there are any functions, that run a function.

For example if the simplest function I could write is something like:

function(){
  print("hello world")
}

However as far as I know the only way to "run" this function is to run something like:

my_fun <- function(){
  print("hello world")
}

my_fun()

Is there a way to achieve this result without giving the function an object? Intuitively I think this is not too different than what %>% does, but I'm having trouble thinking about how to do this. Is there a function that I could pipe into to run this function without giving it it's own object?

2 Answers

Do can IIFE (Immediately-Invoked Function Expression). It´s a quite popular pattern in JS.

(function() {print("hello world")})()

I think you're just asking if you can run a function without explicitly naming it. Sure.

(function(){
  print("hello world")
})()

Wrap the anonymous function in parens and then 'call' it with a pair of parens as well.

> (function(){
+   print("hello world")
+ })()
[1] "hello world"
Related