skip to Main Content

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?

2

Answers


  1. Whenever you put parentheses next to the function name (with or without parameters inside the parentheses), you are telling it to execute. What is being assigned to the variable is the result of the function execution.

    There are several ways in JavaScript to suspend the execution of a function until a later stage, but the mentally simplest way is probably to put it inside another function.

    // not executed yet
    let a = function() {
      console.log('hello');
    }
    
    // execute it
    a()
    
    Login or Signup to reply.
  2. You can assign a function to a object like this:

    var obj = {};
    obj.test = function() {
      return "Hello";
    }
    document.querySelector("button").addEventListener("click", function () 
    {   
      console.log(obj.test())
    });
    <Button>Click</Button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search