mirror of
https://github.com/microsoft/Web-Dev-For-Beginners.git
synced 2025-10-02 17:28:04 +02:00
moving folders
This commit is contained in:
12
js-basics/2-functions-methods/.github/post-lecture-quiz.md
vendored
Normal file
12
js-basics/2-functions-methods/.github/post-lecture-quiz.md
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
*Complete this quiz by checking one answer per question.*
|
||||
|
||||
1. Arguments must be provided for all parameters in a function
|
||||
|
||||
- [ ] true
|
||||
- [ ] false
|
||||
|
||||
2. What does a default value do?
|
||||
|
||||
- [ ] Sets a correct value
|
||||
- [ ] Gives a starter value for a parameters so your code still behaves if you omit an argument for it
|
||||
- [ ] Has no utility
|
12
js-basics/2-functions-methods/.github/pre-lecture-quiz.md
vendored
Normal file
12
js-basics/2-functions-methods/.github/pre-lecture-quiz.md
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
*Complete this quiz in class*
|
||||
|
||||
1. What's an argument?
|
||||
|
||||
- [ ] It's something you declare in the function definition
|
||||
- [ ] It's something you pass into a function at invocation time
|
||||
- [ ] It's something you have with people you know
|
||||
|
||||
2. True or false: a function must return something
|
||||
|
||||
- [ ] true
|
||||
- [ ] false
|
190
js-basics/2-functions-methods/README.md
Normal file
190
js-basics/2-functions-methods/README.md
Normal file
@@ -0,0 +1,190 @@
|
||||
# JavaScript Basics: Methods and Functions
|
||||
|
||||
[](https://youtube.com/watch?v=XgKsD6Zwvlc "Methods and Functions")
|
||||
|
||||

|
||||
> Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac)
|
||||
|
||||
## [Pre-lecture quiz](.github/pre-lecture-quiz.md)
|
||||
|
||||
When we think about writing code, we always want to ensure our code is readable. While this sounds counterintuitive, code is read many more times than it's written. One core tool in a developer's toolbox to ensure maintainable code is the **function**.
|
||||
|
||||
## Functions
|
||||
|
||||
At its core, a function is a block of code we can execute on demand. This is perfect for scenarios where we need to perform the same task multiple times; rather than duplicating the logic in multiple locations (which would make it hard to update when the time comes), we can centralize it in one location, and call it whenever we need the operation performed - you can even call functions from other functions!.
|
||||
|
||||
Just as important is the ability to name a function. While this might seem trivial, the name provides a quick way of documenting a section of code. You could think of this as a label on a button. If I click on a button which reads "Cancel timer", I know it's going to stop running the clock.
|
||||
|
||||
## Creating and calling a function
|
||||
|
||||
The syntax for a function looks like the following:
|
||||
|
||||
```javascript
|
||||
function nameOfFunction() { // function definition
|
||||
// function definition/body
|
||||
}
|
||||
```
|
||||
|
||||
If I wanted to create a function to display a greeting, it might look like this:
|
||||
|
||||
```javascript
|
||||
function displayGreeting() {
|
||||
console.log('Hello, world!');
|
||||
}
|
||||
```
|
||||
|
||||
Whenever we want to call (or invoke) our function, we use the name of the function followed by `()`. It's worth noting the fact our function can be defined before or after we decide to call it; the JavaScript compiler will find it for you.
|
||||
|
||||
```javascript
|
||||
// calling our function
|
||||
displayGreeting();
|
||||
```
|
||||
|
||||
> **NOTE:** There is a special type of function known as a **method**, which you've already been using! In fact, we saw this in our demo above when we used `console.log`. What makes a method different from a function is a method is attached to an object (`console` in our example), while a function is free floating. You will hear many developers use these terms interchangeably.
|
||||
|
||||
### Function best practices
|
||||
|
||||
There are a handful of best practices to keep in mind when creating functions
|
||||
|
||||
- As always, use descriptive names so you know what the function will do
|
||||
- Use **camelCasing** to combine words
|
||||
- Keep your functions focused on a specific task
|
||||
|
||||
## Passing information to a function
|
||||
|
||||
To make a function more reusable you'll often want to pass information into it. If we consider our `displayGreeting` example above, it will only display **Hello, world!**. Not the most useful function one could create. If we want to make it a little more flexible, like allowing someone to specify the name of the person to greet, we can add a **parameter**. A parameter (also sometimes called an **argument**), is additional information sent to a function.
|
||||
|
||||
Parameters are listed in the definition part within parenthesis and are comma separated like so:
|
||||
|
||||
```javascript
|
||||
function name(param, param2, param3) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
We can update our `displayGreeting` to accept a name and have that displayed.
|
||||
|
||||
```javascript
|
||||
function displayGreeting(name) {
|
||||
const message = `Hello, ${name}!`;
|
||||
console.log(message);
|
||||
}
|
||||
```
|
||||
|
||||
When we want to call our function and pass in the parameter, we specify it in the parenthesis.
|
||||
|
||||
```javascript
|
||||
displayGreeting('Christopher');
|
||||
// displays "Hello, Christopher!" when run
|
||||
```
|
||||
|
||||
## Default values
|
||||
|
||||
We can make our function even more flexible by adding more parameters. But what if we don't want to require every value be specified? Keeping with our greeting example, we could leave name as required (we need to know who we're greeting), but we want to allow the greeting itself to be customized as desired. If someone doesn't want to customize it, we provide a default value instead. To provide a default value to a parameter, we set it much in the same way we set a value for a variable - `parameterName = 'defaultValue'`. To see a full example:
|
||||
|
||||
```javascript
|
||||
function displayGreeting(name, salutation='Hello') {
|
||||
console.log(`${salutation}, ${name}`);
|
||||
}
|
||||
```
|
||||
|
||||
When we call the function, we can then decide if we want to set a value for `salutation`.
|
||||
|
||||
```javascript
|
||||
displayGreeting('Christopher');
|
||||
// displays "Hello, Christopher"
|
||||
|
||||
displayGreeting('Christopher', 'Hi');
|
||||
// displays "Hi, Christopher"
|
||||
```
|
||||
|
||||
## Return values
|
||||
|
||||
Up until now the function we built will always output to the [console](https://developer.mozilla.org/en-US/docs/Web/API/console). Sometimes this can be exactly what we're looking for, especially when we create functions which will be calling other services. But what if I want to create a helper function to perform a calculation and provide the value back so I can use it elsewhere?
|
||||
|
||||
We can do this by using a **return value**. A return value is returned by the function, and can be stored in a variable just the same as we could store a literal value such as a string or number.
|
||||
|
||||
If a function does return something then the keyword `return` is used. The `return` keyword expects a value or reference of what's being returned like so:
|
||||
|
||||
```javascript
|
||||
return myVariable;
|
||||
```
|
||||
|
||||
We could create a function to create a greeting message and return the value back to the caller
|
||||
|
||||
```javascript
|
||||
function createGreetingMessage(name) {
|
||||
const message = `Hello, ${name}`;
|
||||
return message;
|
||||
}
|
||||
```
|
||||
|
||||
When calling this function we'll store the value in a variable. This is much the same way we'd set a variable to a static value (like `const name = 'Christopher'`).
|
||||
|
||||
```javascript
|
||||
const greetingMessage = createGreetingMessage('Christopher');
|
||||
```
|
||||
|
||||
## Functions as parameters for functions
|
||||
|
||||
As you progress in your programming career, you will come across functions which accept functions as parameters. This neat trick is commonly used when we don't know when something is going to occur or complete, but we know we need to perform an operation in response.
|
||||
|
||||
As an example, consider [setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout), which begins a timer and will execute code when it completes. We need to tell it what code we want to execute. Sounds like a perfect job for a function!
|
||||
|
||||
If you run the code below, after 3 seconds you'll see the message **3 seconds has elapsed**.
|
||||
|
||||
```javascript
|
||||
function displayDone() {
|
||||
console.log('3 seconds has elapsed');
|
||||
}
|
||||
// timer value is in milliseconds
|
||||
setTimeout(3000, displayDone);
|
||||
```
|
||||
|
||||
### Anonymous functions
|
||||
|
||||
Let's take another look at what we've built. We're creating a function with a name which will be used one time. As our application gets more complex, we can see ourselves creating a lot of functions which will only be called once. This isn't ideal. As it turns out, we don't always need to provide a name!
|
||||
|
||||
When we are passing a function as a parameter we can bypass creating one in advance and instead build one as part of the parameter. We use the same `function` keyword, but instead we build it as a parameter.
|
||||
|
||||
Let's rewrite the code above to use an anonymous function:
|
||||
|
||||
```javascript
|
||||
setTimeout(3000, function() {
|
||||
console.log('3 seconds has elapsed');
|
||||
});
|
||||
```
|
||||
|
||||
If you run our new code you'll notice we get the same results. We've created a function, but didn't have to give it a name!
|
||||
|
||||
### Fat arrow functions
|
||||
|
||||
One shortcut common in a lot of programming languages (including JavaScript) is the ability to use what's called an **arrow** or **fat arrow** function. It uses a special indicator of `=>`, which looks like an arrow - thus the name! By using `=>`, we are able to skip the `function` keyword.
|
||||
|
||||
Let's rewrite our code one more time to use a fat arrow function:
|
||||
|
||||
```javascript
|
||||
setTimeout(3000, () => {
|
||||
console.log('3 seconds has elapsed');
|
||||
});
|
||||
```
|
||||
|
||||
### When to use each strategy
|
||||
|
||||
You've now seen we have three ways to pass a function as a parameter and might be wondering when to use each. If you know you'll be using the function more than once, create it as normal. If you'll be using it for just the one location, it's generally best to use an anonymous function. Whether or not you use a fat arrow function or the more traditional `function` syntax is up to you, but you will notice most modern developers prefer `=>`.
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Challenge
|
||||
|
||||
Can you articulate in one sentence the difference between functions and methods? Give it a try!
|
||||
|
||||
## [Post-lecture quiz](.github/post-lecture-quiz.md)
|
||||
|
||||
## Review & Self Study
|
||||
|
||||
It's worth [reading up a little more on arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), as they are increasingly used in code bases. Practice writing a function, and then rewriting it with this syntax.
|
||||
|
||||
## Assignment
|
||||
|
||||
[Fun with Functions](assignment.md)
|
13
js-basics/2-functions-methods/assignment.md
Normal file
13
js-basics/2-functions-methods/assignment.md
Normal file
@@ -0,0 +1,13 @@
|
||||
# Fun with Functions
|
||||
|
||||
## Instructions
|
||||
|
||||
Create different functions, both functions that return something and functions that don't return anything.
|
||||
|
||||
See if you can create a function that has a mix of parameters and parameters with default values.
|
||||
|
||||
## Rubric
|
||||
|
||||
| Criteria | Exemplary | Adequate | Needs Improvement |
|
||||
| -------- | -------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | ----------------- |
|
||||
| | Solution is offered with two or more well-performing functions with diverse parameters | Working solution is offered with one function and few parameters | Solution has bugs |
|
BIN
js-basics/2-functions-methods/images/webdev101-js-functions.png
Normal file
BIN
js-basics/2-functions-methods/images/webdev101-js-functions.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 1.4 MiB |
195
js-basics/2-functions-methods/translations/README.de.md
Normal file
195
js-basics/2-functions-methods/translations/README.de.md
Normal file
@@ -0,0 +1,195 @@
|
||||
# JavaScript-Grundlagen: Methoden und Funktionen
|
||||
|
||||
[](https://youtube.com/watch?v=XgKsD6Zwvlc "Methoden und Funktionen")
|
||||
|
||||
## [Pre-Lecture Quiz](.github/pre-lecture-quiz.md)
|
||||
|
||||
Wenn wir darüber nachdenken, Code zu schreiben, möchten wir immer sicherstellen, dass unser Code lesbar ist. Während dies nicht intuitiv klingt, wird Code viel öfter gelesen als geschrieben. Ein Kernwerkzeug in der Toolbox eines Entwicklers, um wartbaren Code sicherzustellen, ist die **Funktion**.
|
||||
|
||||
## Funktionen
|
||||
|
||||
Eine Funktion ist im Kern ein Codeblock, den wir bei Bedarf ausführen können. Dies ist perfekt für Szenarien, in denen wir dieselbe Aufgabe mehrmals ausführen müssen. Anstatt die Logik an mehreren Orten zu duplizieren (was eine Aktualisierung zu gegebener Zeit erschweren würde), können wir sie an einem Ort zentralisieren und jederzeit aufrufen, wenn die Operation ausgeführt werden muss - Sie können sogar Funktionen von anderen Funktionen aus aufrufen!.
|
||||
|
||||
Ebenso wichtig ist die Fähigkeit, eine Funktion zu benennen. Obwohl dies trivial erscheinen mag, bietet der Name eine schnelle Möglichkeit, einen Codeabschnitt zu dokumentieren. Sie können sich dies als Beschriftung auf einer Schaltfläche vorstellen. Wenn ich auf eine Schaltfläche mit der Aufschrift "Timer abbrechen" klicke, weiß ich, dass die Uhr nicht mehr läuft.
|
||||
|
||||
## Eine Funktion erstellen und aufrufen
|
||||
|
||||
Die Syntax für eine Funktion sieht folgendermaßen aus:
|
||||
|
||||
|
||||
```javascript
|
||||
function nameOfFunction() { // function definition
|
||||
// function definition/body
|
||||
}
|
||||
```
|
||||
|
||||
Wenn ich eine Funktion zum Anzeigen einer Begrüßung erstellen wollte, könnte dies folgendermaßen aussehen:
|
||||
|
||||
```javascript
|
||||
function displayGreeting() {
|
||||
console.log('Hello, world!');
|
||||
}
|
||||
```
|
||||
|
||||
Wann immer wir unsere Funktion aufrufen (oder aufrufen) möchten, verwenden wir den Namen der Funktion, gefolgt von `()`. Es ist erwähnenswert, dass unsere Funktion definiert werden kann, bevor oder nachdem wir uns entscheiden, sie aufzurufen. Der JavaScript-Compiler findet es für Sie.
|
||||
|
||||
|
||||
```javascript
|
||||
// calling our function
|
||||
displayGreeting();
|
||||
```
|
||||
|
||||
> **HINWEIS:** Es gibt eine spezielle Art von Funktion, die als **Methode** bekannt ist und die Sie bereits verwendet haben! Tatsächlich haben wir dies in unserer obigen Demo gesehen, als wir `console.log` verwendet haben. Was eine Methode von einer Funktion unterscheidet, ist, dass eine Methode an ein Objekt angehängt ist (in unserem Beispiel `console`), während eine Funktion frei schwebend ist. Sie werden hören, dass viele Entwickler diese Begriffe synonym verwenden.
|
||||
|
||||
### Best Practices für Funktionen
|
||||
|
||||
Es gibt eine Handvoll Best Practices, die beim Erstellen von Funktionen berücksichtigt werden müssen
|
||||
|
||||
- Verwenden Sie wie immer beschreibende Namen, damit Sie wissen, was die Funktion tun wird
|
||||
- Verwenden Sie **camelCasing**, um Wörter zu kombinieren
|
||||
- Konzentrieren Sie Ihre Funktionen auf eine bestimmte Aufgabe
|
||||
|
||||
## Informationen an eine Funktion übergeben
|
||||
|
||||
Um eine Funktion wiederverwendbarer zu machen, möchten Sie häufig Informationen an sie weitergeben. Wenn wir unser Beispiel `displayGreeting` oben betrachten, wird nur **Hallo, Welt!** angezeigt. Nicht die nützlichste Funktion, die man erstellen könnte. Wenn wir es etwas flexibler gestalten möchten, z. B. jemandem erlauben, den Namen der zu begrüßenden Person anzugeben, können wir einen **Parameter** hinzufügen. Ein Parameter (manchmal auch als **Argument** bezeichnet) sind zusätzliche Informationen, die an eine Funktion gesendet werden.
|
||||
|
||||
Die Parameter sind im Definitionsteil in Klammern aufgeführt und werden wie folgt durch Kommas getrennt:
|
||||
|
||||
```javascript
|
||||
function name(param, param2, param3) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
Wir können unser `displayGreeting` aktualisieren, um einen Namen zu akzeptieren und diesen anzeigen zu lassen.
|
||||
|
||||
|
||||
```javascript
|
||||
function displayGreeting(name) {
|
||||
const message = `Hello, ${name}!`;
|
||||
console.log(message);
|
||||
}
|
||||
```
|
||||
|
||||
Wenn wir unsere Funktion aufrufen und den Parameter übergeben möchten, geben wir ihn in Klammern an.
|
||||
|
||||
```javascript
|
||||
displayGreeting('Christopher');
|
||||
// zeigt "Hallo Christopher!" wenn ausgeführt
|
||||
```
|
||||
|
||||
## Standardwerte
|
||||
|
||||
Wir können unsere Funktion noch flexibler gestalten, indem wir weitere Parameter hinzufügen. Aber was ist, wenn nicht jeder Wert angegeben werden soll? In Übereinstimmung mit unserem Begrüßungsbeispiel könnten wir den Namen nach Bedarf belassen (wir müssen wissen, wen wir begrüßen), aber wir möchten, dass die Begrüßung selbst nach Wunsch angepasst wird. Wenn jemand es nicht anpassen möchte, geben wir stattdessen einen Standardwert an. Um einem Parameter einen Standardwert zuzuweisen, setzen wir ihn ähnlich wie einen Wert für eine Variable - `parameterName = 'defaultValue'`. Um ein vollständiges Beispiel zu sehen:
|
||||
|
||||
|
||||
```javascript
|
||||
function displayGreeting(name, salutation='Hello') {
|
||||
console.log(`${salutation}, ${name}`);
|
||||
}
|
||||
```
|
||||
|
||||
When we call the function, we can then decide if we want to set a value for `salutation`.
|
||||
|
||||
```javascript
|
||||
displayGreeting('Christopher');
|
||||
// zeigt "Hallo Christopher!"
|
||||
|
||||
displayGreeting('Christopher', 'Hi');
|
||||
// zeigt "Hi Christopher!"
|
||||
```
|
||||
|
||||
## Rückgabewerte
|
||||
|
||||
Bisher wurde die von uns erstellte Funktion immer an die [Konsole](https://developer.mozilla.org/en-US/docs/Web/API/console) ausgegeben. Manchmal kann dies genau das sein, wonach wir suchen, insbesondere wenn wir Funktionen erstellen, die andere Dienste aufrufen. Was aber, wenn ich eine Hilfsfunktion erstellen möchte, um eine Berechnung durchzuführen und den Wert zurückzugeben, damit ich ihn an anderer Stelle verwenden kann?
|
||||
|
||||
Wir können dies tun, indem wir einen **Rückgabewert** verwenden. Ein Rückgabewert wird von der Funktion zurückgegeben und kann in einer Variablen genauso gespeichert werden, wie wir einen Literalwert wie eine Zeichenfolge oder eine Zahl speichern könnten.
|
||||
|
||||
Wenn eine Funktion etwas zurückgibt, wird das Schlüsselwort `return` verwendet. Das Schlüsselwort `return` erwartet einen Wert oder eine Referenz dessen, was wie folgt zurückgegeben wird:
|
||||
|
||||
|
||||
```javascript
|
||||
return myVariable;
|
||||
```
|
||||
|
||||
Wir könnten eine Funktion erstellen, um eine Begrüßungsnachricht zu erstellen und den Wert an den Anrufer zurückzugeben:
|
||||
|
||||
```javascript
|
||||
function createGreetingMessage(name) {
|
||||
const message = `Hello, ${name}`;
|
||||
return message;
|
||||
}
|
||||
```
|
||||
|
||||
Beim Aufruf dieser Funktion speichern wir den Wert in einer Variablen. Dies ist fast die gleiche Art und Weise, wie wir eine Variable auf einen statischen Wert setzen würden (wie `const name = 'Christopher'`).
|
||||
|
||||
```javascript
|
||||
const greetingMessage = createGreetingMessage('Christopher');
|
||||
```
|
||||
|
||||
## Funktionen als Parameter für Funktionen
|
||||
|
||||
Im Laufe Ihrer Programmierkarriere werden Sie auf Funktionen stoßen, die Funktionen als Parameter akzeptieren. Dieser nette Trick wird häufig verwendet, wenn wir nicht wissen, wann etwas eintreten oder abgeschlossen sein wird, aber wir wissen, dass wir als Reaktion darauf eine Operation ausführen müssen.
|
||||
|
||||
Betrachten Sie als Beispiel [setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout), das einen Timer startet und nach dessen Ausführung Code ausführt. Wir müssen ihm sagen, welchen Code wir ausführen wollen. Klingt nach einem perfekten Job für eine Veranstaltung!
|
||||
|
||||
Wenn Sie den folgenden Code ausführen, wird nach 3 Sekunden die Meldung **3 Sekunden sind verstrichen** angezeigt.
|
||||
|
||||
|
||||
```javascript
|
||||
function displayDone() {
|
||||
console.log('3 seconds has elapsed');
|
||||
}
|
||||
// Der Timer-Wert wird in Millisekunden angegeben
|
||||
setTimeout(3000, displayDone);
|
||||
```
|
||||
|
||||
### Anonyme Funktionen
|
||||
|
||||
Schauen wir uns noch einmal an, was wir gebaut haben. Wir erstellen eine Funktion mit einem Namen, der einmal verwendet wird. Wenn unsere Anwendung komplexer wird, können wir uns vorstellen, viele Funktionen zu erstellen, die nur einmal aufgerufen werden. Das ist nicht ideal. Wie sich herausstellt, müssen wir nicht immer einen Namen angeben!
|
||||
|
||||
Wenn wir eine Funktion als Parameter übergeben, können wir die Erstellung einer Funktion im Voraus umgehen und stattdessen eine als Teil des Parameters erstellen. Wir verwenden das gleiche Schlüsselwort `function`, aber stattdessen erstellen wir es als Parameter.
|
||||
|
||||
Schreiben wir den obigen Code neu, um eine anonyme Funktion zu verwenden:
|
||||
|
||||
```javascript
|
||||
setTimeout(3000, function() {
|
||||
console.log('3 seconds has elapsed');
|
||||
});
|
||||
```
|
||||
|
||||
Wenn Sie unseren neuen Code ausführen, werden Sie feststellen, dass wir die gleichen Ergebnisse erhalten. Wir haben eine Funktion erstellt, mussten ihr aber keinen Namen geben!
|
||||
|
||||
### Fettpfeilfunktionen
|
||||
|
||||
Eine in vielen Programmiersprachen (einschließlich JavaScript) übliche Abkürzung ist die Möglichkeit, eine sogenannte **arrow** - oder **fat arrow** -Funktion zu verwenden. Es wird ein spezieller Indikator für `=>` verwendet, der wie ein Pfeil aussieht - daher der Name! Mit `=>` können wir das Schlüsselwort `function` überspringen.
|
||||
|
||||
Lassen Sie uns unseren Code noch einmal umschreiben, um eine Fettpfeilfunktion zu verwenden:
|
||||
|
||||
|
||||
```javascript
|
||||
setTimeout(3000, () => {
|
||||
console.log('3 seconds has elapsed');
|
||||
});
|
||||
```
|
||||
|
||||
### Wann wird jede Strategie angewendet?
|
||||
|
||||
Sie haben jetzt gesehen, dass wir drei Möglichkeiten haben, eine Funktion als Parameter zu übergeben, und fragen sich möglicherweise, wann sie jeweils verwendet werden sollen. Wenn Sie wissen, dass Sie die Funktion mehrmals verwenden, erstellen Sie sie wie gewohnt. Wenn Sie es nur für einen Ort verwenden, ist es im Allgemeinen am besten, eine anonyme Funktion zu verwenden. Ob Sie eine Fat-Arrow-Funktion oder die traditionellere `function` Syntax verwenden, liegt bei Ihnen, aber Sie werden feststellen, dass die meisten modernen Entwickler `=>` bevorzugen.
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Herausforderung
|
||||
|
||||
Können Sie den Unterschied zwischen Funktionen und Methoden in einem Satz artikulieren? Versuche es!
|
||||
|
||||
## [Quiz nach der Vorlesung](.github/post-lecture-quiz.md)
|
||||
|
||||
## Review & Selbststudium
|
||||
|
||||
Es lohnt sich, [etwas mehr über Pfeilfunktionen zu lesen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), da diese zunehmend in Codebasen verwendet werden. Üben Sie, eine Funktion zu schreiben und sie dann mit dieser Syntax neu zu schreiben.
|
||||
|
||||
## Zuordnung
|
||||
|
||||
[Spaß mit Funktionen](assignment.md)
|
99
js-basics/2-functions-methods/translations/README.es.md
Normal file
99
js-basics/2-functions-methods/translations/README.es.md
Normal file
@@ -0,0 +1,99 @@
|
||||
# Conceptos básicos de JavaScript: métodos y funciones
|
||||
|
||||
[](https://youtube.com/watch?v=XgKsD6Zwvlc "Métodos y funciones")
|
||||
|
||||
## [Pre-lecture prueba](.github/pre-lecture-quiz.md)
|
||||
|
||||
Cuando necesite su código para realizar una tarea, utilizará un método o una función. Analicemos las diferencias.
|
||||
|
||||
## Funciones
|
||||
|
||||
Una función es un bloque de código destinado a realizar una tarea. Usted crea una función usando la palabra clave `function`, un nombre, un conjunto de parámetros y la definición de la función también conocida como funciones _body_. La sintaxis de una función se parece a la siguiente:
|
||||
|
||||
```javascript
|
||||
function name(param, param2, param3) { // definición de función
|
||||
// definición de función/body
|
||||
}
|
||||
```
|
||||
|
||||
## Métodos
|
||||
|
||||
TODO
|
||||
|
||||
### Parámetro
|
||||
|
||||
Los parámetros se enumeran en la parte de definición entre paréntesis y están separados por comas así:
|
||||
|
||||
```javascript
|
||||
(param, param2, param3)
|
||||
```
|
||||
|
||||
### Parámetro
|
||||
|
||||
Cuerpo de función
|
||||
|
||||
Aquí define qué tarea debe realizar la función. Una función puede devolver algo o no. Si una función devuelve algo, entonces se usa la palabra clave `return`. La palabra clave `return` espera un valor o referencia de lo que se devuelve así:
|
||||
|
||||
|
||||
```javascript
|
||||
return myVariable;
|
||||
```
|
||||
|
||||
Un ejemplo más completo puede verse así:
|
||||
|
||||
```javascript
|
||||
function add(firstValue, secondValue) {
|
||||
let sum = firstValue + secondValue;
|
||||
return sum;
|
||||
}
|
||||
```
|
||||
|
||||
En el código anterior, se devuelve la variable `sum`.
|
||||
|
||||
### Invocación
|
||||
|
||||
Cuando _invocas_ una función, la llamas con 0...N conjuntos de argumentos. Los valores de los argumentos se vinculan a los parámetros correspondientes a su posición. El método `add()` introducido se puede invocar de la siguiente manera:
|
||||
|
||||
|
||||
```javascript
|
||||
let result = add(1, 3);
|
||||
console.log(result); // imprime 4
|
||||
```
|
||||
|
||||
Los argumentos `1` y `3` están vinculados a los parámetros `firstValue` y `secondValue` debido al orden en el que se definen los parámetros.
|
||||
|
||||
JavaScript es bastante flexible cuando se trata de invocaciones. No está obligado a proporcionar argumentos para todos los parámetros, el código se ejecutará de todos modos. Sin embargo, dependiendo de lo que le pase, es posible que el código no se comporte como se esperaba.
|
||||
|
||||
> Desafío, intente llamar al método `add()` así `add(1)` y vea qué sucede
|
||||
|
||||
### Valores predeterminados
|
||||
|
||||
También existe el concepto de _ valores predeterminados_ en los parámetros. Esto significa que si no se pasa un argumento a un parámetro durante la invocación, el parámetro asumirá el valor predeterminado. Considere el siguiente código usando un valor predeterminado:
|
||||
|
||||
|
||||
```javascript
|
||||
function add5(firstValue, secondValue = 5) {
|
||||
return firstValue + secondValue;
|
||||
}
|
||||
```
|
||||
|
||||
La invocación de la función anterior podría verse así:
|
||||
|
||||
```javascript
|
||||
add5 (4) // devuelve 9
|
||||
add5 (4,2) // devuelve 6
|
||||
```
|
||||
|
||||
Cualquier parámetro con valores predeterminados debe estar al final de la lista de parámetros. La razón es que JavaScript intenta hacer coincidir argumentos con parámetros y los parámetros con valores predeterminados pueden omitirse en la invocación.
|
||||
|
||||
🚀 Desafío:
|
||||
|
||||
|
||||
## [Post-lecture prueba](.github/post-lecture-quiz.md)
|
||||
|
||||
## Revisión y autoestudio
|
||||
|
||||
TODO
|
||||
|
||||
**Tarea**: [Práctica de tipos de datos](assignment.md)
|
||||
|
13
js-basics/2-functions-methods/translations/assignment.de.md
Normal file
13
js-basics/2-functions-methods/translations/assignment.de.md
Normal file
@@ -0,0 +1,13 @@
|
||||
# Spaß mit Funktionen
|
||||
|
||||
## Anleitung
|
||||
|
||||
Erstellen Sie verschiedene Funktionen, sowohl Funktionen, die etwas zurückgeben, als auch Funktionen, die nichts zurückgeben.
|
||||
|
||||
Überprüfen Sie, ob Sie eine Funktion erstellen können, die eine Mischung aus Parametern und Parametern mit Standardwerten enthält.
|
||||
|
||||
## Rubrik
|
||||
|
||||
| Kriterien | Vorbildlich | Angemessen | Verbesserungsbedarf |
|
||||
| -------- | -------------------------------------------------- ------------------------------------ | -------------------------------------------------- -------------- | ----------------- |
|
||||
| | Die Lösung wird mit zwei oder mehr leistungsfähigen Funktionen mit verschiedenen Parametern angeboten Arbeitslösung wird mit einer Funktion und wenigen Parametern angeboten Lösung hat Fehler |
|
13
js-basics/2-functions-methods/translations/assignment.es.md
Normal file
13
js-basics/2-functions-methods/translations/assignment.es.md
Normal file
@@ -0,0 +1,13 @@
|
||||
# Diversión con funciones
|
||||
|
||||
## Instrucciones
|
||||
|
||||
Cree diferentes funciones, tanto funciones que devuelvan algo como funciones que no devuelvan nada.
|
||||
|
||||
Vea si puede crear una función que tenga una combinación de parámetros y parámetros con valores predeterminados.
|
||||
|
||||
## Rúbrica
|
||||
|
||||
| Criterios | Ejemplar | Adecuado | Necesita mejorar |
|
||||
| -------- | -------------------------------------------------- ------------------------------------ | -------------------------------------------------- -------------- | ----------------- |
|
||||
| | La solución se ofrece con dos o más funciones de buen rendimiento con diversos parámetros | La solución de trabajo se ofrece con una función y pocos parámetros | La solución tiene errores |
|
Reference in New Issue
Block a user