DEV Community

Robert Mion
Robert Mion

Posted on

You don't know the first thing about functions in JavaScript

The point of this article is to give you an 'A-ha!' moment about functions in JavaScript.

This function returns the sum of two numbers

function sum(a, b) {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

To call - or invoke - this function, you'd write this:

sum(2, 3) // returns 5
Enter fullscreen mode Exit fullscreen mode

How you might imagine this function works is:

function sum(2, 3) {
  return 2 + 3;
}
Enter fullscreen mode Exit fullscreen mode

However, two additional steps happen:

function sum(a, b) {
  let a = 2;
  let b = 3;
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

What I hope this walkthrough showed you:

  • When you define a function, you declare the expected parameters and their respective unique labels (e.g. a and b)
  • When called, you explicitly specify the arguments you want the function to use as its parameters
  • When evaluated, the function assigns each value passed as argument (or a copy of that value) to its parameters
  • The function then proceeds to evaluate its body using the values passed when called, aliased as the labels you defined when the program compiled

This tutorial was short, clear, and fun. I made a game just like it to help you teach yourself frontend

Fix a function!

Top comments (4)

Collapse
 
pentacular profile image
pentacular • Edited

Except that it probably doesn't actually do that.

The key phrase here is, "as though".

You also left out 'this', and 'arguments' which are important for understanding functions and parameters in Javascript.

What's also missing is talking about why it is significant that the function executes as though parameters were variables assigned with argument values.

Which is kind of disappointing in an article titled "You don't know the first thing about functions in JavaScript". :)

Collapse
 
bamideleandrew profile image
Andrew Bamidele • Edited

You know you could pass them directly in the parameters and reduce the number of lines and possibly prevent declaring this values twice

Collapse
 
vmuthabuku profile image
vincent muthabuku • Edited

I did not know that, nice one

Collapse
 
cheyennels profile image
Cheyenne Lee Smith

Fun little game, thanks for sharing!