-
-
Notifications
You must be signed in to change notification settings - Fork 637
Add concept exercise functions #1183
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
2aeb552
ac95006
248ae2f
1427263
4bb3fc9
0b37c57
bcbbbbd
1171fde
e248061
082f266
ab85daf
67eb0ef
7e4d47e
91c4a35
7a51e9b
72bb21e
e4bf3cb
c8a0a9d
aadb693
8ada2fc
ea12ea7
67c648a
63e26ec
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
{ | ||
"blurb": "There are multiple ways to define functions in JavaScript. Learn about function declarations and function expressions.", | ||
"authors": ["junedev"], | ||
"contributors": [] | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,162 @@ | ||
# About | ||
|
||
A function allows to group code into a reusable unit. | ||
There are multiple ways to define functions in JavaScript. | ||
Here we will look at _function declarations_ and _function expressions_. | ||
Other possibilities like [arrow functions][concept-arrow-functions] will be covered in other concepts. | ||
|
||
## Function Declaration | ||
|
||
The standard way of defining a function in JavaScript is a _function declaration_, also called _function definition_ or _function statement_. | ||
|
||
It consists of the `function` keyword, the name of the function, and a comma-separated list of parameters in round brackets. | ||
This is followed by the function body (the code that should be executed) wrapped in curly brackets. | ||
|
||
```javascript | ||
function someName(param1, param2, param3) { | ||
// ... | ||
} | ||
``` | ||
|
||
## Using a Function | ||
|
||
In JavaScript a function is invoked (called) by stating the function name followed by round brackets that contain the arguments. | ||
|
||
```javascript | ||
someName(arg1, arg2, arg3); | ||
``` | ||
|
||
Just stating the function name does **not** call the function in JavaScript. | ||
|
||
```javascript | ||
function sayHello() { | ||
console.log('Hello, World!'); | ||
} | ||
|
||
sayHello; | ||
// => [Function: sayHello] | ||
|
||
sayHello(); | ||
// => 'Hello, World!' | ||
``` | ||
|
||
## Parameters | ||
|
||
When working with parameters inside the function body, be aware of possible side effects to the original value that was passed to the function. | ||
In JavaScript, an argument is a copy of a reference to the original value. | ||
What this means in practice depends on the data type of the argument. | ||
|
||
- Values of [primitive data types][mdn-primitives] are _immutable_. | ||
All "modifications" always create a new primitive value. | ||
Because of that, the original value is never affected by what happens to the argument in the function body. | ||
|
||
- For all other values (objects, arrays, functions) it is a mixed bag. | ||
Since the reference is copied, a reassignment will not affect the original value. | ||
However, since you care dealing with a [shallow copy][wikipedia-shalllow-copy], modifying the argument in the function body will also change the original value that was passed in. | ||
|
||
By default, all parameters defined in the function declaration are optional in JavaScript. | ||
If you provide less arguments than there are parameters, the missing arguments will be `undefined` inside the function, see [Null and Undefined][concept-null-undefined]. | ||
In many cases it makes sense to assign a more appropriate default value than `undefined`. | ||
This can by done by specifying default parameters directly in the function definition. | ||
|
||
```javascript | ||
function someName(param1 = defaultValue1, param2 = defaultValue2) { | ||
// ... | ||
} | ||
``` | ||
|
||
You can even call a function with more arguments than there were parameters in the definition. | ||
All arguments, including those excess arguments, can be found in the [arguments "array"][mdn-arguments-object]. | ||
|
||
It is also possible to define functions that accept an arbitrary number of arguments (variadic functions), see rest parameters in [Rest and Spread Operators][concept-rest-and-spread] for details about this. | ||
|
||
## Return Statement | ||
|
||
Using the `return` statement, you can pass the result of a function to the code that called it. | ||
There can be multiple `return` statements in a function. | ||
The execution of the function ends as soon as it hits one of those `return`s. | ||
|
||
```javascript | ||
function checkNumber(num) { | ||
if (num === 0) { | ||
return 'You passed 0, please provide another number.'; | ||
} | ||
|
||
return 'Thanks for passing such a nice number.'; | ||
} | ||
``` | ||
|
||
If you use a naked return or no return at all, the result of the function is `undefined`. | ||
There are no implicit returns in JavaScript. | ||
|
||
```javascript | ||
function nakedReturn(a) { | ||
a * 2; | ||
return; | ||
} | ||
|
||
nakedReturn(1); | ||
// => undefined | ||
|
||
function noReturn(a) { | ||
a * 2; | ||
} | ||
|
||
noReturn(1); | ||
// => undefined | ||
``` | ||
|
||
In JavaScript, you can only return exactly one value. | ||
If you want to pass more information, you need to combine it into one entity first, usually into an [object][concept-objects], or an [array][concept-arrays].. | ||
|
||
```javascript | ||
function divide(a, b) { | ||
return { | ||
quotient: Math.floor(a / b), | ||
remainder: a % b, | ||
}; | ||
} | ||
``` | ||
|
||
## Function Expression | ||
|
||
A function declaration is a standalone statement. | ||
But sometimes it is helpful to define a function as part of another expression, e.g., in an assignment, as a function parameter ([callback][concept-callbacks]) or as value in an [object][concept-objects]. | ||
This can be done with a function expression. | ||
It has the same syntax as a function declaration, only that the function name can be omitted to create an _anonymous function_. | ||
|
||
```javascript | ||
const someFunction = function (param) { | ||
// ... | ||
}; | ||
|
||
someOtherFunction(function (param) { | ||
//... | ||
}); | ||
|
||
const obj = { | ||
someFunction: function (param) { | ||
// ... | ||
}, | ||
}; | ||
``` | ||
|
||
## Scope | ||
|
||
A function introduces a new execution context in JavaScript. | ||
Variables defined inside a function are not accessible outside of that function. | ||
But variables defined in the parent scope (the scope where the function was defined itself) are accessible inside the function. | ||
junedev marked this conversation as resolved.
Show resolved
Hide resolved
|
||
The [MDN documentation on scope][mdn-scope] shows examples of this behavior. | ||
|
||
Have a look at [closures][concept-closures] to learn more about variable scope in JavaScript. | ||
|
||
[concept-arrow-functions]: /tracks/javascript/concepts/arrow-functions | ||
junedev marked this conversation as resolved.
Show resolved
Hide resolved
|
||
[wikipedia-shalllow-copy]: https://en.wikipedia.org/wiki/Object_copying#Shallow_copy | ||
[concept-null-undefined]: /tracks/javascript/concepts/null-undefined | ||
[concept-rest-and-spread]: /tracks/javascript/concepts/rest-and-spread | ||
junedev marked this conversation as resolved.
Show resolved
Hide resolved
|
||
[concept-objects]: /tracks/javascript/concepts/objects | ||
[concept-callbacks]: /tracks/javascript/concepts/callbacks | ||
[mdn-arguments-object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments | ||
[mdn-primitives]: https://developer.mozilla.org/en-US/docs/Glossary/Primitive | ||
[mdn-scope]: https://developer.mozilla.org/en-US/docs/Glossary/Scope | ||
[concept-closures]: /tracks/javascript/concepts/closures |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,123 @@ | ||
# Introduction | ||
|
||
A function allows to group code into a reusable unit. | ||
There are multiple ways to define functions in JavaScript. | ||
Here we will look at _function declarations_ and _function expressions_.. | ||
Other possibilities like [arrow functions][concept-arrow-functions] will be covered in other concepts. | ||
|
||
## Function Declaration | ||
|
||
The standard way of defining a function in JavaScript is a _function declaration_, also called _function definition_ or _function statement_. | ||
|
||
It consists of the `function` keyword, the name of the function, and a comma-separated list of parameters in round brackets. | ||
This is followed by the function body (the code that should be executed) wrapped in curly brackets. | ||
|
||
```javascript | ||
function someName(param1, param2, param3) { | ||
// ... | ||
} | ||
``` | ||
|
||
In JavaScript a function is invoked (called) by stating the function name followed by round brackets that contain the arguments. | ||
|
||
```javascript | ||
someName(arg1, arg2, arg3); | ||
``` | ||
|
||
## Parameters | ||
|
||
When working with parameters inside the function body, be aware of possible side effects to the original value that was passed to the function. | ||
In JavaScript, the behavior depends on the data type of the argument. | ||
|
||
- All values that have [primitive data types][mdn-primitives] are immutable in JavaScript, so if used as arguments they are _passed by value_. | ||
That means you are dealing with a copy of the original value in the function body and you can modify it without affecting the original value. | ||
- All other values (objects, arrays, functions) are _passed by reference_. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same comments as above, but in the introduction I would be inclined to make this section even simpler. |
||
If you modify arguments of non-primitive types, you are changing the original value outside of the function because the argument represents a reference to the original value, not a copy of that value. | ||
|
||
By default, all parameters defined in the function declaration are optional in JavaScript. | ||
If you provide less arguments than there are parameters, the missing arguments will be `undefined` inside the function, see [Null and Undefined][concept-null-undefined]. | ||
In many cases it makes sense to assign a more appropriate default value than `undefined`. | ||
This can by done by specifying default parameters directly in the function definition. | ||
|
||
```javascript | ||
function someName(param1 = defaultValue1, param2 = defaultValue2) { | ||
// ... | ||
} | ||
``` | ||
|
||
## Return Statement | ||
|
||
Using the `return` statement, you can pass the result of a function to the code that called it. | ||
There can be multiple `return` statements in a function. | ||
The execution of the function ends as soon as it hits one of those `return`s. | ||
|
||
```javascript | ||
function checkNumber(num) { | ||
if (num === 0) { | ||
return 'You passed 0, please provide another number.'; | ||
} | ||
|
||
return 'Thanks for passing such a nice number.'; | ||
} | ||
``` | ||
|
||
If you use a naked return or no return at all, the result of the function is `undefined`. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. "naked returns" - is that how they are called in JS? Googling that phrase only gives me Golang-related results. I'm asking because I never heard it before 🤔 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. How would you call this instead? I also heard people saying "unadorned return" but I think that's even less common than "naked return". There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If I had to find a short name, I would call it an "empty return". |
||
There are no implicit returns in JavaScript. | ||
|
||
```javascript | ||
function nakedReturn(a) { | ||
a * 2; | ||
return; | ||
} | ||
|
||
nakedReturn(1); | ||
// => undefined | ||
|
||
function noReturn(a) { | ||
a * 2; | ||
} | ||
|
||
noReturn(1); | ||
// => undefined | ||
``` | ||
|
||
In JavaScript, you can only return exactly one value. | ||
If you want to pass more information, you need to combine it into one entity first, usually into an [object][concept-objects], or an [array][concept-arrays].. | ||
|
||
```javascript | ||
function divide(a, b) { | ||
return { | ||
quotient: Math.floor(a / b), | ||
remainder: a % b, | ||
}; | ||
} | ||
``` | ||
|
||
## Function Expression | ||
|
||
A function declaration is a standalone statement. | ||
But sometimes it is helpful to define a function as part of another expression, e.g., in an assignment, as a function parameter ([callback][concept-callbacks]) or as value in an [object][concept-objects]. | ||
This can be done with a function expression. | ||
It has the same syntax as a function declaration, only that the function name can be omitted to create an _anonymous function_. | ||
|
||
```javascript | ||
const someFunction = function (param) { | ||
// ... | ||
}; | ||
|
||
someOtherFunction(function (param) { | ||
//... | ||
}); | ||
|
||
const obj = { | ||
someFunction: function (param) { | ||
// ... | ||
}, | ||
}; | ||
``` | ||
|
||
[concept-arrow-functions]: /tracks/javascript/concepts/arrow-functions | ||
[concept-null-undefined]: /tracks/javascript/concepts/null-undefined | ||
[concept-objects]: /tracks/javascript/concepts/objects | ||
[concept-callbacks]: /tracks/javascript/concepts/callbacks | ||
[mdn-primitives]: https://developer.mozilla.org/en-US/docs/Glossary/Primitive |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
[ | ||
{ | ||
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions", | ||
"description": "MDN: Functions Overview" | ||
}, | ||
{ | ||
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function", | ||
"description": "MDN: Function Declaration" | ||
}, | ||
{ | ||
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function", | ||
"description": "MDN: Function Expression" | ||
} | ||
] |
This file was deleted.
This file was deleted.
This file was deleted.
This file was deleted.
Uh oh!
There was an error while loading. Please reload this page.