The code inside a function does not run when the function is defined. It runs when something invokes it. "Invoke", "call", "execute", "run", and "call upon" all mean the same thing. This lesson covers the ways a function gets run and exactly what happens when it does.
A function can be invoked:
The () after a function name is the operator that actually runs it. Without them, you are just referring to the function itself:
function toCelsius(fahrenheit) {
return (5 / 9) * (fahrenheit - 32);
}
let value = toCelsius(77); // the RESULT of calling it
let fn = toCelsius; // the function ITSELF
console.log(value);
console.log(fn);
(Chrome shows a function with a little ƒ in front.) toCelsius refers to the function; toCelsius(77) refers to its result.
() is a very common bug, and nothing errors. let t = getTime; stores the whole function, not the time. If you see the function's source code printed where you expected a value, look for missing parentheses.
Calling a function runs it, but if it returns a value, you still have to do something with that value to see it:
function sayHello() {
return "Hello World";
}
sayHello(); // runs, but the result is thrown away
let greeting = sayHello(); // store it
console.log(sayHello()); // or display it
Only one line printed. The first call ran perfectly well; nobody looked at the answer.
return (or the end), control jumps back to where it was calledfunction add(a, b) {
console.log(" inside add");
return a + b;
}
console.log("before");
let result = add(2, 3);
console.log("after, result is " + result);
You can call the same function as often as you need. Each call is independent: the function starts fresh every time, with new local variables.
function rollDie() {
return Math.floor(Math.random() * 6) + 1;
}
for (let i = 0; i < 3; i++) {
console.log(rollDie());
}
Functions written with the function keyword can even be called from lines above their declaration. JavaScript reads all function declarations before running anything. This is called hoisting:
console.log(triple(4)); // works!
function triple(n) {
return n * 3;
}
function keyword. Functions stored in let or const variables (Function Expressions) must be defined before they are called, just like any other let or const.
A function that belongs to an object is called a method. You call it with a dot. You have been doing this for a while:
console.log("hi".toUpperCase()); // a method built into strings
console.log(Math.max(3, 9, 2)); // a method on the Math object
Even console.log is a method: log, belonging to the console object. You will write your own methods in the Objects section.
So far everything has printed to the console. To show a function's result on the page, put it into an HTML element with innerHTML:
<p id="demo"></p>
<script>
function sayHello() {
return "Hello World";
}
document.getElementById("demo").innerHTML = sayHello();
</script>
The paragraph with id="demo" now shows "Hello World". (document.getElementById("demo") finds the element whose id is "demo", and setting its innerHTML replaces what is inside it.)
Most functions on real web pages run because the user did something, like clicking. The simplest way is an onclick attribute right on the button:
<p id="demo"></p>
<button onclick="showHello()">Click Me</button>
<script>
function showHello() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
The function sits unused until the button is clicked; then the browser calls it. The more modern way is addEventListener, where you hand the browser the function itself to call later:
const btn = document.getElementById("myButton");
btn.addEventListener("click", showHello); // no () here!
addEventListener("click", showHello()), with parentheses, runs the function immediately, once, when the page loads, and hands the browser its return value instead of the function. Pass the function (no parentheses) so the browser can call it when the click happens. (In an onclick="..." attribute it is the opposite: there you do write the parentheses, because the attribute holds code to run.)
A function can also invoke itself the moment it is defined. Wrap the function in parentheses, then add () after it:
(function () {
console.log("I ran myself");
})();
This is called an IIFE (Immediately Invoked Function Expression, pronounced "iffy"). It has no name and runs exactly once. It was very common in older code as a way to keep variables private; you will see it again in the advanced Functions lessons.
sayHello does not run the function; sayHello() doesundefined)What is the difference between sayHello and sayHello()?
sayHello refers to the function itself, without running it. sayHello() runs the function and gives you its result.What does this log, in order?
function step() {
console.log("B");
return "C";
}
console.log("A");
let x = step();
console.log(x);
A, B, C. The flow pauses at step(), runs the body (logging B), returns "C" into x, then continues.You want showMenu to run when a button is clicked. Which line is right?
btn.addEventListener("click", showMenu());btn.addEventListener("click", showMenu);btn.addEventListener("click", "showMenu");btn.addEventListener(showMenu, "click");new Date()