folder names

This commit is contained in:
Jen Looper
2020-11-09 22:51:04 -05:00
parent 33e5d5f777
commit 1d81829ac1
367 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,18 @@
*Complete this quiz after the lesson by checking one answer per question.*
1. Constants are the same as `let` and `var` to declare variables except
- [ ] Constants must be initialized
- [ ] Constants can be altered
- [ ] Constants can be reassigned
2. Numbers and ____ are JavaScript primitives that handle numeric data
- [ ] bigint
- [ ] boolean
- [ ] star
3. Strings can reside between both single and double quotes
- [ ] true
- [ ] false

View File

@@ -0,0 +1,17 @@
*Complete this quiz in class*
1. Booleans are a data type you can use to test the length of a string
- [ ] true
- [ ] false
1. The following is an operation you can perform on a string
- [ ] concatenation
- [ ] appending
- [ ] splicing
3. `==` and `===` are interchangeable
- [ ] true
- [ ] false

View File

@@ -0,0 +1,194 @@
# JavaScript Basics: Data Types
[![Data types in JavaScript](https://img.youtube.com/vi/JNIXfGiDWM8/0.jpg)](https://youtube.com/watch?v=JNIXfGiDWM8 "Data types in JavaScript")
![JavaScript Basics - Data types](images/webdev101-js-datatypes.png)
> Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac)
## [Pre-lecture quiz](.github/pre-lecture-quiz.md)
This lesson covers the basics of JavaScript, the language that provides interactivity on the web.
Let's start with variables and the data types that populate them!
## Variables
Variables store values that can be used and changed throughout your code.
Creating and **declaring** a variable has the following syntax **[keyword] [name]**. It's made up of the two parts:
- **Keyword**. Keywords can be `let` or `var`.
> Note, They keyword `let` was introduced in ES6 and gives your variable a so called _block scope_. It's recommended that you use `let` over `var`. We will cover block scopes more in depth in future parts.
- **The variable name**, this is a name you choose yourself.
### Task - working with variables
1. **Declare a variable**. Let's declare a variable using the `let` keyword:
```javascript
let myVariable;
```
`myVariable` has now been declared using the `let` keyword. It currently doesn't have a value.
1. **Assign a value**. Store a value in a variable with the `=` operator, followed by the expected value.
```javascript
myVariable = 123;
```
> Note: the use of `=` in this lesson means we make use of an "assignment operator", used to set a value to a variable. It doesn't denote equality.
`myVariable` has now been *initialized* with the value 123.
1. **Refactor**. Replace your code with the following statement.
```javascript
let myVariable = 123;
```
The above is called an _explicit initialization_ when a variable is declared and is assigned a value at the same time.
1. **Change the variable value**. Change the variable value in the following way:
```javascript
myVariable = 321;
```
Once a variable is declared, you can change its value at any point in your code with the `=` operator and the new value.
✅ Try it! You can write JavaScript right in your browser. Open a browser window and navigate to Developer Tools. In the console, you will find a prompt; type `let myVariable = 123`, press return, then type `myVariable`. What happens? Note, you'll learn more about these concepts in subsequent lessons.
## Constants
Declaration and initialization of a constant follows the same concepts as a variable, with the exception of the `const` keyword. Constants are typically declared with all uppercase letters.
```javascript
const MY_VARIABLE = 123;
```
Constants are similar to variables, with two exceptions:
- **Must have a value**. Constants must be initialized, or an error will occur when running code.
- **Reference cannot be changed**. The reference of a constant cannot be changed once initialized, or an error will occur when running code. Let's look at two examples:
- **Simple value**. The following is NOT allowed:
```javascript
const PI = 3;
PI = 4; // not allowed
```
- **Object reference is protected**. The following is NOT allowed.
```javascript
const obj = { a: 3 };
obj = { b: 5 } // not allowed
```
- **Object value is not protected**. The following IS allowed:
```javascript
const obj = { a: 3 };
obj.a = 5; // allowed
```
Above you are changing the value of the object but not the reference itself, which makes it allowed.
> Note, a `const` means the reference is protected from reassignment. The value is not _immutable_ though and can change, especially if it's a complex construct like an object.
## Data Types
Variables can store many different types of values, like numbers and text. These various types of values are known as the **data type**. Data types are an important part of software development because it helps developers make decisions on how the code should be written and how the software should run. Furthermore, some data types have unique features that help transform or extract additional information in a value.
✅ Data Types are also referred to as JavaScript data primitives, as they are the lowest-level data types that are provided by the language. There are 6 primitive data types: string, number, bigint, boolean, undefined, and symbol. Take a minute to visualize what each of these primitives might represent. What is a `zebra`? How about `0`? `true`?
### Numbers
In the previous section, the value of `myVariable` was a number data type.
`let myVariable = 123;`
Variables can store all types of numbers, including decimals or negative numbers. Numbers also can be used with arithmetic operators, covered in the [next section](#operators).
### Arithmetic Operators
There are several types of operators to use when performing arithmetic functions, and some are listed here:
| Symbol | Description | Example |
| ------ | ------------------------------------------------------------------------ | -------------------------------- |
| `+` | **Addition**: Calculates the sum of two numbers | `1 + 2 //expected answer is 3` |
| `-` | **Subtraction**: Calculates the difference of two numbers | `1 - 2 //expected answer is -1` |
| `*` | **Multiplication**: Calculates the product of two numbers | `1 * 2 //expected answer is 2` |
| `/` | **Division**: Calculates the quotient of two numbers | `1 / 2 //expected answer is 0.5` |
| `%` | **Remainder**: Calculates the remainder from the division of two numbers | `1 % 2 //expected answer is 1` |
✅ Try it! Try an arithmetic operation in your browser's console. Do the results surprise you?
### Strings
Strings are sets of characters that reside between single or double quotes.
- `'This is a string'`
- `"This is also a string"`
- `let myString = 'This is a string value stored in a variable';`
Remember to use quotes when writing a string, or else JavaScript will assume it's a variable name.
### Formatting Strings
Strings are textual, and will require formatting from time to time.
To **concatenate** two or more strings, or join them together, use the `+` operator.
```javascript
let myString1 = "Hello";
let myString2 = "World";
myString1 + myString2 + "!"; //HelloWorld!
myString1 + " " + myString2 + "!"; //Hello World!
myString1 + ", " + myString2 + "!"; //Hello, World!
```
✅ Why does `1 + 1 = 2` in JavaScript, but `'1' + '1' = 11?` Think about it. What about `'1' + 1`?
**Template literals** are another way to format strings, except instead of quotes, the backtick is used. Anything that is not plain text must be placed inside placeholders `${ }`. This includes any variables that may be strings.
```javascript
let myString1 = "Hello";
let myString2 = "World";
`${myString1} ${myString2}!` //Hello World!
`${myString1}, ${myString2}!` //Hello World!
```
You can achieve your formatting goals with either method, but template literals will respect any spaces and line breaks.
✅ When would you use a template literal vs. a plain string?
### Booleans
Booleans can be only two values: `true` or `false`. Booleans can help make decisions on which lines of code should run when certain conditions are met. In many cases, [operators](#operators) assist with setting the value of a Boolean and you will often notice and write variables being initialized or their values being updated with an operator.
- `let myTrueBool = true`
- `let myFalseBool = false`
✅ A variable can be considered 'truthy' if it evaluates to a boolean `true`. Interestingly, in JavaScript, [all values are truthy unless defined as falsy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy).
---
## 🚀 Challenge
JavaScript is notorious for its surprising ways of handling datatypes on occasion. Do a bit of research on these 'gotchas'. For example: case sensitivity can bite! Try this in your console: `let age = 1; let Age = 2; age == Age` (resolves `false` -- why?). What other gotchas can you find?
## [Post-lecture quiz](.github/post-lecture-quiz.md)
## Review & Self Study
Take a look at [this list of JavaScript exercises](https://css-tricks.com/snippets/javascript/) and try one. What did you learn?
## Assignment
[Data Types Practice](assignment.md)

View File

@@ -0,0 +1,11 @@
# Data Types Practice
## Instructions
Imagine you are building a shopping cart. Write some documentation on the data types that you would need to complete your shopping experience. How did you arrive at your choices?
## Rubric
Criteria | Exemplary | Adequate | Needs Improvement
--- | --- | --- | -- |
||The six data types are listed and explored in detail, documenting their use|Four datatypes are explored|Two data types are explored|

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

View File

@@ -0,0 +1,197 @@
# JavaScript-Grundlagen: Datentypen
[![Datentypen in JavaScript](https://img.youtube.com/vi/JNIXfGiDWM8/0.jpg)](https://youtube.com/watch?v=JNIXfGiDWM8 "Datentypen in JavaScript")
## [Pre-Lecture Quiz](.github/pre-lecture-quiz.md)
Diese Lektion behandelt die Grundlagen von JavaScript, der Sprache, die Interaktivität im Web bietet.
Beginnen wir mit Variablen und den Datentypen, die sie füllen!
## Variablen
Variablen speichern Werte, die im gesamten Code verwendet und geändert werden können.
Das Erstellen und **Deklarieren** einer Variablen hat die folgende Syntax **[keyword] [name]**. Es besteht aus zwei Teilen:
- **Keyword**. Schlüsselwörter können `let` oder `var` sein.
> Hinweis: Das Schlüsselwort `let` wurde in ES6 eingeführt und gibt Ihrer Variablen einen sogenannten "Block Scope". Es wird empfohlen, `let` over` var` zu verwenden. Wir werden uns in zukünftigen Teilen eingehender mit Blockbereichen befassen.
- **Der Variablenname**, dies ist ein Name, den Sie selbst wählen.
### Aufgabe - Arbeiten mit Variablen
1. **Deklariere eine Variable**. Deklarieren wir eine Variable mit dem Schlüsselwort `let`:
```javascript
let myVariable;
```
`myVariable` wurde jetzt mit dem Schlüsselwort `let` deklariert. Es hat derzeit keinen Wert.
1. **Weisen Sie einen Wert zu**. Speichern Sie einen Wert in einer Variablen mit dem Operator `=`, gefolgt vom erwarteten Wert.
```javascript
myVariable = 123;
```
> Hinweis: Die Verwendung von `=` in dieser Lektion bedeutet, dass wir einen "Zuweisungsoperator" verwenden, mit dem ein Wert auf eine Variable gesetzt wird. Es bedeutet nicht Gleichheit.
`myVariable` wurde jetzt mit dem Wert 123 *initialisiert*.
1. **Refactor**. Ersetzen Sie Ihren Code durch die folgende Anweisung.
```javascript
let myVariable = 123;
```
Das Obige wird als _explizite Initialisierung_ bezeichnet, wenn eine Variable deklariert und gleichzeitig ein Wert zugewiesen wird.
1. **Ändern Sie den Variablenwert**. Ändern Sie den Variablenwert folgendermaßen:
```javascript
myVariable = 321;
```
Sobald eine Variable deklariert ist, können Sie ihren Wert an jeder Stelle in Ihrem Code mit dem Operator `=` und dem neuen Wert ändern.
✅ Probieren Sie es aus! Sie können JavaScript direkt in Ihren Browser schreiben. Öffnen Sie ein Browserfenster und navigieren Sie zu Developer Tools. In der Konsole finden Sie eine Eingabeaufforderung. Geben Sie `let myVariable = 123` ein, drücken Sie die Eingabetaste und geben Sie `myVariable` ein. Was geschieht? Beachten Sie, dass Sie in den folgenden Lektionen mehr über diese Konzepte erfahren werden.
## Konstanten
Die Deklaration und Initialisierung einer Konstante folgt denselben Konzepten wie eine Variable, mit Ausnahme des Schlüsselworts `const`. Konstanten werden normalerweise mit allen Großbuchstaben deklariert.
```javascript
const MY_VARIABLE = 123;
```
Konstanten ähneln Variablen mit zwei Ausnahmen:
- **Muss einen Wert haben**. Konstanten müssen initialisiert werden, sonst tritt beim Ausführen von Code ein Fehler auf.
- **Referenz kann nicht geändert werden**. Die Referenz einer Konstante kann nach der Initialisierung nicht mehr geändert werden. Andernfalls tritt beim Ausführen von Code ein Fehler auf. Schauen wir uns zwei Beispiele an:
- **Einfacher Wert**. Folgendes ist NICHT erlaubt:
```javascript
const PI = 3;
PI = 4; // not allowed
```
- **Objektreferenz ist geschützt**. Folgendes ist NICHT erlaubt.
```javascript
const obj = { a: 3 };
obj = { b: 5 } // not allowed
```
- **Objektwert ist nicht geschützt**. Folgendes ist erlaubt:
```javascript
const obj = { a: 3 };
obj.a = 5; // allowed
```
Oben ändern Sie den Wert des Objekts, aber nicht die Referenz selbst, wodurch es zulässig wird.
> Beachten Sie, dass ein `const` bedeutet, dass die Referenz vor einer Neuzuweisung geschützt ist. Der Wert ist jedoch nicht änderbar und kann sich ändern, insbesondere wenn es sich um ein komplexes Konstrukt wie ein Objekt handelt.
## Datentypen
Variablen können viele verschiedene Arten von Werten wie Zahlen und Text speichern. Diese verschiedenen Arten von Werten werden als **Datentyp** bezeichnet. Datentypen sind ein wichtiger Bestandteil der Softwareentwicklung, da sie Entwicklern helfen, Entscheidungen darüber zu treffen, wie der Code geschrieben und wie die Software ausgeführt werden soll. Darüber hinaus verfügen einige Datentypen über einzigartige Funktionen, mit denen zusätzliche Informationen in einen Wert umgewandelt oder extrahiert werden können.
✅ Datentypen werden auch als JavaScript-Datenprimitive bezeichnet, da es sich um die Datentypen der niedrigsten Ebene handelt, die von der Sprache bereitgestellt werden. Es gibt 6 primitive Datentypen: Zeichenfolge, Zahl, Bigint, Boolescher Wert, undefiniert und Symbol. Nehmen Sie sich eine Minute Zeit, um zu visualisieren, was jedes dieser Grundelemente darstellen könnte. Was ist ein `zebra`? Wie wäre es mit `0`? `true`?
### Zahlen
Im vorherigen Abschnitt war der Wert von `myVariable` ein Datentyp für Zahlen.
`let myVariable = 123;`
Variablen können alle Arten von Zahlen speichern, einschließlich Dezimalstellen oder negativer Zahlen. Zahlen können auch mit arithmetischen Operatoren verwendet werden, die im [nächsten Abschnitt](#operators) behandelt werden.
### Rechenzeichen
Es gibt verschiedene Arten von Operatoren, die beim Ausführen von arithmetischen Funktionen verwendet werden können. Einige sind hier aufgeführt:
| Symbol | Beschreibung | Beispiel |
| ------ | -------------------------------------------------- ---------------------- | -------------------------------- |
| `+` | **Addition**: Berechnet die Summe zweier Zahlen | `1 + 2 // erwartete Antwort ist 3` |
| `-` | **Subtraktion**: Berechnet die Differenz zweier Zahlen | `1 - 2 // erwartete Antwort ist -1` |
| `*` | **Multiplikation**: Berechnet das Produkt zweier Zahlen | `1 * 2 // erwartete Antwort ist 2` |
| `/` | **Division**: Berechnet den Quotienten aus zwei Zahlen | `1/2 // erwartete Antwort ist 0.5` |
| %% | **Rest**: Berechnet den Rest aus der Division zweier Zahlen | `1 % 2 // erwartete Antwort ist 1` |
✅ Probieren Sie es aus! Versuchen Sie eine arithmetische Operation in der Konsole Ihres Browsers. Überraschen Sie die Ergebnisse?
### Strings
Zeichenfolgen sind Zeichensätze, die zwischen einfachen oder doppelten Anführungszeichen stehen.
- `'Das ist eine Saite'`
- `"Dies ist auch eine Zeichenfolge"`
- `let myString = 'Dies ist ein in einer Variablen gespeicherter Zeichenfolgenwert';`
Denken Sie daran, beim Schreiben einer Zeichenfolge Anführungszeichen zu verwenden. Andernfalls geht JavaScript davon aus, dass es sich um einen Variablennamen handelt.
### Formatieren von Zeichenfolgen
Zeichenfolgen sind Textzeichenfolgen und müssen von Zeit zu Zeit formatiert werden.
Verwenden Sie den Operator `+`, um zwei oder mehr Zeichenfolgen zu **verketten** oder miteinander zu verbinden.
```javascript
let myString1 = "Hello";
let myString2 = "World";
myString1 + myString2 + "!"; //HelloWorld!
myString1 + " " + myString2 + "!"; //Hello World!
myString1 + ", " + myString2 + "!"; //Hello, World!
```
.
✅ Warum ist in JavaScript `1 + 1 = 2`, aber `'1' + '1' = 11?` Denken Sie darüber nach. Was ist mit `'1' + 1`?
** Vorlagenliterale ** sind eine weitere Möglichkeit, Zeichenfolgen zu formatieren, außer dass anstelle von Anführungszeichen das Backtick verwendet wird. Alles, was kein einfacher Text ist, muss in die Platzhalter `${ }` eingefügt werden. Dies schließt alle Variablen ein, die Zeichenfolgen sein können.
```javascript
let myString1 = "Hello";
let myString2 = "World";
`${myString1} ${myString2}!` //Hello World!
`${myString1}, ${myString2}!` //Hello World!
```
Sie können Ihre Formatierungsziele mit beiden Methoden erreichen, aber Vorlagenliterale berücksichtigen alle Leerzeichen und Zeilenumbrüche.
✅ Wann würden Sie ein Vorlagenliteral im Vergleich zu einer einfachen Zeichenfolge verwenden?
### Boolesche Werte
Boolesche Werte können nur zwei Werte sein: `true` oder `false`. Boolesche Werte können dabei helfen, Entscheidungen darüber zu treffen, welche Codezeilen ausgeführt werden sollen, wenn bestimmte Bedingungen erfüllt sind. In vielen Fällen helfen [Operatoren](#operators) beim Festlegen des Werts eines Booleschen Werts, und Sie werden häufig feststellen und schreiben, dass Variablen initialisiert oder ihre Werte mit einem Operator aktualisiert werden.
- `let myTrueBool = true`
- `let myFalseBool = false`
✅ Eine Variable kann als "wahr" betrachtet werden, wenn sie als boolescher Wert "wahr" ausgewertet wird. Interessanterweise sind in JavaScript [alle Werte wahr, sofern sie nicht als falsch definiert sind](https://developer.mozilla.org/en-US/docs/Glossary/Truthy).
--- ---.
## 🚀 Herausforderung
JavaScript ist bekannt für seine überraschende Art, gelegentlich mit Datentypen umzugehen. Recherchiere ein bisschen über diese 'Fallstricke'. Zum Beispiel: Groß- und Kleinschreibung kann beißen! Versuchen Sie dies in Ihrer Konsole: `let age = 1; let Age = 2; age == Age` (löst `false` auf - warum?). Welche anderen Fallstricke können Sie finden?
## [Quiz nach der Vorlesung](.github/post-lecture-quiz.md)
## Review & Selbststudium
Schauen Sie sich [diese Liste der JavaScript-Übungen](https://css-tricks.com/snippets/javascript/) an und probieren Sie eine aus. Was hast du gelernt?
## Zuordnung
[Praxis für Datentypen](assignment.md)

View File

@@ -0,0 +1,187 @@
# Conceptos básicos de JavaScript: tipos de datos
[![Tipos de datos en JavaScript](https://img.youtube.com/vi/rEHV3fFMfn0/0.jpg)](https://youtube.com/watch?v=rEHV3fFMfn0 "Tipos de datos en JavaScript")
## [Pre-lecture prueba](.github/pre-lecture-quiz.md)
Esta lección cubre los conceptos básicos de JavaScript, el lenguaje que proporciona interactividad en la web.
¡Comencemos con las variables y los tipos de datos que las pueblan!
## Variables
Las variables almacenan valores que se pueden usar y cambiar a lo largo de su código.
Crear y **declarar** una variable tiene la siguiente sintaxis **[keyword] [name]**. Está compuesto por dos partes:
- **Keyword**. Las palabras clave pueden ser `let` o `var`.
> Tenga en cuenta que la palabra clave `let` se introdujo en ES6 y le da a su variable un llamado _alcance de bloque_ (block scope). Se recomienda utilizar `let` sobre `var`. Cubriremos los alcances de bloque con más profundidad en partes futuras.
- **El nombre de la variable**, este es un nombre que elige usted mismo.
### Tarea - trabajar con variables
1. **Declare una variable**. Declaremos una variable usando la palabra clave `let`:
```javascript
let myVariable;
```
`myVariable` ahora se ha declarado usando la palabra clave `let`. Actualmente no tiene ningún valor.
1. **Asignar un valor**. Almacene un valor en una variable con el operador `=`, seguido del valor esperado.
```javascript
myVariable = 123;
```
> Nota: el uso de `=` en esta lección significa que hacemos uso de un "operador de asignación", que se utiliza para establecer un valor en una variable. No denota igualdad.
`myVariable` ahora se ha *inicializado* con el valor 123.
1. **Refactor**. Reemplace su código con la siguiente declaración.
```javascript
let myVariable = 123;
```
Lo anterior se denomina _inicialización explícita_ cuando se declara una variable y se le asigna un valor al mismo tiempo.
1. **Cambiar el valor de la variable**. Cambie el valor de la variable de la siguiente manera:
```javascript
myVariable = 321;
```
Una vez que se declara una variable, puede cambiar su valor en cualquier punto de su código con el operador `=` y el nuevo valor.
✅ ¡Pruébalo! Puede escribir JavaScript directamente en su navegador. Abra una ventana del navegador y navegue hasta Herramientas de desarrollo. En la consola, encontrará un mensaje; escriba `let myVariable = 123`, presione retorno, luego escriba `myVariable`. ¿Lo que pasa? Tenga en cuenta que aprenderá más sobre estos conceptos en lecciones posteriores.
## Constantes
La declaración e inicialización de una constante sigue los mismos conceptos que una variable, con la excepción de la palabra clave `const`. Las constantes se declaran normalmente con todas las letras mayúsculas.
```javascript
const MY_VARIABLE = 123;
```
CLas constantes son similares a las variables, con dos excepciones:
- **Debe tener un valor**. Las constantes deben inicializarse o se producirá un error al ejecutar el código.
- **La referencia no se puede cambiar**. La referencia de una constante no se puede cambiar una vez inicializada, o se producirá un error al ejecutar el código. Veamos dos ejemplos:
- **Valor simple**. NO se permite lo siguiente:
```javascript
const PI = 3;
PI = 4; // no permitido
```
- **La referencia de objeto está protegida**. NO se permite lo siguiente.
```javascript
const obj = { a: 3 };
obj = { b: 5 } // o permitido
```
- **El valor del objeto no está protegido**. Se permite lo siguiente:
```javascript
const obj = { a: 3 };
obj.a = 5; // permitido
```
Arriba está cambiando el valor del objeto pero no la referencia en sí, lo que lo permite.
> Tenga en cuenta que una `const` significa que la referencia está protegida contra la reasignación. Sin embargo, el valor no es _immutable_ y puede cambiar, especialmente si es una construcción compleja como un objeto.
## Tipos de datos
Las variables pueden almacenar muchos tipos diferentes de valores, como números y texto. Estos diversos tipos de valores se conocen como **tipo de datos**. Los tipos de datos son una parte importante del desarrollo de software porque ayudan a los desarrolladores a tomar decisiones sobre cómo se debe escribir el código y cómo se debe ejecutar el software. Además, algunos tipos de datos tienen características únicas que ayudan a transformar o extraer información adicional en un valor.
✅ Los tipos de datos también se conocen como primitivas de datos de JavaScript, ya que son los tipos de datos de nivel más bajo que proporciona el lenguaje. Hay 6 tipos de datos primitivos: cadena, número, bigint, booleano, indefinido y símbolo. Tómese un minuto para visualizar lo que podría representar cada una de estas primitivas. ¿Qué es una `cebra`? ¿Qué tal `0`? ¿`true`?
### Números
En la sección anterior, el valor de "myVariable" era un tipo de datos numérico.
`let myVariable = 123;`
Las variables pueden almacenar todo tipo de números, incluidos decimales o números negativos. Los números también se pueden usar con operadores aritméticos, que se tratan en la [siguiente sección] (# operadores).
### Operadores aritméticos
Hay varios tipos de operadores que se pueden utilizar al realizar funciones aritméticas, y algunos se enumeran aquí:
| Símbolo | Descripción | Ejemplo |
| ------- | ------------------------------------------------------------------------ | -------------------------------------- |
| `+` | **Suma**: Calcula la suma de dos números | `1 + 2 //la respuesta esperada es 3` |
| `-` | **Resta**: Calcula la diferencia de dos números | `1 - 2 //la respuesta esperada es -1` |
| `*` | **Multiplicación**: Calcula el producto de dos números | `1 * 2 //la respuesta esperada es 2` |
| `/` | **División**: Calcula el cociente de dos números | `1 / 2 //la respuesta esperada es 0.5` |
| `%` | **Resto**: Calcula el resto a partir de la división de dos números | `1 % 2 //la respuesta esperada es 1` |
✅ ¡Pruébalo! Pruebe una operación aritmética en la consola de su navegador. ¿Te sorprenden los resultados?
### Cadenas
Las cadenas son conjuntos de caracteres que residen entre comillas simples o dobles.
- `'Esto es una cadena'`
- `"Esto también es una cadena"`
- `let myString = 'Este es un valor de cadena almacenado en una variable';`
Recuerde utilizar comillas al escribir una cadena, de lo contrario JavaScript asumirá que es un nombre de variable.
### Formateo de cadenas
Las cadenas son textuales y requerirán formato de vez en cuando.
Para **concatenar** dos o más cadenas, o unirlas, use el operador `+`.
```javascript
let myString1 = "Hello";
let myString2 = "World";
myString1 + myString2 + "!"; //HelloWorld!
myString1 + " " + myString2 + "!"; //Hello World!
myString1 + ", " + myString2 + "!"; //Hello, World!
```
✅ ¿Por qué `1 + 1 = 2` en JavaScript, pero `'1' + '1' = 11?` Piense en ello. ¿Qué pasa con `'1' + 1`?
** Los literales de plantilla ** son otra forma de formatear cadenas, excepto que en lugar de comillas, se usa la comilla invertida. Todo lo que no sea texto sin formato debe colocarse dentro de los marcadores de posición `${ }`. Esto incluye cualquier variable que pueda ser cadenas.
```javascript
let myString1 = "Hello";
let myString2 = "World";
`${myString1} ${myString2}!` //Hello World!
`${myString1}, ${myString2}!` //Hello World!
```
Puede lograr sus objetivos de formato con cualquier método, pero los literales de plantilla respetarán los espacios y saltos de línea.
✅ ¿Cuándo usaría una plantilla literal frente a una cadena simple?
### Booleanos
Los booleanos pueden tener solo dos valores: `true` o `false`. Los valores booleanos pueden ayudar a tomar decisiones sobre qué líneas de código deben ejecutarse cuando se cumplen ciertas condiciones. En muchos casos, [operadores](#operadores) ayudan a establecer el valor de un booleano y, a menudo, notará y escribirá variables que se inicializan o que sus valores se actualizan con un operador.
- `let myTrueBool = true`
- `let myFalseBool = false`
✅ Una variable se puede considerar 'verdadera' si se evalúa como un valor booleano 'verdadero'. Curiosamente, en JavaScript, [todos los valores son verdaderos a menos que se definan como falsos](https://developer.mozilla.org/en-US/docs/Glossary/Truthy).
🚀 Desafío: JavaScript es conocido por sus sorprendentes formas de manejar tipos de datos en ocasiones. Investiga un poco sobre estos "errores". Por ejemplo: ¡la sensibilidad a mayúsculas y minúsculas puede morder! Pruebe esto en su consola: `let age = 1; let Age = 2; age == Age` (resuelve `false` - ¿por qué?). ¿Qué otras trampas puedes encontrar?
## [Post-lecture prueba](.github/post-lecture-quiz.md)
## Revisión y autoestudio
Eche un vistazo a [esta lista de ejercicios de JavaScript](https://css-tricks.com/snippets/javascript/) y pruebe uno. ¿Qué aprendiste?
**Tarea**: [Práctica de tipos de datos](assignment.md)

View File

@@ -0,0 +1,11 @@
# Datentypen üben
## Anleitung
Stellen Sie sich vor, Sie bauen einen Einkaufswagen. Schreiben Sie eine Dokumentation zu den Datentypen, die Sie benötigen, um Ihr Einkaufserlebnis zu vervollständigen. Wie sind Sie zu Ihren Entscheidungen gekommen?
## Rubrik
Kriterien | Vorbildlich | Angemessen | Muss verbessert werden
--- | --- | --- | - |
|| Die sechs Datentypen werden aufgelistet und detailliert untersucht, wobei ihre Verwendung dokumentiert wird. | Vier Datentypen werden untersucht. | Zwei Datentypen werden untersucht. |

View File

@@ -0,0 +1,11 @@
# Práctica de tipos de datos
## Instrucciones
Imagina que estás construyendo un carrito de compras. Escriba documentación sobre los tipos de datos que necesitaría para completar su experiencia de compra. ¿Cómo llegó a sus elecciones?
## Rúbrica
Criterios | Ejemplar | Adecuado | Necesita mejorar
--- | --- | --- | - |
|| Los seis tipos de datos se enumeran y exploran en detalle, documentando su uso | Se exploran cuatro tipos de datos | Se exploran dos tipos de datos |

View 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

View 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

View File

@@ -0,0 +1,190 @@
# JavaScript Basics: Methods and Functions
[![Methods and Functions](https://img.youtube.com/vi/XgKsD6Zwvlc/0.jpg)](https://youtube.com/watch?v=XgKsD6Zwvlc "Methods and Functions")
![JavaScript Basics - Functions](images/webdev101-js-functions.png)
> 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)

View 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 |

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

View File

@@ -0,0 +1,195 @@
# JavaScript-Grundlagen: Methoden und Funktionen
[![Methoden und Funktionen](https://img.youtube.com/vi/XgKsD6Zwvlc/0.jpg)](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)

View File

@@ -0,0 +1,99 @@
# Conceptos básicos de JavaScript: métodos y funciones
[![Métodos y funciones](https://img.youtube.com/vi/XgKsD6Zwvlc/0.jpg)](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)

View 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 |

View 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 |

View File

@@ -0,0 +1,12 @@
*Complete this quiz by checking one answer per question.*
1. What would the following code return: `'1' == 1`
- [ ] true
- [ ] false
2. Choose the correct operator to express _or_ logic
- [ ] `a | b`
- [ ] `a || b`
- [ ] `a or b`

View File

@@ -0,0 +1,13 @@
*Complete this quiz in class*
1. The following operator `==` is called
- [ ] Equality
- [ ] Strict equality
- [ ] Assignment
2. A comparison in JavaScript returns what type?
- [ ] boolean
- [ ] null
- [ ] string

View File

@@ -0,0 +1,166 @@
# JavaScript Basics: Making Decisions
[![Making Decisions](https://img.youtube.com/vi/SxTp8j-fMMY/0.jpg)](https://youtube.com/watch?v=SxTp8j-fMMY "Making Decisions")
## [Pre-lecture quiz](.github/pre-lecture-quiz.md)
Making decisions and controlling the order in which your code runs makes your code reusable and robust. This section covers the syntax for controlling data flow in JavaScript and its significance when used with Boolean data types
## A Brief Recap on Booleans
Booleans can be only two values: `true` or `false`. Booleans help make decisions on which lines of code should run when certain conditions are met.
Set your boolean to be true or false like this:
`let myTrueBool = true`
`let myFalseBool = false`
✅ Booleans are named after the English mathematician, philosopher and logician George Boole (18151864).
## Comparison Operators and Booleans
Operators are used to evaluate conditions by making comparisons that will create a Boolean value. The following is a list of operators that are frequently used.
| Symbol | Description | Example |
| ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ |
| `<` | **Greater than**: Compares two values and returns the `true` Boolean data type if the value on the right side is larger than the left | `5 < 6 // true` |
| `<=` | **Greater than or equal to**: Compares two values and returns the `true` Boolean data type if the value on the right side is larger than or equal to the left | `5 <= 6 // true` |
| `>` | **Less than**: Compares two values and returns the `true` Boolean data type if the value on the left side is larger than the right | `5 > 6 // false` |
| `=>` | **Less than or equal to**: Compares two values and returns the `true` Boolean data type if the value on the left side is larger than or equal to the right | `5 => 6 // false` |
| `===` | **Strict equality**: Compares two values and returns the `true` Boolean data type if values on the right and left are equal AND are the same data type. | `5 === 6 // false` |
| `!==` | **Inequality**: Compares two values and returns the opposite Boolean value of what a strict equality operator would return | `5 !== 6 // true` |
✅ Check your knowledge by writing some comparisons in your browser's console. Does any returned data surprise you?
## If Statement
The if statement will run code in between its blocks if the condition is true.
```javascript
if (condition){
//Condition was true. Code in this block will run.
}
```
Logical operators are often used to form the condition.
```javascript
let currentMoney;
let laptopPrice;
if (currentMoney >= laptopPrice){
//Condition was true. Code in this block will run.
console.log("Getting a new laptop!");
}
```
## IF..Else Statement
The `else` statement will run the code in between its blocks when the condition is false. It's optional with an `if` statement.
```javascript
let currentMoney;
let laptopPrice;
if (currentMoney >= laptopPrice){
//Condition was true. Code in this block will run.
console.log("Getting a new laptop!");
}
else{
//Condition was true. Code in this block will run.
console.log("Can't afford a new laptop, yet!");
}
```
✅ Test your understanding of this code and the following code by running it in a browser console. Change the values of the currentMoney and laptopPrice variables to change the returned `console.log()`.
## Logical Operators and Booleans
Decisions might require more than one comparison, and can be strung together with logical operators to produce a Boolean value.
| Symbol | Description | Example |
| ------ | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| `&&` | **Logical AND**: Compares two Boolean expressions. Returns true **only** if both sides are true | `(5 > 6) && (5 < 6 ) //One side is false, other is true. Returns false` |
| `||` | **Logical OR**: Compares two Boolean expressions. Returns true if at least one side is true | `(5 > 6) || (5 < 6) //One side is false, other is true. Returns true` |
| `!` | **Logical NOT**: Returns the opposite value of a Boolean expression | `!(5 > 6) // 5 is not greater than 6, but "!" will return true` |
## Conditions and Decisions with Logical Operators
Logical operators can be used to form conditions in if..else statements.
```javascript
let currentMoney;
let laptopPrice;
let laptopDiscountPrice = laptopPrice - (laptopPrice * .20) //Laptop price at 20 percent off
if (currentMoney >= laptopPrice || currentMoney >= laptopDiscountPrice){
//Condition was true. Code in this block will run.
console.log("Getting a new laptop!");
}
else {
//Condition was true. Code in this block will run.
console.log("Can't afford a new laptop, yet!");
}
```
### Negation operator
You've seen so far how if you can use an `if...else` statement to create conditional logic. Anything that goes into an `if` needs to evaluate to true/false. By using the `!` operator you can _negate_ the expression. It would look like so:
```javascript
if (!condition) {
// runs if condition is false
} else {
// runs if condition is true
}
```
### Ternary expressions
`if...else` isn't the only way to express decision logic. You can also use something called a ternary operator. The syntax for it looks like this:
```javascript
let variable = condition ? <return this if true> : <return this if false>`
```
Below is a more tangible example:
```javascript
let firstNumber = 20;
let secondNumber = 10
let biggestNumber = firstNumber > secondNumber ? firstNumber: secondNumber;
```
✅ Take a minute to read this code a few times. Do you understand how these operators are working?
The above states that
- if `firstNumber` is larger than `secondNumber`
- then assign `firstNumber` to `biggestNumber`
- else assign `secondNumber`.
The ternary expression is just a compact way of writing the code below:
```javascript
let biggestNumber;
if (firstNumber > secondNumber) {
biggestNumber = firstNumber;
} else {
biggestNumber = secondNumber;
}
```
---
## 🚀 Challenge
Create a program that is written first with logical operators, and then rewrite it using a ternary expression. What's your preferred syntax?
## [Post-lecture quiz](.github/post-lecture-quiz.md)
## Review & Self Study
Read more about the many operators available to the user [on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators).
## Assignment
[Operators](assignment.md)

View File

@@ -0,0 +1,40 @@
# Operators
## Instructions
Play around with operators. Here's a suggestion for a program you can implement:
You have a set of students from two different grading systems.
### First grading system
One grading system is defined as grades being from 1-5 where 3 and above means you pass the course.
### Second grading system
The other grade system has the following grades `A, A-, B, B-, C, C-` where `A` is the top grade and `C` is the lowest passing grade.
### The task
Given the following array `allStudents` representing all students and their grades, construct a new array `studentsWhoPass` containing all students who pass.
> TIP, use a for-loop and if...else and comparison operators:
```javascript
let allStudents = [
'A',
'B-'
1,
4
5,
2
]
let studentsWhoPass = [];
```
## Rubric
| Criteria | Exemplary | Adequate | Needs Improvement |
| -------- | ------------------------------ | ----------------------------- | ------------------------------- |
| | Complete solution is presented | Partial solution is presented | Solution with bugs is presented |

View File

@@ -0,0 +1,169 @@
# JavaScript-Grundlagen: Entscheidungen treffen
[![Entscheidungen treffen](https://img.youtube.com/vi/SxTp8j-fMMY/0.jpg)](https://youtube.com/watch?v=SxTp8j-fMMY "Entscheidungen treffen")
## [Pre-Lecture Quiz](.github/pre-lecture-quiz.md)
Wenn Sie Entscheidungen treffen und die Reihenfolge steuern, in der Ihr Code ausgeführt wird, ist Ihr Code wiederverwendbar und robust. Dieser Abschnitt behandelt die Syntax zur Steuerung des Datenflusses in JavaScript und ihre Bedeutung bei Verwendung mit booleschen Datentypen.
## Eine kurze Zusammenfassung der Booleschen Werte
Boolesche Werte können nur zwei Werte sein: `true` oder `false`. Boolesche Werte helfen bei der Entscheidung, welche Codezeilen ausgeführt werden sollen, wenn bestimmte Bedingungen erfüllt sind.
Stellen Sie Ihren Booleschen Wert wie folgt auf wahr oder falsch ein:
`let myTrueBool = true`
`let myFalseBool = false`
✅ Boolesche sind nach dem englischen Mathematiker, Philosophen und Logiker George Boole (18151864) benannt.
## Vergleichsoperatoren und Boolesche Werte
Operatoren werden verwendet, um Bedingungen durch Vergleiche zu bewerten, die einen Booleschen Wert erzeugen. Das Folgende ist eine Liste von Operatoren, die häufig verwendet werden.
| Symbol | Beschreibung | Beispiel |
| ------ | -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- ------- | ------------------ |
| `<` | **Größer als**: Vergleicht zwei Werte und gibt den booleschen Datentyp "true" zurück, wenn der Wert auf der rechten Seite größer als der linke ist `5 < 6 // true` |
| `<=` | **Größer oder gleich**: Vergleicht zwei Werte und gibt den booleschen Datentyp `true` zurück, wenn der Wert auf der rechten Seite größer oder gleich dem linken | ist `5 <= 6 // true` |
| `>` | **Kleiner als**: Vergleicht zwei Werte und gibt den booleschen Datentyp `true` zurück, wenn der Wert auf der linken Seite größer als der rechte ist `5 > 6 // false` |
| `=>` | **Kleiner oder gleich**: Vergleicht zwei Werte und gibt den booleschen Datentyp `true` zurück, wenn der Wert auf der linken Seite größer oder gleich dem rechten | ist `5 => 6 // false` |
| `===` | **Strikte Gleichheit**: Vergleicht zwei Werte und gibt den booleschen Datentyp `true` zurück, wenn die Werte rechts und links gleich sind UND denselben Datentyp haben. | `5 === 6 // false` |
| `!==` | **Ungleichung**: Vergleicht zwei Werte und gibt den entgegengesetzten Booleschen Wert zurück, den ein strikter Gleichheitsoperator | zurückgeben würde `5 !== 6 // true` |
✅ Überprüfen Sie Ihr Wissen, indem Sie einige Vergleiche in die Konsole Ihres Browsers schreiben. Überraschen Sie zurückgegebene Daten?
## If-Anweisung
Die if-Anweisung führt Code zwischen ihren Blöcken aus, wenn die Bedingung erfüllt ist.
```javascript
if (condition){
//Bedingung war wahr. Der Code in diesem Block wird ausgeführt.
}
```
Logische Operatoren werden häufig verwendet, um die Bedingung zu bilden.
```javascript
let currentMoney;
let laptopPrice;
if (currentMoney >= laptopPrice){
//Bedingung war wahr. Der Code in diesem Block wird ausgeführt.
console.log("Getting a new laptop!");
}
```
## IF..Else Anweisung
Die `else`-Anweisung führt den Code zwischen ihren Blöcken aus, wenn die Bedingung falsch ist. Es ist optional mit einer `if`-Anweisung.
```javascript
let currentMoney;
let laptopPrice;
if (currentMoney >= laptopPrice){
//Bedingung war wahr. Der Code in diesem Block wird ausgeführt.
console.log("Getting a new laptop!");
}
else{
//Bedingung war wahr. Der Code in diesem Block wird ausgeführt.
console.log("Can't afford a new laptop, yet!");
}
```
✅ Testen Sie Ihr Verständnis dieses Codes und des folgenden Codes, indem Sie ihn in einer Browserkonsole ausführen. Ändern Sie die Werte der Variablen currentMoney und LaptopPrice, um das zurückgegebene `console.log()` zu ändern.
## Logische Operatoren und Boolesche Werte
Entscheidungen erfordern möglicherweise mehr als einen Vergleich und können mit logischen Operatoren verknüpft werden, um einen Booleschen Wert zu erzeugen.
| Symbol | Beschreibung | Beispiel |
| ------ | -------------------------------------------------- ----------------------------------------- | -------------------------------------------------- --------------------- |
| `&&` | **Logisches UND**: Vergleicht zwei Boolesche Ausdrücke. Gibt true **nur** zurück, wenn beide Seiten true | sind `(5 > 6) && (5 < 6) // Eine Seite ist falsch, die andere ist wahr. Gibt false` | zurück
| `||` | **Logisches ODER**: Vergleicht zwei Boolesche Ausdrücke. Gibt true zurück, wenn mindestens eine Seite true ist `(5 > 6) || (5 < 6) // Eine Seite ist falsch, die andere ist wahr. Gibt true` | zurück
| `!` | **Logisch NICHT**: Gibt den entgegengesetzten Wert eines Booleschen Ausdrucks | zurück `! (5 > 6) // 5 ist nicht größer als 6, aber "!" wird true zurückgeben` |
## Bedingungen und Entscheidungen mit logischen Operatoren
Logische Operatoren können verwendet werden, um Bedingungen in if..else-Anweisungen zu bilden.
```javascript
let currentMoney;
let laptopPrice;
let laptopDiscountPrice = laptopPrice - (laptopPrice * .20) //Laptop-Preis bei 20 Prozent Rabatt
if (currentMoney >= laptopPrice || currentMoney >= laptopDiscountPrice){
//Bedingung war wahr. Der Code in diesem Block wird ausgeführt.
console.log("Getting a new laptop!");
}
else {
//Bedingung war wahr. Der Code in diesem Block wird ausgeführt.
console.log("Can't afford a new laptop, yet!");
}
```
### Negationsoperator
Sie haben bisher gesehen, wie Sie mit einer `if...else`-Anweisung eine bedingte Logik erstellen können. Alles, was in ein `if` geht, muss als wahr / falsch bewertet werden. Mit dem Operator `!` Können Sie den Ausdruck _negieren_. Es würde so aussehen:
```javascript
if (!condition) {
// wird ausgeführt, wenn die Bedingung falsch ist
} else {
// wird ausgeführt, wenn die Bedingung erfüllt ist
}
```
### Ternäre Ausdrücke
`if...else` ist nicht die einzige Möglichkeit, Entscheidungslogik auszudrücken. Sie können auch einen so genannten ternären Operator verwenden. Die Syntax dafür sieht folgendermaßen aus:
```javascript
let variable = condition ? <return this if true> : <return this if false>`
```
Below is a more tangible example:
```javascript
let firstNumber = 20;
let secondNumber = 10
let biggestNumber = firstNumber > secondNumber ? firstNumber: secondNumber;
```
✅ Nehmen Sie sich eine Minute Zeit, um diesen Code einige Male zu lesen. Verstehen Sie, wie diese Operatoren arbeiten?
Das Obige besagt das
- wenn `firstNumber` größer als `secondNumber` ist
- dann `firstNumber` zu `biggestNumber` zuweisen
- sonst `secondNumber` zuweisen.
Der ternäre Ausdruck ist nur eine kompakte Art, den folgenden Code zu schreiben:
```javascript
let biggestNumber;
if (firstNumber > secondNumber) {
biggestNumber = firstNumber;
} else {
biggestNumber = secondNumber;
}
```
---
## 🚀 Herausforderung
Erstellen Sie ein Programm, das zuerst mit logischen Operatoren geschrieben wird, und schreiben Sie es dann mit einem ternären Ausdruck neu. Was ist Ihre bevorzugte Syntax?
## [Quiz nach der Vorlesung] (.github/post-lecture-quiz.md)
## Review & Selbststudium
Lesen Sie mehr über die vielen Operatoren, die dem Benutzer [auf MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators) zur Verfügung stehen.
## Zuordnung
[Operators](assignment.md)

View File

@@ -0,0 +1,164 @@
# Conceptos básicos de JavaScript: tomar decisiones
![video](video-url)
## [Pre-lecture prueba](.github/pre-lecture-quiz.md)
Tomar decisiones y controlar el orden en que se ejecuta su código hace que su código sea reutilizable y robusto. Esta sección cubre la sintaxis para controlar el flujo de datos en JavaScript y su importancia cuando se usa con tipos de datos booleanos.
## Un breve resumen sobre los valores booleanos
Los booleanos pueden tener solo dos valores: `true` o` false`. Los booleanos ayudan a tomar decisiones sobre qué líneas de código deben ejecutarse cuando se cumplen ciertas condiciones.
Establezca su booleano en verdadero o falso de esta manera:
`let myTrueBool = true`
`let myFalseBool = false`
✅ Los booleanos llevan el nombre del matemático, filósofo y lógico inglés George Boole. (18151864).
## Operadores de comparación y valores booleanos
Los operadores se utilizan para evaluar las condiciones haciendo comparaciones que crearán un valor booleano. La siguiente es una lista de operadores que se utilizan con frecuencia.
| Símbolo | Descripción | Ejemplo |
| ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ |
| `<` | **Mayor que**: compara dos valores y devuelve el tipo de datos booleano `true` si el valor del lado derecho es mayor que el del izquierdo | `5 < 6 // true` |
| `<=` | **Mayor o igual que**: compara dos valores y devuelve el tipo de datos booleano `true` si el valor del lado derecho es mayor o igual que el del lado izquierdo | `5 <= 6 // true` |
| `>` | **Menor que**: compara dos valores y devuelve el tipo de datos booleano `true` si el valor del lado izquierdo es mayor que el del derecho | `5 > 6 // false` |
| `=>` | **Menor o igual que**: compara dos valores y devuelve el tipo de datos booleano `true` si el valor del lado izquierdo es mayor o igual que el del lado derecho | `5 => 6 // false` |
| `===` | **Igualdad estricta**: compara dos valores y devuelve el tipo de datos booleano `true` si los valores de la derecha y la izquierda son iguales Y son del mismo tipo de datos | `5 === 6 // false` |
| `!==` | **Desigualdad**: compara dos valores y devuelve el valor booleano opuesto de lo que devolvería un operador de igualdad estricta | `5 !== 6 // true` |
✅ Compruebe sus conocimientos escribiendo algunas comparaciones en la consola de su navegador. ¿Te sorprende algún dato devuelto?
## Declaración If
La sentencia if ejecutará código entre sus bloques si la condición es verdadera.
```javascript
if (condition){
//La condición era verdadera. Se ejecutará el código de este bloque.
}
```
Los operadores lógicos se utilizan a menudo para formar la condición.
```javascript
let currentMoney;
let laptopPrice;
if (currentMoney >= laptopPrice){
//La condición era verdadera. Se ejecutará el código de este bloque.
console.log("Getting a new laptop!");
}
```
## IF..Else Declaración
La declaración `else` ejecutará el código entre sus bloques cuando la condición sea falsa. Es opcional con una declaración `if`.
```javascript
let currentMoney;
let laptopPrice;
if (currentMoney >= laptopPrice){
//La condición era verdadera. Se ejecutará el código de este bloque.
console.log("Getting a new laptop!");
}
else{
//La condición era verdadera. Se ejecutará el código de este bloque.
console.log("Can't afford a new laptop, yet!");
}
```
✅ Pruebe su comprensión de este código y del siguiente código ejecutándolo en una consola de navegador. Cambie los valores de las variables currentMoney y laptopPrice para cambiar el `console.log()` devuelto.
## Operadores lógicos y booleanos
Las decisiones pueden requerir más de una comparación y se pueden unir con operadores lógicos para producir un valor booleano.
| Símbolo | Descripción | Ejemplo |
| ------ | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| `&&` | **AND lógico**: compara dos expresiones booleanas. Devuelve verdadero **solo** si ambos lados son verdaderos | `(5 > 6) && (5 < 6 ) //Un lado es falso, el otro es verdadero. Devuelve falso` |
| `||` | **OR lógico**: compara dos expresiones booleanas. Devuelve verdadero si al menos un lado es verdadero | `(5 > 6) || (5 < 6) //Un lado es falso, el otro es verdadero. Devuelve verdadero` |
| `!` | **NOT lógico**: Devuelve el valor opuesto de una expresión booleana | `!(5 > 6) // 5 no es mayor que 6, pero "!" devolverá verdadero` |
## Condiciones y decisiones con operadores lógicos
Los operadores lógicos se pueden utilizar para formar condiciones en sentencias if..else.
```javascript
let currentMoney;
let laptopPrice;
let laptopDiscountPrice = laptopPrice - (laptopPrice * .20) //Precio del portátil al 20% de descuento
if (currentMoney >= laptopPrice || currentMoney >= laptopDiscountPrice){
//La condición era verdadera. Se ejecutará el código de este bloque.
console.log("Getting a new laptop!");
}
else {
//La condición era verdadera. Se ejecutará el código de este bloque.
console.log("Can't afford a new laptop, yet!");
}
```
### Operador de negación
Hasta ahora has visto cómo si puedes usar una instrucción `if...else` para crear lógica condicional. Cualquier cosa que entre en un `if` debe evaluarse como verdadero / falso. Utilizando el operador `!` Puede _negar_ la expresión. Se vería así:
```javascript
if (!condition) {
// se ejecuta si la condición es falsa
} else {
// se ejecuta si la condición es verdadera
}
```
### Expresiones ternarias
`If...else` no es la única forma de expresar la lógica de decisión. También puede usar algo llamado operador ternario. La sintaxis tiene el siguiente aspecto:
```javascript
let variable = condition ? <return this if true> : <return this if false>`
```
A continuación se muestra un ejemplo más tangible:
```javascript
let firstNumber = 20;
let secondNumber = 10
let biggestNumber = firstNumber > secondNumber ? firstNumber: secondNumber;
```
✅ Tómese un minuto para leer este código varias veces. ¿Entiende cómo trabajan estos operadores?
Lo anterior establece que
- si `firstNumber` es mayor que `secondNumber`
- luego asigne `firstNumber` a `biggestNumber`
- de lo contrario, asigne `secondNumber`.
La expresión ternaria es solo una forma compacta de escribir el siguiente código:
```javascript
let biggestNumber;
if (firstNumber > secondNumber) {
biggestNumber = firstNumber;
} else {
biggestNumber = secondNumber;
}
```
🚀 Desafío: cree un programa que se escriba primero con operadores lógicos y luego vuelva a escribirlo utilizando una expresión ternaria. ¿Cuál es tu sintaxis preferida?
## [Post-lecture prueba](.github/post-lecture-quiz.md)
## Revisión y autoestudio
Más información sobre los muchos operadores disponibles para el usuario [en MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators).
**Asignación**: [Operadores](assignment.md)

View File

@@ -0,0 +1,40 @@
# Operatoren
## Anleitung
Spielen Sie mit den Betreibern herum. Hier ist ein Vorschlag für ein Programm, das Sie implementieren können:
Sie haben eine Gruppe von Studenten aus zwei verschiedenen Bewertungssystemen.
### Erstbewertungssystem
Ein Bewertungssystem ist definiert als Noten von 1 bis 5, wobei 3 und höher bedeutet, dass Sie den Kurs bestehen.
### Zweites Bewertungssystem
Das andere Notensystem hat die folgenden Noten `A, A-, B, B-, C, C-` wobei `A` die Bestnote und `C` die niedrigste bestandene Note ist.
### Die Aufgabe
Erstellen Sie unter Berücksichtigung des folgenden Arrays `allStudents`, das alle Schüler und ihre Noten darstellt, ein neues Array `studentsWhoPass`, das alle bestandenen Schüler enthält.
> TIPP, verwenden Sie eine for-Schleife und if...else und Vergleichsoperatoren:
```javascript
let allStudents = [
'A',
'B-'
1,
4
5,
2
]
let studentsWhoPass = [];
```
## Rubrik
| Kriterien | Vorbildlich | Angemessen | Verbesserungsbedarf |
| -------- | ------------------------------ | ----------------------------- | ------------------------------- |
| | Komplettlösung wird vorgestellt | Teillösung wird vorgestellt Lösung mit Fehlern wird vorgestellt |

View File

@@ -0,0 +1,41 @@
# Operadores
## Instrucciones
Juega con los operadores. Aquí hay una sugerencia de un programa que puede implementar.
Tiene un conjunto de estudiantes de dos sistemas de calificación diferentes.
### Primer sistema de calificación
Un sistema de calificación se define como calificaciones del 1 al 5, donde 3 y más significa que aprueba el curso.
### Segundo sistema de calificación
El otro sistema de calificaciones tiene las siguientes calificaciones `A, A-, B, B-, C, C-` donde `A` es la calificación más alta y `C` es la calificación más baja para aprobar.
### La tarea
Dada la siguiente matriz `allStudents` que representa a todos los estudiantes y sus calificaciones, construya una nueva matriz `StudentsWhoPass` que contenga a todos los estudiantes que aprobaron.
> SUGERENCIA, use un bucle for y if ... else y operadores de comparación:
```javascript
let allStudents = [
'A',
'B-'
1,
4
5,
2
]
let studentsWhoPass = [];
```
## Rúbrica
| Criterios | Ejemplar | Adecuado | Necesita mejorar |
| -------- | ------------------------------ | ----------------------------- | ------------------------------- |
| | Se presenta la solución completa | Se presenta solución parcial | Se presenta solución con errores |

View File

@@ -0,0 +1,18 @@
*Complete this quiz by checking one answer per question.*
1. What part of a for-loop would you need to modify to increment its iteration by 5
- [ ] condition
- [ ] counter
- [ ] iteration-expression
2. What's the difference between a `while` and a `for-loop`
- [ ] A `for-loop` has a counter and iteration-expression, where `while` only has a condition
- [ ] A `while` has a counter and iteration-expression where `for-loop` only has a condition
- [ ] They are the same, just an alias for one another
3. Given the code `for (let i=1; i < 5; i++)`, how many iterations will it perform?
- [ ] 5
- [ ] 4

View File

@@ -0,0 +1,13 @@
*Complete this quiz in class*
1. To refer to specific item in an array, you would use a
- [ ] square bracket `[]`
- [ ] index
- [ ] curly braces `{}`
2. How do you get the number of items in an array
- [ ] The `len(array)` method
- [ ] The property `size` on the array
- [ ] The `length` property on the array

View File

@@ -0,0 +1,118 @@
# JavaScript Basics: Arrays and Loops
[![Arrays and Loops](https://img.youtube.com/vi/Q_CRM2lXXBg/0.jpg)](https://youtube.com/watch?v=Q_CRM2lXXBg "Arrays and Loops")
## [Pre-lecture quiz](.github/pre-lecture-quiz.md)
This lesson covers the basics of JavaScript, the language that provides interactivity on the web. In this lesson, you'll learn about arrays and loops, which are used to manipulate data.
## Arrays
Working with data is a common task for any language, and it's a much easier task when data is organized in a structural format, such as arrays. With arrays, data is stored in a structure similar to a list. One major benefit of arrays is that you can store different types of data in one array.
✅ Arrays are all around us! Can you think of a real-life example of an array, such as a solar panel array?
The syntax for an array is a pair of square brackets.
`let myArray = [];`
This is an empty array, but arrays can be declared already populated with data. Multiple values in an array are separated by a comma.
`let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"];`
The array values are assigned a unique value called the **index**, a whole number that is assigned based on its distance from the beginning of the array. In the example above, the string value "Chocolate" has an index of 0, and the index of "Rocky Road" is 4. Use the index with square brackets to retrieve, change, or insert array values.
✅ Does it surprise you that arrays start at the zero index? In some programming languages, indexes start at 1. There's an interesting history around this, which you can [read on Wikipedia](https://en.wikipedia.org/wiki/Zero-based_numbering).
```javascript
let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"];
iceCreamFlavors[2]; //"Vanilla"
```
You can leverage the index to change a value, like this:
```javascript
iceCreamFlavors[4] = "Butter Pecan"; //Changed "Rocky Road" to "Butter Pecan"
```
And you can insert a new value at a given index like this:
```javascript
iceCreamFlavors[5] = "Cookie Dough"; //Added "Cookie Dough"
```
✅ A more common way to push values to an array is by using array operators such as array.push()
To find out how many items are in an array, use the `length` property.
```javascript
let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"];
iceCreamFlavors.length; //5
```
✅ Try it yourself! Use your browser's console to create and manipulate an array of your own creation.
## Loops
Loops allow for repetitive or **iterative** tasks, and can save a lot of time and code. Each iteration can vary in their variables, values, and conditions. There are different types of loops in JavaScript, and they have small differences, but essentially do the same thing: loop over data.
### For Loop
The `for` loop requires 3 parts to iterate:
- `counter` A variable that is typically initialized with a number that counts the number of iterations.
- `condition` Expression that uses comparison operators to cause the loop to stop when `true`
- `iteration-expression` Runs at the end of each iteration, typically used to change the counter value
```javascript
//Counting up to 10
for (let i = 0; i < 10; i++) {
console.log(i);
}
```
✅ Run this code in a browser console. What happens when you make small changes to the counter, condition, or iteration expression? Can you make it run backwards, creating a countdown?
### While loop
Unlike the syntax for the `for` loop, `while` loops only require a condition that will stop the loop when `true`. Conditions in loops usually rely on other values like counters, and must be managed during the loop. Starting values for counters must be created outside the loop, and any expressions to meet a condition, including changing the counter must be maintained inside the loop.
```javascript
//Counting up to 10
let i = 0;
while (i < 10) {
console.log(i);
i++;
}
```
✅ Why would you choose a for loop vs. a while loop? 17K viewers had the same question on StackOverflow, and some of the opinions [might be interesting to you](https://stackoverflow.com/questions/39969145/while-loops-vs-for-loops-in-javascript).
## Loops and Arrays
Arrays are often used with loops because most conditions require the length of the array to stop the loop, and the index can also be the counter value.
```javascript
let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"];
for (let i = 0; i < iceCreamFlavors.length; i++) {
console.log(iceCreamFlavors[i]);
} //Ends when all flavors are printed
```
✅ Experiment with looping over an array of your own making in your browser's console.
---
## 🚀 Challenge
There are other ways of looping over arrays other than for and while loops. There are [forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach), [for-of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of), and [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). Rewrite your array loop using one of these techniques.
## [Post-lecture quiz](.github/post-lecture-quiz.md)
## Review & Self Study
Arrays in JavaScript have many methods attached to them, extremely useful for data manipulation. [Read up on these methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) and try some of them out (like push, pop, slice and splice) on an array of your creation.
## Assignment
[Loop an Array](assignment.md)

View File

@@ -0,0 +1,13 @@
# Loop an Array
## Instructions
Create a program that lists every 3rd number between 1-20 and prints it to the console.
> TIP: use a for-loop and modify the iteration-expression
## Rubric
| Criteria | Exemplary | Adequate | Needs Improvement |
| -------- | --------------------------------------- | ------------------------ | ------------------------------ |
| | Program runs correctly and is commented | Program is not commented | Program is incomplete or buggy |

View File

@@ -0,0 +1,122 @@
# JavaScript-Grundlagen: Arrays und Loops
[![Arrays und Loops](https://img.youtube.com/vi/Q_CRM2lXXBg/0.jpg)](https://youtube.com/watch?v=Q_CRM2lXXBg "Arrays and Loops")
## [Pre-Lecture Quiz](.github/pre-lecture-quiz.md)
Diese Lektion behandelt die Grundlagen von JavaScript, der Sprache, die Interaktivität im Web bietet. In dieser Lektion lernen Sie Arrays und Loops kennen, mit denen Daten bearbeitet werden.
## Arrays
Das Arbeiten mit Daten ist eine häufige Aufgabe für jede Sprache und eine viel einfachere Aufgabe, wenn Daten in einem strukturellen Format wie Arrays organisiert sind. Bei Arrays werden Daten in einer Struktur ähnlich einer Liste gespeichert. Ein Hauptvorteil von Arrays besteht darin, dass Sie verschiedene Datentypen in einem Array speichern können.
✅ Arrays sind überall um uns herum! Können Sie sich ein reales Beispiel für ein Array vorstellen, beispielsweise ein Solarpanel-Array?
Die Syntax für ein Array besteht aus zwei eckigen Klammern.
`let myArray = [];`
Dies ist ein leeres Array, aber Arrays können als bereits mit Daten gefüllt deklariert werden. Mehrere Werte in einem Array werden durch ein Komma getrennt.
`let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"];`
Den Array-Werten wird ein eindeutiger Wert zugewiesen, der als **Index** bezeichnet wird. Diese ganze Zahl wird basierend auf dem Abstand vom Anfang des Arrays zugewiesen. Im obigen Beispiel hat der Zeichenfolgenwert "Chocolate" den Index 0 und der Index "Rocky Road" den Wert 4. Verwenden Sie den Index in eckigen Klammern, um Array-Werte abzurufen, zu ändern oder einzufügen.
✅ Überrascht es Sie, dass Arrays am Nullindex beginnen? In einigen Programmiersprachen beginnen die Indizes bei 1. Es gibt eine interessante Geschichte, die Sie [auf Wikipedia lesen](https://en.wikipedia.org/wiki/Zero-based_numbering) können.
```javascript
let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"];
iceCreamFlavors[2]; //"Vanilla"
```
Sie können den Index nutzen, um einen Wert wie folgt zu ändern:
```javascript
iceCreamFlavors[4] = "Butter Pecan"; //ändert "Rocky Road" in "Butter Pecan"
```
And you can insert a new value at a given index like this:
```javascript
iceCreamFlavors[5] = "Cookie Dough"; //"Cookie Dough" hinzugefügt
```
✅ Eine häufigere Methode zum Übertragen von Werten in ein Array ist die Verwendung von Array-Operatoren wie array.push()
Verwenden Sie die Eigenschaft `length`, um herauszufinden, wie viele Elemente sich in einem Array befinden.
```javascript
let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"];
iceCreamFlavors.length; //5
```
✅ Probieren Sie es aus! Verwenden Sie die Konsole Ihres Browsers, um ein Array Ihrer eigenen Erstellung zu erstellen und zu bearbeiten.
## Schleifen
Schleifen ermöglichen sich wiederholende oder **iterative** Aufgaben und können viel Zeit und Code sparen. Jede Iteration kann in ihren Variablen, Werten und Bedingungen variieren. Es gibt verschiedene Arten von Schleifen in JavaScript, und sie weisen kleine Unterschiede auf, tun jedoch im Wesentlichen dasselbe: Schleifen über Daten.
### For Loop
Die `for`-Schleife benötigt 3 Teile, um zu iterieren:
- `counter` Eine Variable, die normalerweise mit einer Zahl initialisiert wird, die die Anzahl der Iterationen zählt.
- `condition` Ausdruck, der Vergleichsoperatoren verwendet, um zu bewirken, dass die Schleife stoppt, wenn `true`
- `iteration-expression` Wird am Ende jeder Iteration ausgeführt und normalerweise zum Ändern des Zählerwerts verwendet
```javascript
//Counting up to 10
for (let i = 0; i < 10; i++) {
console.log(i);
}
```
✅ Führen Sie diesen Code in einer Browserkonsole aus. Was passiert, wenn Sie kleine Änderungen am Zähler, der Bedingung oder dem Iterationsausdruck vornehmen? Können Sie es rückwärts laufen lassen und einen Countdown erstellen?
### While-Schleife
Im Gegensatz zur Syntax für die `for` -Schleife erfordern `while`-Schleifen nur eine Bedingung, die die Schleife stoppt, wenn `true`. Bedingungen in Schleifen hängen normalerweise von anderen Werten wie Zählern ab und müssen während der Schleife verwaltet werden. Startwerte für Zähler müssen außerhalb der Schleife erstellt werden, und alle Ausdrücke, die eine Bedingung erfüllen, einschließlich des Änderns des Zählers, müssen innerhalb der Schleife beibehalten werden.
```javascript
//Counting up to 10
let i = 0;
while (i < 10) {
console.log(i);
i++;
}
```
✅ Warum sollten Sie eine for-Schleife oder eine while-Schleife wählen? 17.000 Zuschauer hatten dieselbe Frage zu StackOverflow und einige der Meinungen [könnten für Sie interessant sein](https://stackoverflow.com/questions/39969145/while-loops-vs-for-loops-in-javascript).
## Schleifen und Arrays
Arrays werden häufig mit Schleifen verwendet, da die meisten Bedingungen die Länge des Arrays erfordern, um die Schleife zu stoppen, und der Index auch der Zählerwert sein kann.
```javascript
let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"];
for (let i = 0; i < iceCreamFlavors.length; i++) {
console.log(iceCreamFlavors[i]);
} //Endet, wenn alle Geschmacksrichtungen gedruckt sind
```
✅ Experimentieren Sie mit dem Durchlaufen eines Arrays, das Sie selbst erstellt haben, in der Konsole Ihres Browsers.
---
## 🚀 Herausforderung
Es gibt andere Möglichkeiten, Arrays als for- und while-Schleifen zu durchlaufen. Es gibt [forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach), [for-of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) und [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). Schreiben Sie Ihre Array-Schleife mit einer dieser Techniken neu.
## [Quiz nach der Vorlesung](.github/post-lecture-quiz.md)
## Review & Selbststudium
An Arrays in JavaScript sind viele Methoden angehängt, die für die Datenmanipulation äußerst nützlich sind. [Informieren Sie sich über diese Methoden](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) und probieren Sie einige davon aus (wie Push, Pop, Slice und Splice). auf einem Array Ihrer Kreation.
## Zuordnung
[Array schleifen](assignment.md)

View File

@@ -0,0 +1,114 @@
# Conceptos básicos de JavaScript: matrices y bucles
[![Matrices y bucles](https://img.youtube.com/vi/Q_CRM2lXXBg/0.jpg)](https://youtube.com/watch?v=Q_CRM2lXXBg "Matrices y bucles")
## [Pre-lecture prueba](.github/pre-lecture-quiz.md)
Esta lección cubre los conceptos básicos de JavaScript, el lenguaje que proporciona interactividad en la web. En esta lección, aprenderá sobre matrices y bucles, que se utilizan para manipular datos.
## Matrices
Trabajar con datos es una tarea común para cualquier lenguaje y es una tarea mucho más fácil cuando los datos están organizados en un formato estructural, como matrices. Con las matrices, los datos se almacenan en una estructura similar a una lista. Uno de los principales beneficios de las matrices es que puede almacenar diferentes tipos de datos en una matriz.
✅ ¡Las matrices están a nuestro alrededor! ¿Puede pensar en un ejemplo de la vida real de una matriz, como una matriz de paneles solares?
La sintaxis de una matriz es un par de corchetes.
`let myArray = [];`
Esta es una matriz vacía, pero las matrices se pueden declarar ya pobladas con datos. Varios valores en una matriz están separados por una coma.
`let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"];`
A los valores de la matriz se les asigna un valor único llamado **índice**, un número entero que se asigna en función de su distancia desde el principio de la matriz. En el ejemplo anterior, el valor de cadena "Chocolate" tiene un índice de 0 y el índice de "Rocky Road" es 4. Utilice el índice entre corchetes para recuperar, cambiar o insertar valores de matriz.
✅ ¿Le sorprende que las matrices comiencen en el índice cero? En algunos lenguajes de programación, los índices comienzan en 1. Hay una historia interesante en torno a esto, que puedes [leer en Wikipedia](https://en.wikipedia.org/wiki/Zero-based_numbering).
```javascript
let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"];
iceCreamFlavors[2]; //"Vanilla"
```
Puede aprovechar el índice para cambiar un valor, como este:
```javascript
iceCreamFlavors[4] = "Butter Pecan"; //Se cambió "Rocky Road" a "Butter Pecan"
```
Y puede insertar un nuevo valor en un índice dado como este:
```javascript
iceCreamFlavors[5] = "Cookie Dough"; //Añadida "Cookie Dough"
```
✅ Una forma más común de enviar valores a una matriz es mediante el uso de operadores de matriz como array.push()
Para saber cuántos elementos hay en una matriz, use la propiedad `length`.
```javascript
let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"];
iceCreamFlavors.length; //5
```
✅ ¡Inténtalo tú mismo! Utilice la consola de su navegador para crear y manipular una matriz de su propia creación.
## Bucles
Los bucles permiten tareas repetitivas o **iterativas** y pueden ahorrar mucho tiempo y código. Cada iteración puede variar en sus variables, valores y condiciones. Hay diferentes tipos de bucles en JavaScript y tienen pequeñas diferencias, pero esencialmente hacen lo mismo: bucles sobre datos.
### En bucle
El ciclo `for` requiere 3 partes para iterar:
- `counter` Una variable que normalmente se inicializa con un número que cuenta el número de iteraciones.
- `condition` Expresión que usa operadores de comparación para hacer que el bucle se detenga cuando `true`
- `iteration-expression` Se ejecuta al final de cada iteración, generalmente se usa para cambiar el valor del contador
```javascript
//Contando hasta 10
for (let i = 0; i < 10; i++) {
console.log(i);
}
```
✅ Ejecute este código en una consola de navegador. ¿Qué sucede cuando realiza pequeños cambios en el contador, la condición o la expresión de iteración? ¿Puedes hacer que corra al revés, creando una cuenta regresiva?
### Bucle while
A diferencia de la sintaxis para el ciclo `for`, los ciclos `while` solo requieren una condición que detendrá el ciclo cuando sea `true`. Las condiciones en los bucles suelen depender de otros valores, como contadores, y deben gestionarse durante el bucle. Los valores iniciales para los contadores deben crearse fuera del ciclo, y cualquier expresión que cumpla una condición, incluido el cambio del contador, debe mantenerse dentro del ciclo.
```javascript
//Contando hasta 10
let i = 0;
while (i < 10) {
console.log(i);
i++;
}
```
✅ ¿Por qué elegiría un bucle for frente a un bucle while? 17K espectadores tenían la misma pregunta sobre StackOverflow, y algunas de las opiniones [podrían ser interesantes para usted](https://stackoverflow.com/questions/39969145/ while-loops-vs-for-loops-in-javascript).
## Bucles y matrices
Las matrices se utilizan a menudo con bucles porque la mayoría de las condiciones requieren la longitud de la matriz para detener el bucle, y el índice también puede ser el valor del contador.
```javascript
let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"];
for (let i = 0; i < iceCreamFlavors.length; i++) {
console.log(iceCreamFlavors[i]);
} //Termina cuando se imprimen todos los sabores
```
✅ Experimente recorriendo una serie de su propia creación en la consola de su navegador.
🚀 Desafío: Hay otras formas de realizar un bucle sobre arreglos además de los bucles for y while. Existen [forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach), [for-of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of), y [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). Vuelva a escribir su bucle de matriz utilizando una de estas técnicas.
## [Post-lecture prueba](.github/post-lecture-quiz.md)
## Revisión y autoestudio
Las matrices en JavaScript tienen muchos métodos adjuntos, extremadamente útiles para la manipulación de datos. [Lea sobre estos métodos](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) y pruebe algunos de ellos (como push, pop, slice y splice) en una matriz de su creación.
**Asignación**: [Bucle de una matriz](assignment.md)

View File

@@ -0,0 +1,13 @@
# Schleife ein Array
## Anleitung
Erstellen Sie ein Programm, das jede dritte Zahl zwischen 1 und 20 auflistet und auf der Konsole druckt.
> TIPP: Verwenden Sie eine for-Schleife und ändern Sie den Iterationsausdruck
## Rubrik
| Kriterien | Vorbildlich | Angemessen | Verbesserungsbedarf |
| -------- | --------------------------------------- | ------------------------ | ------------------------------ |
| | Programm läuft korrekt und ist kommentiert | Programm ist nicht kommentiert | Programm ist unvollständig oder fehlerhaft

View File

@@ -0,0 +1,13 @@
# Hacer bucle en una matriz
## Instrucciones
Cree un programa que enumere cada tercer número entre 1 y 20 y lo imprima en la consola.
> SUGERENCIA: use un bucle for y modifique la expresión-iteración
## Rúbrica
| Criterios | Ejemplar | Adecuado | Necesita mejorar |
| -------- | --------------------------------------- | ------------------------ | ------------------------------ |
| | El programa se ejecuta correctamente y está comentado | Programa no comentado | El programa está incompleto o con errores |

21
2-js-basics/LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 WebDev-For-Beginners
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

14
2-js-basics/README.md Normal file
View File

@@ -0,0 +1,14 @@
# Introduction to JavaScript
JavaScript is the language of the web. In these four lessons, you'll learn its basics.
### Topics
1. [Variables and Data Types](1-data-types/README.md)
2. [Functions and Methods](2-functions-methods/README.md)
3. [Making Decisions with JavaScript](3-making-decisions/README.md)
4. [Arrays and Loops](4-arrays-loops/README.md)
### Credits
These lessons were written with ♥️ by [Jasmine Greenaway](https://twitter.com/paladique), [Christopher Harrison](https://twitter.com/geektrainer) and [Chris Noring](https://twitter.com/chris_noring)

View File

@@ -0,0 +1,14 @@
# Einführung in JavaScript
JavaScript ist die Sprache des Webs. In diesen vier Lektionen lernen Sie die Grundlagen.
### Themen
1. [Variablen und Datentypen](1-Datentypen/README.md)
2. [Funktionen und Methoden](2-functions-methods/README.md)
3. [Entscheidungen mit JavaScript treffen](3-making-decisions/README.md)
4. [Arrays und Loops](4-arrays-loops/README.md)
### Credits
Diese Lektionen wurden mit ♥ von [Jasmine Greenaway](https://twitter.com/paladique), [Christopher Harrison](https://twitter.com/geektrainer) und [Chris Noring](https://twitter.com/chris_noring)

View File

@@ -0,0 +1,14 @@
# Introducción a JavaScript
JavaScript es el lenguaje de la web. En estas cuatro lecciones, aprenderá sus conceptos básicos.
### Temas
1. [Variables y tipos de datos](data-types/README.md)
2. [Funciones y métodos](variables-datatypes/README.md)
3. [Toma de decisiones con JavaScript](making-decisions/README.md)
4. [Arrays and Loops](arrays-loops/README.md)
### Créditos
Estas lecciones fueron escritas con ♥ por [Jasmine Greenaway](https://twitter.com/paladique) y [Chris Noring](https://twitter.com/chris_noring)