loading...

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

rmion profile image Robert Mion ・1 min read

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;
}

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

sum(2, 3) // returns 5

How you might imagine this function works is:

function sum(2, 3) {
  return 2 + 3;
}

However, two additional steps happen:

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

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!

Posted on by:

rmion profile

Robert Mion

@rmion

I design. I write. And I code. ....and I mentor, tutor and coach junior developers!

Discussion

markdown guide
 

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". :)

 

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

 
 

Fun little game, thanks for sharing!