create account

The JavaScript Journey #7 - What are Functions? by adnanrahic

View this thread on: hive.blogpeakd.comecency.com
· @adnanrahic ·
$88.17
The JavaScript Journey #7 - What are Functions?
![Space Man](https://raw.githubusercontent.com/adnanrahic/cdn/master/tjj-7/1-sky-earth-space-working.jpg)

I guess if you've ever watched any space sci-fi movie ever you'll be familiar with what functions are. In space travel, all the heroes need to go to cryo-sleep in order to travel the vast distances between stars. How does any of this make any sense, you ask? I'm not losing my mind, promise! View functions just like the space heroes exploring galaxies. Functions freeze code in order to use it at a later time. This frozen code can be reused as many times as you wish, without the need to write it again and again. 

## Dry Theory
First and foremost let's go through some dry theory. Before being able to understand the logic behind functions we need to hear the official definitions.

### Wrapping code
Any function is a piece of code or program wrapped in a value. These values can be executed in order to run the wrapped program. Executing such a value, a function, is called **invoking**, **calling**, or **applying** it. All of these are heavy words. In the rest of the lesson, we'll stick to **calling** to keep it simple and concise. So how do we tell our program to call a function? Easy, we just put parentheses after the value which holds the function.

![Call a function](https://raw.githubusercontent.com/adnanrahic/cdn/master/tjj-7/2-pexels-photo%20(1).jpg)

```javascript
alert('Hello Steemit!');
```
###

Here we see a built in function that will create an alert window in your browser with the text *Hello Steemit!*. But of more use to us is the ```console.log()``` function.

```javascript
console.log('Hello Steemit!');
```
###
It'll output the value given to it back to the console.

## Return to sender
The behavior above is all classified as side effects. Functions are not that simple. They can also produce new values! Which is awesome, because you don't need side effects to be useful. Let's take another built in function in JavaScript, ```Math.max```.

```javascript
var maxNumber = Math.max(2, 4);
console.log(maxNumber); 
// 4
```
###

![Return To Sender](https://raw.githubusercontent.com/adnanrahic/cdn/master/tjj-7/3-14155209556_c46e13cd15_b.jpg)

You see? The function has returned a value and assigned it to the variable ```maxNumber```. This means the function produced a value. Having this in mind, everything that produces a value is an expression. So it can be used in combination with other expressions.

```javascript
Math.max(2, 4) + 6 > 5 || 1 == Math.min(1, 7)
// true
```
###

## Bread and butter
Functions are the core of programming in JavaScript. They are used to structure larger programs and to reduce repetition. This means we can create subprograms in our larger program. Remember, above I mentioned that functions freeze code to be used later. This can be viewed as a subprogram. And to call upon it at a later time we give it a name. Meaning every function has a name, and that it is isolated from another subprogram.

Want to create a function? I bet you do.

## Function definition
A function definition is just like a variable definition. The value of the function is assigned to the variable. 

```javascript
var square = function(x) {
  return x * x;
};
var result = square(12);
console.log(result);
// → 144
```
###

Functions are created with the ```function``` keyword. Every function has a body and parameters. The body is wrapped in curly braces (```{}```), and contains all the expression that will be executed when the function is called. Functions can have as many parameters as the programmer wants or none at all. Here are two examples.

```javascript
// No parameters
var sayHello = function() {
  console.log("Hello!");
};
sayHello();
// → Pling!

// Multiple Parameters
var addTwoNumbers = function(x, y) {
  return x + y;
};
var result = addTwoNumbers(5, 1);
console.log(result);
// → 6!
```
###

## Backtracking
Let's take a step back and focus on ```return``` statements a bit more. I mentioned it determines what value will be returned from the function execution. But I didn't mention that the code in the function stops executing when it reaches a return statement. All code underneath a return will never be executed! 

```javascript
var addTwoNumbers = function(x, y) {
  return x + y;
  console.log('This will never be reached!');
};
var result = addTwoNumbers(1, 5);
console.log(result);
// the console.log() in the function will never be called!
// → 6!
```
###

The code that called the function will receive the value returned from it. In the example above that means the variable ```result``` will be assigned the value ```6```. But, what if we don't have a return statement in a function? What happens then!? Remember our friend ```undefined```? Every function that does not have a return statement will return ```undefined```. Take a look.

```javascript
var addTwoNumbers = function(x, y) {
  console.log(x + y);
};
var result = addTwoNumbers(1, 5);
console.log(result);
// → 6
// → undefined
```

## Summary
Today you have learned what functions are and their basic use case. You now understand that they are used to structure larger programs and that they freeze code to be used later. They are defined with the ```function``` keyword and have parameters and a body. Functions are **called** by putting two braces after their name. This act is also called invoking. It runs the code which has been frozen inside of the function and returns a value if it is specified within the function. Otherwise the value ```undefined``` is returned.

Hope you guys and girls had as much fun reading this as I had writing it. Next time I'll be writing about control flow and conditional statements. Heads up though, we'll return to functions more a bit later.

Until next time, have fun!

---

## Check out previous lessons
- [Lesson 1 - Values](https://steemit.com/programming/@adnanrahic/the-javascript-journey-1-values)
- [Lesson 2 - Arithmetic and Operators](https://steemit.com/programming/@adnanrahic/the-javascript-journey-2-arithmetic-and-operators)
- [Lesson 3 - Logical Operators](https://steemit.com/programming/@adnanrahic/the-javascript-journey-3-logical-operators)
- [Lesson 4 - Special Values and Precise Comparisons](https://steemit.com/programming/@adnanrahic/the-javascript-journey-4-special-values-and-precise-comparisons)
- [Chapter 1 Recap](https://steemit.com/programming/@adnanrahic/the-javascript-journey-chapter-1-recap)
- [Lesson 5 - Expressions and Statements](https://steemit.com/programming/@adnanrahic/the-javascript-journey-5-expressions-and-statements)
- [Lesson 6 - Variables](https://steemit.com/programming/@adnanrahic/the-javascript-journey-6-variables)

---

*Drop an upvote if you liked the article, share if you believe it will be of help to someone. Feel free to ask any questions you have in the comments below.*
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
properties (23)
authoradnanrahic
permlinkthe-javascript-journey-7-what-are-functions
categoryprogramming
json_metadata{"tags":["programming","howto","education","technology","steemit"],"image":["https://raw.githubusercontent.com/adnanrahic/cdn/master/tjj-7/1-sky-earth-space-working.jpg","https://raw.githubusercontent.com/adnanrahic/cdn/master/tjj-7/2-pexels-photo%20(1).jpg","https://raw.githubusercontent.com/adnanrahic/cdn/master/tjj-7/3-14155209556_c46e13cd15_b.jpg"],"links":["https://steemit.com/programming/@adnanrahic/the-javascript-journey-1-values","https://steemit.com/programming/@adnanrahic/the-javascript-journey-2-arithmetic-and-operators","https://steemit.com/programming/@adnanrahic/the-javascript-journey-3-logical-operators","https://steemit.com/programming/@adnanrahic/the-javascript-journey-4-special-values-and-precise-comparisons","https://steemit.com/programming/@adnanrahic/the-javascript-journey-chapter-1-recap","https://steemit.com/programming/@adnanrahic/the-javascript-journey-5-expressions-and-statements","https://steemit.com/programming/@adnanrahic/the-javascript-journey-6-variables"],"app":"steemit/0.1","format":"markdown"}
created2017-09-02 22:24:39
last_update2017-09-02 22:24:39
depth0
children9
last_payout2017-09-09 22:24:39
cashout_time1969-12-31 23:59:59
total_payout_value66.679 HBD
curator_payout_value21.489 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length6,836
author_reputation1,605,311,705,685
root_title"The JavaScript Journey #7 - What are Functions?"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id13,689,484
net_rshares22,842,279,951,035
author_curate_reward""
vote details (33)
@codero ·
Cool post. You can also do `return;` if you don't want to return anything. I came across Golang's ability to have multiple return values (it would be cool if javascript implements something like that). I mean something like `return x, y, z;` .

 Also checkout my new post on Javascript's `const` keyword:

https://steemit.com/programming/@codero/javascript-s-const-keyword

and follow me. I want to write more if there is support. 

Follow me @codero
properties (22)
authorcodero
permlinkre-adnanrahic-the-javascript-journey-7-what-are-functions-20170904t131508819z
categoryprogramming
json_metadata{"tags":["programming"],"users":["codero"],"links":["https://steemit.com/programming/@codero/javascript-s-const-keyword"],"app":"steemit/0.1"}
created2017-09-04 13:15:09
last_update2017-09-04 13:15:09
depth1
children1
last_payout2017-09-11 13:15:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length450
author_reputation15,333,700,816
root_title"The JavaScript Journey #7 - What are Functions?"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id13,844,135
net_rshares0
@adnanrahic ·
That's cool! But returning multiple values in an object acts just fine, at least for me.
Like this: ```return { x: x, y: y, z: z}```

A word of advice from someone a bit more experienced. Please do not beg for followers. It can only diminish the respect people here have for you. I've never, not even once, begged for anything here, and still, people read my stuff. That's solely because I provide value, and value is worth reading. People are busy, they do not have time to read articles that are badly written or simply do not interest them.

Best of luck with your future endevours. :)
properties (22)
authoradnanrahic
permlinkre-codero-re-adnanrahic-the-javascript-journey-7-what-are-functions-20170909t194045296z
categoryprogramming
json_metadata{"tags":["programming"],"app":"steemit/0.1"}
created2017-09-09 19:40:45
last_update2017-09-09 19:40:45
depth2
children0
last_payout2017-09-16 19:40:45
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length588
author_reputation1,605,311,705,685
root_title"The JavaScript Journey #7 - What are Functions?"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id14,388,330
net_rshares0
@diamondlockr ·
like your post and upped!
properties (22)
authordiamondlockr
permlinkre-adnanrahic-the-javascript-journey-7-what-are-functions-20170907t104954047z
categoryprogramming
json_metadata{"tags":["programming"],"app":"steemit/0.1"}
created2017-09-07 10:49:45
last_update2017-09-07 10:49:45
depth1
children0
last_payout2017-09-14 10:49:45
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length25
author_reputation26,623,845,971
root_title"The JavaScript Journey #7 - What are Functions?"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id14,137,886
net_rshares0
@failshub ·
Get More Upvotes and Followers With : https://steemfollower.com/?r=1966
👎  ,
properties (23)
authorfailshub
permlinkre-adnanrahic-the-javascript-journey-7-what-are-functions-20170902t224438439z
categoryprogramming
json_metadata{"tags":["programming"],"links":["https://steemfollower.com/?r=1966"],"app":"steemit/0.1"}
created2017-09-02 22:45:51
last_update2017-09-02 22:45:51
depth1
children0
last_payout2017-09-09 22:45:51
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length71
author_reputation-594,830,628,851
root_title"The JavaScript Journey #7 - What are Functions?"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id13,690,612
net_rshares-10,923,267,428
author_curate_reward""
vote details (2)
@gotgame ·
Fell in love with the way you covered every aspect of Functions. Thanks for this, looking forward to the next module
properties (22)
authorgotgame
permlinkre-adnanrahic-the-javascript-journey-7-what-are-functions-20170907t085838854z
categoryprogramming
json_metadata{"tags":["programming"],"app":"steemit/0.1"}
created2017-09-07 08:58:42
last_update2017-09-07 08:58:42
depth1
children1
last_payout2017-09-14 08:58:42
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length116
author_reputation23,969,707,386,372
root_title"The JavaScript Journey #7 - What are Functions?"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id14,130,348
net_rshares0
@adnanrahic ·
Thank you! Stay tuned, it'll be soon enough. :)
👍  
properties (23)
authoradnanrahic
permlinkre-gotgame-re-adnanrahic-the-javascript-journey-7-what-are-functions-20170909t194131413z
categoryprogramming
json_metadata{"tags":["programming"],"app":"steemit/0.1"}
created2017-09-09 19:41:30
last_update2017-09-09 19:41:30
depth2
children0
last_payout2017-09-16 19:41:30
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length47
author_reputation1,605,311,705,685
root_title"The JavaScript Journey #7 - What are Functions?"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id14,388,392
net_rshares423,627,337
author_curate_reward""
vote details (1)
@mohammedali64466 ·
good
👍  
👎  
properties (23)
authormohammedali64466
permlinkre-adnanrahic-the-javascript-journey-7-what-are-functions-20170903t142640117z
categoryprogramming
json_metadata{"tags":["programming"],"app":"steemit/0.1"}
created2017-09-03 14:26:45
last_update2017-09-03 14:26:45
depth1
children0
last_payout2017-09-10 14:26:45
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length4
author_reputation-121,877,119,891
root_title"The JavaScript Journey #7 - What are Functions?"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id13,747,388
net_rshares-9,905,158,953
author_curate_reward""
vote details (2)
@phil-coding ·
I really loved this Post! I will try to read the whole Series +1 follow for me
properties (22)
authorphil-coding
permlinkre-adnanrahic-the-javascript-journey-7-what-are-functions-20170903t043033995z
categoryprogramming
json_metadata{"tags":["programming"],"app":"steemit/0.1"}
created2017-09-03 04:32:06
last_update2017-09-03 04:32:06
depth1
children1
last_payout2017-09-10 04:32:06
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length78
author_reputation4,773,758,818
root_title"The JavaScript Journey #7 - What are Functions?"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id13,708,938
net_rshares0
@adnanrahic ·
I'm thrilled you liked it! Hope you have fun with reading the rest of the series. :)
properties (22)
authoradnanrahic
permlinkre-phil-coding-re-adnanrahic-the-javascript-journey-7-what-are-functions-20170903t072947309z
categoryprogramming
json_metadata{"tags":["programming"],"app":"steemit/0.1"}
created2017-09-03 07:29:54
last_update2017-09-03 07:29:54
depth2
children0
last_payout2017-09-10 07:29:54
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length84
author_reputation1,605,311,705,685
root_title"The JavaScript Journey #7 - What are Functions?"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id13,719,002
net_rshares0