feat: The Odin Project Learn Operators and Variables (#53943)

Co-authored-by: Tom <20648924+moT01@users.noreply.github.com>
This commit is contained in:
Sem Bauke
2024-03-04 20:39:35 +01:00
committed by GitHub
parent 61e5a0d1ad
commit a8ce82facb
11 changed files with 683 additions and 0 deletions

View File

@@ -1175,6 +1175,12 @@
"intro": [
"Explore the distinctions between block and inline elements in HTML and CSS. This course provides insights into how these display types affect layout and behavior, empowering you to make informed design decisions."
]
},
"top-learn-variables-and-operators": {
"title": "Learn Variables and Operators",
"intro": [
"Get started with JavaScript by learning about variables and operators. This course covers the fundamentals of JavaScript programming, including data types, operators, and variable declarations."
]
}
}
},

View File

@@ -0,0 +1,49 @@
{
"name": "TOP Learn Variables and Operators",
"isUpcomingChange": false,
"dashedName": "top-learn-variables-and-operators",
"helpCategory": "Odin",
"order": 10,
"time": "",
"template": "",
"required": [],
"superBlock": "the-odin-project",
"challengeOrder": [
{
"id": "65e185b1500d930ce8ed909b",
"title": "Learn Variables and Operators Question A"
},
{
"id": "65e18d61500d930ce8ed90a5",
"title": "Learn Variables and Operators Question B"
},
{
"id": "65e1957a500d930ce8ed90a6",
"title": "Learn Variables and Operators Question C"
},
{
"id": "65e1985e500d930ce8ed90a7",
"title": "Learn Variables and Operators Question D"
},
{
"id": "65e19bc3500d930ce8ed90a8",
"title": "Learn Variables and Operators Question E"
},
{
"id": "65e1a2ea500d930ce8ed90a9",
"title": "Learn Variables and Operators Question F"
},
{
"id": "65e1aaf8500d930ce8ed90aa",
"title": "Learn Variables and Operators Question G"
},
{
"id": "65e1aedc500d930ce8ed90ac",
"title": "Learn Variables and Operators Question H"
},
{
"id": "65e1b46e500d930ce8ed90ad",
"title": "Learn Variables and Operators Question I"
}
]
}

View File

@@ -0,0 +1,63 @@
---
id: 65e185b1500d930ce8ed909b
title: Learn Variables and Operators Question A
challengeType: 15
dashedName: learn-variables-and-operators-question-a
---
# --description--
The simplest way to get started is to create an HTML file with the JavaScript code inside of it. Type the basic HTML skeleton into a file on your computer somewhere:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Page Title</title>
</head>
<body>
<script>
// Your JavaScript goes here!
console.log("Hello, World!")
</script>
</body>
</html>
```
Save and open this file up in a web browser (you can use <a href="https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer" target="_blank" >"Live Server" on Visual Studio Code</a> to do this!) and then open up the browsers console by right-clicking on the blank webpage and selecting "Inspect" or "Inspect Element". In the Developer Tools pane find and select the Console tab, where you should see the output of our `console.log` statement.
> `console.log()` is the command to print something to the developer console in your browser. You can use this to print the results from any of the following articles and exercises to the console. We encourage you to code along with all of the examples in this and future lessons.
Another way to include JavaScript in a webpage is through an external script. This is very similar to linking external CSS docs to your website.
```html
<script src="javascript.js"></script>
```
JavaScript files have the extension `.js` similar to `.css` for stylesheets. External JavaScript files are used for more complex scripts.
# --question--
## --text--
Which statement accurately describes how to include JavaScript in an HTML document?
## --answers--
JavaScript can only be included internally within a `<script>` tag in the HTML body.
---
JavaScript code must be written in the `<head>` section of an HTML document for it to execute properly.
---
JavaScript can be included directly in an HTML file using a `<script>` tag or linked externally via a `<script src="javascript.js">` tag.
---
External JavaScript files require a special attribute in the `<script>` tag to be recognized by web browsers.
## --video-solution--
3

View File

@@ -0,0 +1,64 @@
---
id: 65e18d61500d930ce8ed90a5
title: Learn Variables and Operators Question B
challengeType: 15
dashedName: learn-variables-and-operators-question-b
---
# --description--
You can think of variables as "storage containers" for data in your code.
<img src="https://cdn.statically.io/gh/TheOdinProject/curriculum/d39eaf2ca95e80705f703bb218216c10508f5047/foundations/javascript_basics/fundamentals-1/imgs/00.png" alt='the concept of variables in coding as boxes labeled "birthday" that store and provide access to data, specifically a date "16-09-2003"'>
A variable is a "named storage" for data. You can use variables to store goodies, visitors, and other data.
To create a variable in JavaScript, use the `let` keyword.
The statement below creates (in other words: declares) a variable with the name "message":
```js
let message;
```
Now, you can put some data into it by using the assignment operator `=`:
```js
let message;
// store the string 'Hello' in the variable named message
message = 'Hello';
```
To be concise, you can combine the variable declaration and assignment into a single line:
```js
let message = 'Hello';
```
# --question--
## --text--
What is the purpose of using the `let` keyword in JavaScript?
## --answers--
To perform mathematical operations.
---
To declare a constant value that cannot be changed.
---
To declare a variable that can store data, which can be assigned and changed.
---
To create a function.
## --video-solution--
3

View File

@@ -0,0 +1,50 @@
---
id: 65e1957a500d930ce8ed90a6
title: Learn Variables and Operators Question C
challengeType: 15
dashedName: learn-variables-and-operators-question-c
---
# --description--
To declare a constant (unchanging) variable, use `const` instead of `let`:
```javascript
const myBirthday = '16-09-2003';
```
Variables declared using `const` are called "constants". They cannot be reassigned. An attempt to do so would cause an error:
```javascript
const myBirthday = '16-09-2003';
myBirthday = '01-01-2001'; // error, can't reassign the constant!
```
When a programmer is sure that a variable will never change, they can declare it with `const` to guarantee and communicate that fact to everyone.
# --question--
## --text--
What is the result of attempting to reassign a `const` declared variable in JavaScript?
## --answers--
The reassignment succeeds with no errors.
---
An error is thrown because `const` declared variables cannot be reassigned.
---
JavaScript silently ignores the reassignment.
---
The variable type is automatically changed to `let`.
## --video-solution--
2

View File

@@ -0,0 +1,65 @@
---
id: 65e1985e500d930ce8ed90a7
title: Learn Variables and Operators Question D
challengeType: 15
dashedName: learn-variables-and-operators-question-d
---
# --description--
There are two limitations on variable names in JavaScript:
1. The name must contain only letters, digits, or the symbols `$` and `_`.
1. The first character must not be a digit.
Examples of valid names:
```js
let userName;
let test123;
```
Whats interesting the dollar sign `'$'` and the underscore `'_'` can also be used in names. They are regular symbols, just like letters, without any special meaning.
These names are valid:
```js
let $ = 1; // declared a variable with the name "$"
let _ = 2; // and now a variable with the name "_"
console.log($ + _); // 3
```
Examples of incorrect variable names:
```js
let 1a; // cannot start with a digit
let my-name; // hyphens '-' aren't allowed in the name
```
# --question--
## --text--
Which of the following is a valid JavaScript variable name?
## --answers--
`let 2things;`
---
`let my-name;`
---
`let var!;`
---
`let $myVar;`
## --video-solution--
4

View File

@@ -0,0 +1,50 @@
---
id: 65e19bc3500d930ce8ed90a8
title: Learn Variables and Operators Question E
challengeType: 15
dashedName: learn-variables-and-operators-question-e
---
# --description--
Numbers are the building blocks of programming logic! In fact, its hard to think of any useful programming task that doesnt involve at least a little basic math… so knowing how numbers work is obviously quite important. Luckily, its also fairly straightforward.
| Operator | Description | Example |
|----------|------------------------------|--------------------|
| + | Addition | 5 + 3 = 8 |
| - | Subtraction | 5 - 3 = 2 |
| * | Multiplication | 5 * 3 = 15 |
| ** | Exponentiation | 5 ** 3 = 125 |
| / | Division | 6 / 3 = 2 |
| % | Modulus | 5 % 3 = 2 |
# --assignment--
Given the table of operators above, write a simple program snippet that demonstrates the use of each operator with the variable `x` initialized to `10`.
# --question--
## --text--
What is the result of applying the modulus operator to `x` where `x = 10`?
## --answers--
`x % 3` results in `1`
---
`x % 3` results in `3`
---
`x % 3` results in `0`
---
`x % 3` results in `2`
## --video-solution--
1

View File

@@ -0,0 +1,81 @@
---
id: 65e1a2ea500d930ce8ed90a9
title: Learn Variables and Operators Question F
challengeType: 15
dashedName: learn-variables-and-operators-question-f
---
# --description--
Lets meet the features of JavaScript operators that are beyond school arithmetics.
Usually, the plus operator `+` sums numbers.
But, if the binary `+` is applied to strings, it merges (concatenates) them:
```js
let s = "my" + "string";
console.log(s); // mystring
```
Note that if any of the operands is a string, then the other one is converted to a string too.
For example:
```js
console.log(1 + '2'); // '12'
console.log('1' + 2); // '12'
```
See, it doesnt matter whether the first operand is a string or the second one.
Heres a more complex example:
```js
console.log(2 + 2 + '1') // "41" and not "221"
```
Here, operators work one after another. The first `+` sums two numbers, so it returns `4`, then the next `+` adds the string `1` to it, so its like `4 + '1' = '41'`.
```js
console.log('1' + 2 + 2) // "122" and not "14"
```
Here, the first `+` concatenates the string and the number, so it returns `'12'`, then the next `+` adds `2` to it, so its like `'12' + 2 = '122'`.
The binary `+` is the only operator that supports strings in such a way. Other arithmetic operators work only with numbers and always convert their operands to numbers.
Heres the demo for subtraction and division:
```js
console.log( 6 - '2' ); // 4, converts '2' to a number
console.log( '6' / '2' ); // 3, converts both operands to numbers
```
# --question--
## --text--
Considering the behavior of the `+` operator with mixed data types in JavaScript, what will be the output of the following code snippet?
```js
console.log('3' + 2 - 1);
```
## --answers--
`31`, because the `+` operator concatenates the string and number before subtraction.
---
`32`, because `+` concatenates the string and number before subtraction.
---
`4`, because all operands are converted to numbers first.
---
`321`, because the `-` operator is not supported with strings.
## --video-solution--
1

View File

@@ -0,0 +1,80 @@
---
id: 65e1aaf8500d930ce8ed90aa
title: Learn Variables and Operators Question G
challengeType: 15
dashedName: learn-variables-and-operators-question-g
---
# --description--
The plus `+` exists in two forms: the binary form that you used in the last challenge and the unary form.
The unary plus or, in other words, the plus operator `+` applied to a single value, doesnt do anything to numbers. But if the operand is not a number, the unary plus converts it into a number.
For example:
```js
// No effect on numbers
let x = 1;
console.log( +x ); // 1
let y = -2;
console.log( +y ); // -2
// Converts non-numbers
console.log( +true ); // 1
console.log( +"" ); //
```
The need to convert strings to numbers arises very often. For example, if you are getting values from HTML form fields, they are usually strings. What if you want to sum them?
The binary plus would add them as strings:
```js
let apples = "2";
let oranges = "3";
alert( apples + oranges ); // "23", the binary plus concatenates strings
```
If you want to treat them as numbers, you need to convert and then sum them:
```js
let apples = "2";
let oranges = "3";
// both values converted to numbers before the binary plus
alert( +apples + +oranges ); // 5
// the longer variant
// alert( Number(apples) + Number(oranges) ); // 5
```
From a mathematicians standpoint, the abundance of pluses may seem strange. But from a programmers standpoint, theres nothing special: unary pluses are applied first, they convert strings to numbers, and then the binary plus sums them up.
Why are unary pluses applied to values before the binary ones? As youre going to see, thats because of their _higher_ precedence.
# --question--
## --text--
Given the explanation of unary and binary `+` operators in JavaScript, how can you correctly sum the string values `'2'` and `'3'` as numbers using unary `+`?
## --answers--
`console.log('2' + '3'); // Outputs: '23'`
---
`console.log(+2 + +3); // Outputs: 5`
---
`console.log(+'2' + +'3'); // Outputs: 5`
---
`console.log(Number('2') + Number('3')); // Outputs: '23'`
## --video-solution--
3

View File

@@ -0,0 +1,60 @@
---
id: 65e1aedc500d930ce8ed90ac
title: Learn Variables and Operators Question H
challengeType: 15
dashedName: learn-variables-and-operators-question-h
---
# --description--
If an expression has more than one operator, the execution order is defined by their precedence, or, in other words, the default priority order of operators.
From school, you know that the multiplication in the expression `1 + 2 * 2` should be calculated before the addition. Thats exactly the precedence thing. The multiplication is said to have a higher precedence than the addition.
Parentheses override any precedence, so if youre not satisfied with the default order, you can use them to change it. For example, write `(1 + 2) * 2`.
There are many operators in JavaScript. Every operator has a corresponding precedence number. The one with the larger number executes first. If the precedence is the same, the execution order is from left to right.
Heres an extract from the precedence table (you dont need to remember this, but note that unary operators are higher than corresponding binary ones):
| Precedence | Name | Sign |
|------------|------------------|------|
| ... | ... | ... |
| 14 | unary plus | + |
| 14 | unary negation | - |
| 13 | exponentiation | ** |
| 12 | multiplication | * |
| 12 | division | / |
| 11 | addition | + |
| 11 | subtraction | - |
| ... | ... | ... |
| 2 | assignment | = |
| ... | ... | ... |
# --question--
## --text--
When dealing with multiple operators in a JavaScript expression, which statement is true regarding the order of execution?
## --answers--
Operators are executed from right to left, regardless of their precedence.
---
Operators with higher precedence are executed first, and parentheses can override the predefined precedence.
---
The operator precedence is determined by the operator's speed of execution.
---
Multiplication always takes precedence over addition, and unary operators are executed after binary ones.
## --video-solution--
2

View File

@@ -0,0 +1,115 @@
---
id: 65e1b46e500d930ce8ed90ad
title: Learn Variables and Operators Question I
challengeType: 15
dashedName: learn-variables-and-operators-question-i
---
# --description--
Increasing or decreasing a number by one is among the most common numerical operations.
So, there are special operators for it:
- Increment `++` increases a variable by 1:
```js
let counter = 2;
// works the same as counter = counter + 1, but is shorter
counter++;
console.log(counter); // 3
```
- Decrement `--` decreases a variable by 1:
```js
let counter = 2;
// works the same as counter = counter - 1, but is shorter
counter--;
console.log(counter); // 1
```
The operators `++` and `--` can be placed either before or after a variable.
- When the operator goes after the variable, it is in "postfix form": `counter++`.
- The "prefix form" is when the operator goes before the variable: `++counter`.
Both of these statements do the same thing: increase `counter` by `1`.
Is there any difference? Yes, but you can only see it if you use the returned value of `++/--` .
Lets clarify. As you know, all operators return a value. Increment/decrement is no exception. The prefix form returns the new value while the postfix form returns the old value (prior to increment/decrement).
To see the difference, heres an example:
```js
let counter = 1;
let a = ++counter; // (*)
console.log(a); // 2
```
To summarize:
- If the result of increment/decrement is not used, there is no difference in which form to use:
```js
let counter = 0;
counter++;
++counter;
console.log( counter ); // 2, the lines above did the same
```
- If youd like to increase a value and immediately use the result of the operator, you need the prefix form:
```js
let counter = 0;
console.log( ++counter ); // 1
```
- If youd like to increment a value but use its previous value, you need the postfix form:
```js
let counter = 0;
console.log( counter++ ); // 0
```
# --question--
## --text--
What is the difference in the result of the two console log statements in the JavaScript code below?
```js
let counter = 1;
console.log(2 * ++counter); // Statement A
let counter = 1;
console.log(2 * counter++); // Statement B
```
## --answers--
There is no difference; both alert statements will show the same result.
---
Statement A will log `4` because `++counter` increments the value before the multiplication. Statement B will log `2` because `counter++` increments the value after the multiplication.
---
Statement A will log `2` because `++counter` is a syntax error. Statement B will log `4` because `counter++` is the correct way to increment a counter.
---
Both statements will log `3` because the counter is incremented in both cases before the `console.log`.
## --video-solution--
2