Search code examples
javascriptvariables

Why does JS automatically execute variables?


I'm just learning javascript, and I'm unsure of why when I assign functions to variables it gets executed automatically.

I was under the impression that assigning a variable is essentially just like putting something into a container.

Like, why does this automatically return 'hello' in the console?

let a = console.log('hello')

I would expect the console to only return 'hello' if I called a.

Or why does this automatically return a prompt:

let answer = parseInt(prompt("Please enter the number you would like to FizzBuzz up to: "));

I would expect it to only return the prompt when I call the variable answer.

How would I assign a function to a variable WITHOUT it automatically getting executed?


Solution

  • Whenever you put parentheses after the function (either parentheses with parameters inside them or empty parentheses), you are telling it to execute. What is then being assigned to the variable is the result of the function execution.

    It's possible to assign the function itself to a variable without executing it, like this:

    a = console.log
    

    but there are some caveats if you want to provide the parameters beforehand, or if the function internally uses the this keyword.

    The simplest way is probably to put it inside another function.

    // not executed yet
    let a = function() {
      console.log('hello');
    }
    
    // execute it
    a()
    

    Or with a shorter syntax, as mentioned in the comments:

    // not executed yet
    let a = () => console.log('hello');
    
    // execute it
    a()