mirror of
https://github.com/microsoft/Web-Dev-For-Beginners.git
synced 2025-08-11 17:24:24 +02:00
Added intial files
This commit is contained in:
196
2-js-basics/1-data-types/translations/README.hi.md
Normal file
196
2-js-basics/1-data-types/translations/README.hi.md
Normal file
@@ -0,0 +1,196 @@
|
||||
# JavaScript Basics: Data Types
|
||||
|
||||

|
||||
> Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac)
|
||||
|
||||
## Pre-Lecture Quiz
|
||||
[Pre-lecture quiz](https://nice-beach-0fe9e9d0f.azurestaticapps.net/quiz/7)
|
||||
|
||||
This lesson covers the basics of JavaScript, the language that provides interactivity on the web.
|
||||
|
||||
[](https://youtube.com/watch?v=JNIXfGiDWM8 "Data types in JavaScript")
|
||||
|
||||
|
||||
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
|
||||
[Post-lecture quiz](https://nice-beach-0fe9e9d0f.azurestaticapps.net/quiz/8)
|
||||
|
||||
## 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)
|
195
2-js-basics/2-functions-methods/translations/README.hi.md
Normal file
195
2-js-basics/2-functions-methods/translations/README.hi.md
Normal file
@@ -0,0 +1,195 @@
|
||||
# JavaScript Basics: Methods and Functions
|
||||
|
||||

|
||||
> Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac)
|
||||
|
||||
## Pre-Lecture Quiz
|
||||
[Pre-lecture quiz](https://nice-beach-0fe9e9d0f.azurestaticapps.net/quiz/9)
|
||||
|
||||
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**.
|
||||
|
||||
[](https://youtube.com/watch?v=XgKsD6Zwvlc "Methods and Functions")
|
||||
|
||||
> Click the image above for a video about methods and functions.
|
||||
|
||||
|
||||
## 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(displayDone, 3000);
|
||||
```
|
||||
|
||||
### 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(function() {
|
||||
console.log('3 seconds has elapsed');
|
||||
}, 3000);
|
||||
```
|
||||
|
||||
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(() => {
|
||||
console.log('3 seconds has elapsed');
|
||||
}, 3000);
|
||||
```
|
||||
|
||||
### 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
|
||||
[Post-lecture quiz](https://nice-beach-0fe9e9d0f.azurestaticapps.net/quiz/10)
|
||||
|
||||
## 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)
|
175
2-js-basics/3-making-decisions/translations/README.hi.md
Normal file
175
2-js-basics/3-making-decisions/translations/README.hi.md
Normal file
@@ -0,0 +1,175 @@
|
||||
# JavaScript Basics: Making Decisions
|
||||
|
||||

|
||||
> Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac)
|
||||
|
||||
## Pre-Lecture Quiz
|
||||
[Pre-lecture quiz](https://nice-beach-0fe9e9d0f.azurestaticapps.net/quiz/11)
|
||||
|
||||
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
|
||||
|
||||
[](https://youtube.com/watch?v=SxTp8j-fMMY "Making Decisions")
|
||||
|
||||
> Click the image above for a video about making decisions.
|
||||
## 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 (1815–1864).
|
||||
|
||||
## 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 |
|
||||
| ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ |
|
||||
| `<` | **Less than**: Compares two values and returns the `true` Boolean data type if the value on the left side is less than the right | `5 < 6 // true` |
|
||||
| `<=` | **Less than or equal to**: Compares two values and returns the `true` Boolean data type if the value on the left side is less than or equal to the right | `5 <= 6 // true` |
|
||||
| `>` | **Greater 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` |
|
||||
| `>=` | **Greater 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
|
||||
[Post-lecture quiz](https://nice-beach-0fe9e9d0f.azurestaticapps.net/quiz/12)
|
||||
|
||||
## 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).
|
||||
|
||||
Go through Josh Comeau's wonderful [operator lookup](https://joshwcomeau.com/operator-lookup/)!
|
||||
|
||||
## Assignment
|
||||
|
||||
[Operators](assignment.md)
|
125
2-js-basics/4-arrays-loops/translations/README.hi.md
Normal file
125
2-js-basics/4-arrays-loops/translations/README.hi.md
Normal file
@@ -0,0 +1,125 @@
|
||||
# JavaScript Basics: Arrays and Loops
|
||||
|
||||

|
||||
> Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac)
|
||||
|
||||
## Pre-Lecture Quiz
|
||||
[Pre-lecture quiz](https://nice-beach-0fe9e9d0f.azurestaticapps.net/quiz/13)
|
||||
|
||||
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.
|
||||
|
||||
[](https://youtube.com/watch?v=Q_CRM2lXXBg "Arrays and Loops")
|
||||
|
||||
> Click the image above for a video about arrays and loops.
|
||||
## 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
|
||||
[Post-lecture quiz](https://nice-beach-0fe9e9d0f.azurestaticapps.net/quiz/14)
|
||||
|
||||
|
||||
## 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)
|
Reference in New Issue
Block a user