fix(curriculum): Convert blockquote elements to triple backtick syntax for JavaScript Algorithms and Data Structures (#35992)

* fix: convert js algorithms and data structures

* fix: revert some blocks back to blockquote

* fix: reverted comparison code block to blockquotes

* fix: change js to json

Co-Authored-By: Oliver Eyton-Williams <ojeytonwilliams@gmail.com>

* fix: convert various section to triple backticks

* fix: Make the formatting consistent for comparisons
This commit is contained in:
Randell Dawson
2019-05-17 06:20:30 -07:00
committed by Tom
parent 7532555abf
commit 05f73ca409
157 changed files with 2154 additions and 243 deletions

View File

@ -11,7 +11,13 @@ We can access the data inside arrays using <code>indexes</code>.
Array indexes are written in the same bracket notation that strings use, except that instead of specifying a character, they are specifying an entry in the array. Like strings, arrays use <dfn>zero-based</dfn> indexing, so the first element in an array is element <code>0</code>.
<br />
<strong>Example</strong>
<blockquote>var array = [50,60,70];<br>array[0]; // equals 50<br>var data = array[1]; // equals 60</blockquote>
```js
var array = [50,60,70];
array[0]; // equals 50
var data = array[1]; // equals 60
```
<strong>Note</strong><br>There shouldn't be any spaces between the array name and the square brackets, like <code>array [0]</code>. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.
</section>

View File

@ -9,7 +9,19 @@ videoUrl: 'https://scrimba.com/c/ckND4Cq'
<section id='description'>
One way to think of a <dfn>multi-dimensional</dfn> array, is as an <em>array of arrays</em>. When you use brackets to access your array, the first set of brackets refers to the entries in the outer-most (the first level) array, and each additional pair of brackets refers to the next level of entries inside.
<strong>Example</strong>
<blockquote>var arr = [<br>&nbsp;&nbsp;[1,2,3],<br>&nbsp;&nbsp;[4,5,6],<br>&nbsp;&nbsp;[7,8,9],<br>&nbsp;&nbsp;[[10,11,12], 13, 14]<br>];<br>arr[3]; // equals [[10,11,12], 13, 14]<br>arr[3][0]; // equals [10,11,12]<br>arr[3][0][1]; // equals 11</blockquote>
```js
var arr = [
[1,2,3],
[4,5,6],
[7,8,9],
[[10,11,12], 13, 14]
];
arr[3]; // equals [[10,11,12], 13, 14]
arr[3][0]; // equals [10,11,12]
arr[3][0][1]; // equals 11
```
<strong>Note</strong><br>There shouldn't be any spaces between the array name and the square brackets, like <code>array [0][0]</code> and even this <code>array [0] [0]</code> is not allowed. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.
</section>

View File

@ -9,7 +9,30 @@ videoUrl: 'https://scrimba.com/c/cLeGDtZ'
<section id='description'>
As we have seen in earlier examples, objects can contain both nested objects and nested arrays. Similar to accessing nested objects, Array bracket notation can be chained to access nested arrays.
Here is an example of how to access a nested array:
<blockquote>var ourPets = [<br>&nbsp;&nbsp;{<br>&nbsp;&nbsp;&nbsp;&nbsp;animalType: "cat",<br>&nbsp;&nbsp;&nbsp;&nbsp;names: [<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"Meowzer",<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"Fluffy",<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"Kit-Cat"<br>&nbsp;&nbsp;&nbsp;&nbsp;]<br>&nbsp;&nbsp;},<br>&nbsp;&nbsp;{<br>&nbsp;&nbsp;&nbsp;&nbsp;animalType: "dog",<br>&nbsp;&nbsp;&nbsp;&nbsp;names: [<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"Spot",<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"Bowser",<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"Frankie"<br>&nbsp;&nbsp;&nbsp;&nbsp;]<br>&nbsp;&nbsp;}<br>];<br>ourPets[0].names[1]; // "Fluffy"<br>ourPets[1].names[0]; // "Spot"</blockquote>
```js
var ourPets = [
{
animalType: "cat",
names: [
"Meowzer",
"Fluffy",
"Kit-Cat"
]
},
{
animalType: "dog",
names: [
"Spot",
"Bowser",
"Frankie"
]
}
];
ourPets[0].names[1]; // "Fluffy"
ourPets[1].names[0]; // "Spot"
```
</section>
## Instructions

View File

@ -9,7 +9,24 @@ videoUrl: 'https://scrimba.com/c/cRnRnfa'
<section id='description'>
The sub-properties of objects can be accessed by chaining together the dot or bracket notation.
Here is a nested object:
<blockquote>var ourStorage = {<br>&nbsp;&nbsp;"desk": {<br>&nbsp;&nbsp;&nbsp;&nbsp;"drawer": "stapler"<br>&nbsp;&nbsp;},<br>&nbsp;&nbsp;"cabinet": {<br>&nbsp;&nbsp;&nbsp;&nbsp;"top drawer": { <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"folder1": "a file",<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"folder2": "secrets"<br>&nbsp;&nbsp;&nbsp;&nbsp;},<br>&nbsp;&nbsp;&nbsp;&nbsp;"bottom drawer": "soda"<br>&nbsp;&nbsp;}<br>};<br>ourStorage.cabinet["top drawer"].folder2; // "secrets"<br>ourStorage.desk.drawer; // "stapler"</blockquote>
```js
var ourStorage = {
"desk": {
"drawer": "stapler"
},
"cabinet": {
"top drawer": {
"folder1": "a file",
"folder2": "secrets"
},
"bottom drawer": "soda"
}
};
ourStorage.cabinet["top drawer"].folder2; // "secrets"
ourStorage.desk.drawer; // "stapler"
```
</section>
## Instructions

View File

@ -10,7 +10,18 @@ videoUrl: 'https://scrimba.com/c/cBvmEHP'
The second way to access the properties of an object is bracket notation (<code>[]</code>). If the property of the object you are trying to access has a space in its name, you will need to use bracket notation.
However, you can still use bracket notation on object properties without spaces.
Here is a sample of using bracket notation to read an object's property:
<blockquote>var myObj = {<br>&nbsp;&nbsp;"Space Name": "Kirk",<br>&nbsp;&nbsp;"More Space": "Spock",<br>&nbsp;&nbsp;"NoSpace": "USS Enterprise"<br>};<br>myObj["Space Name"]; // Kirk<br>myObj['More Space']; // Spock<br>myObj["NoSpace"]; // USS Enterprise</blockquote>
```js
var myObj = {
"Space Name": "Kirk",
"More Space": "Spock",
"NoSpace": "USS Enterprise"
};
myObj["Space Name"]; // Kirk
myObj['More Space']; // Spock
myObj["NoSpace"]; // USS Enterprise
```
Note that property names with spaces in them must be in quotes (single or double).
</section>

View File

@ -10,7 +10,16 @@ videoUrl: 'https://scrimba.com/c/cGryJs8'
There are two ways to access the properties of an object: dot notation (<code>.</code>) and bracket notation (<code>[]</code>), similar to an array.
Dot notation is what you use when you know the name of the property you're trying to access ahead of time.
Here is a sample of using dot notation (<code>.</code>) to read an object's property:
<blockquote>var myObj = {<br>&nbsp;&nbsp;prop1: "val1",<br>&nbsp;&nbsp;prop2: "val2"<br>};<br>var prop1val = myObj.prop1; // val1<br>var prop2val = myObj.prop2; // val2</blockquote>
```js
var myObj = {
prop1: "val1",
prop2: "val2"
};
var prop1val = myObj.prop1; // val1
var prop2val = myObj.prop2; // val2
```
</section>
## Instructions

View File

@ -9,11 +9,30 @@ videoUrl: 'https://scrimba.com/c/cnQyKur'
<section id='description'>
Another use of bracket notation on objects is to access a property which is stored as the value of a variable. This can be very useful for iterating through an object's properties or when accessing a lookup table.
Here is an example of using a variable to access a property:
<blockquote>var dogs = {<br>&nbsp;&nbsp;Fido: "Mutt",
Hunter: "Doberman",
Snoopie: "Beagle"<br>};<br>var myDog = "Hunter";<br>var myBreed = dogs[myDog];<br>console.log(myBreed); // "Doberman"</blockquote>
```js
var dogs = {
Fido: "Mutt", Hunter: "Doberman", Snoopie: "Beagle"
};
var myDog = "Hunter";
var myBreed = dogs[myDog];
console.log(myBreed); // "Doberman"
```
Another way you can use this concept is when the property's name is collected dynamically during the program execution, as follows:
<blockquote>var someObj = {<br>&nbsp;&nbsp;propName: "John"<br>};<br>function propPrefix(str) {<br>&nbsp;&nbsp;var s = "prop";<br>&nbsp;&nbsp;return s + str;<br>}<br>var someProp = propPrefix("Name"); // someProp now holds the value 'propName'<br>console.log(someObj[someProp]); // "John"</blockquote>
```js
var someObj = {
propName: "John"
};
function propPrefix(str) {
var s = "prop";
return s + str;
}
var someProp = propPrefix("Name"); // someProp now holds the value 'propName'
console.log(someObj[someProp]); // "John"
```
Note that we do <em>not</em> use quotes around the variable name when using it to access the property because we are using the <em>value</em> of the variable, not the <em>name</em>.
</section>

View File

@ -11,7 +11,11 @@ videoUrl: 'https://scrimba.com/c/cM2KBAG'
Now let's try to add two numbers using JavaScript.
JavaScript uses the <code>+</code> symbol as an addition operator when placed between two numbers.
<strong>Example:</strong>
<blockquote>myVar = 5 + 10; // assigned 15</blockquote>
```js
myVar = 5 + 10; // assigned 15
```
</section>
## Instructions

View File

@ -9,7 +9,22 @@ videoUrl: 'https://scrimba.com/c/c3JvVfg'
<section id='description'>
In a <code>switch</code> statement you may not be able to specify all possible values as <code>case</code> statements. Instead, you can add the <code>default</code> statement which will be executed if no matching <code>case</code> statements are found. Think of it like the final <code>else</code> statement in an <code>if/else</code> chain.
A <code>default</code> statement should be the last case.
<blockquote>switch (num) {<br>&nbsp;&nbsp;case value1:<br>&nbsp;&nbsp;&nbsp;&nbsp;statement1;<br>&nbsp;&nbsp;&nbsp;&nbsp;break;<br>&nbsp;&nbsp;case value2:<br>&nbsp;&nbsp;&nbsp;&nbsp;statement2;<br>&nbsp;&nbsp;&nbsp;&nbsp;break;<br>...<br>&nbsp;&nbsp;default:<br>&nbsp;&nbsp;&nbsp;&nbsp;defaultStatement;<br>&nbsp;&nbsp;&nbsp;&nbsp;break;<br>}</blockquote>
```js
switch (num) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
default:
defaultStatement;
break;
}
```
</section>
## Instructions

View File

@ -11,9 +11,26 @@ You may have heard the term <code>object</code> before.
Objects are similar to <code>arrays</code>, except that instead of using indexes to access and modify their data, you access the data in objects through what are called <code>properties</code>.
Objects are useful for storing data in a structured way, and can represent real world objects, like a cat.
Here's a sample cat object:
<blockquote>var cat = {<br>&nbsp;&nbsp;"name": "Whiskers",<br>&nbsp;&nbsp;"legs": 4,<br>&nbsp;&nbsp;"tails": 1,<br>&nbsp;&nbsp;"enemies": ["Water", "Dogs"]<br>};</blockquote>
```js
var cat = {
"name": "Whiskers",
"legs": 4,
"tails": 1,
"enemies": ["Water", "Dogs"]
};
```
In this example, all the properties are stored as strings, such as - <code>"name"</code>, <code>"legs"</code>, and <code>"tails"</code>. However, you can also use numbers as properties. You can even omit the quotes for single-word string properties, as follows:
<blockquote>var anotherObject = {<br>&nbsp;&nbsp;make: "Ford",<br>&nbsp;&nbsp;5: "five",<br>&nbsp;&nbsp;"model": "focus"<br>};</blockquote>
```js
var anotherObject = {
make: "Ford",
5: "five",
"model": "focus"
};
```
However, if your object has any non-string properties, JavaScript will automatically typecast them as strings.
</section>

View File

@ -8,7 +8,20 @@ videoUrl: 'https://scrimba.com/c/caeJgsw'
## Description
<section id='description'>
<code>if/else</code> statements can be chained together for complex logic. Here is <dfn>pseudocode</dfn> of multiple chained <code>if</code> / <code>else if</code> statements:
<blockquote>if (<em>condition1</em>) {<br>&nbsp;&nbsp;<em>statement1</em><br>} else if (<em>condition2</em>) {<br>&nbsp;&nbsp;<em>statement2</em><br>} else if (<em>condition3</em>) {<br>&nbsp;&nbsp;<em>statement3</em><br>. . .<br>} else {<br>&nbsp;&nbsp;<em>statementN</em><br>}</blockquote>
```js
if (condition1) {
statement1
} else if (condition2) {
statement2
} else if (condition3) {
statement3
. . .
} else {
statementN
}
```
</section>
## Instructions

View File

@ -10,9 +10,18 @@ videoUrl: 'https://scrimba.com/c/c7ynnTp'
Comments are lines of code that JavaScript will intentionally ignore. Comments are a great way to leave notes to yourself and to other people who will later need to figure out what that code does.
There are two ways to write comments in JavaScript:
Using <code>//</code> will tell JavaScript to ignore the remainder of the text on the current line:
<blockquote>// This is an in-line comment.</blockquote>
```js
// This is an in-line comment.
```
You can make a multi-line comment beginning with <code>/*</code> and ending with <code>*/</code>:
<blockquote>/* This is a<br>multi-line comment */</blockquote>
```js
/* This is a
multi-line comment */
```
<strong>Best Practice</strong><br>As you write code, you should regularly add comments to clarify the function of parts of your code. Good commenting can help communicate the intent of your code&mdash;both for others <em>and</em> for your future self.
</section>

View File

@ -9,10 +9,26 @@ videoUrl: 'https://scrimba.com/c/cKyVMAL'
<section id='description'>
There are many <dfn>Comparison Operators</dfn> in JavaScript. All of these operators return a boolean <code>true</code> or <code>false</code> value.
The most basic operator is the equality operator <code>==</code>. The equality operator compares two values and returns <code>true</code> if they're equivalent or <code>false</code> if they are not. Note that equality is different from assignment (<code>=</code>), which assigns the value at the right of the operator to a variable in the left.
<blockquote>function equalityTest(myVal) {<br>&nbsp;&nbsp;if (myVal == 10) {<br>&nbsp;&nbsp;&nbsp;&nbsp; return "Equal";<br>&nbsp;&nbsp;}<br>&nbsp;&nbsp;return "Not Equal";<br>}</blockquote>
```js
function equalityTest(myVal) {
if (myVal == 10) {
return "Equal";
}
return "Not Equal";
}
```
If <code>myVal</code> is equal to <code>10</code>, the equality operator returns <code>true</code>, so the code in the curly braces will execute, and the function will return <code>"Equal"</code>. Otherwise, the function will return <code>"Not Equal"</code>.
In order for JavaScript to compare two different <code>data types</code> (for example, <code>numbers</code> and <code>strings</code>), it must convert one type to another. This is known as "Type Coercion". Once it does, however, it can compare terms as follows:
<blockquote>1 == 1 // true<br>1 == 2 // false<br>1 == '1' // true<br>"3" == 3 // true</blockquote>
```js
1 == 1 // true
1 == 2 // false
1 == '1' // true
"3" == 3 // true
```
</section>
## Instructions

View File

@ -10,7 +10,14 @@ videoUrl: 'https://scrimba.com/c/cp6GbH4'
The greater than operator (<code>&gt;</code>) compares the values of two numbers. If the number to the left is greater than the number to the right, it returns <code>true</code>. Otherwise, it returns <code>false</code>.
Like the equality operator, greater than operator will convert data types of values while comparing.
<strong>Examples</strong>
<blockquote> 5 > 3 // true<br> 7 > '3' // true<br> 2 > 3 // false<br>'1' > 9 // false</blockquote>
```js
5 > 3 // true
7 > '3' // true
2 > 3 // false
'1' > 9 // false
```
</section>
## Instructions

View File

@ -10,7 +10,14 @@ videoUrl: 'https://scrimba.com/c/c6KBqtV'
The <code>greater than or equal to</code> operator (<code>&gt;=</code>) compares the values of two numbers. If the number to the left is greater than or equal to the number to the right, it returns <code>true</code>. Otherwise, it returns <code>false</code>.
Like the equality operator, <code>greater than or equal to</code> operator will convert data types while comparing.
<strong>Examples</strong>
<blockquote> 6 >= 6 // true<br> 7 >= '3' // true<br> 2 >= 3 // false<br>'7' >= 9 // false</blockquote>
```js
6 >= 6 // true
7 >= '3' // true
2 >= 3 // false
'7' >= 9 // false
```
</section>
## Instructions

View File

@ -9,7 +9,15 @@ videoUrl: 'https://scrimba.com/c/cdBm9Sr'
<section id='description'>
The inequality operator (<code>!=</code>) is the opposite of the equality operator. It means "Not Equal" and returns <code>false</code> where equality would return <code>true</code> and <em>vice versa</em>. Like the equality operator, the inequality operator will convert data types of values while comparing.
<strong>Examples</strong>
<blockquote>1 != 2 // true<br>1 != "1" // false<br>1 != '1' // false<br>1 != true // false<br>0 != false // false</blockquote>
```js
1 != 2 // true
1 != "1" // false
1 != '1' // false
1 != true // false
0 != false // false
```
</section>
## Instructions

View File

@ -9,7 +9,15 @@ videoUrl: 'https://scrimba.com/c/cNVRWtB'
<section id='description'>
The <dfn>less than</dfn> operator (<code>&lt;</code>) compares the values of two numbers. If the number to the left is less than the number to the right, it returns <code>true</code>. Otherwise, it returns <code>false</code>. Like the equality operator, <dfn>less than</dfn> operator converts data types while comparing.
<strong>Examples</strong>
<blockquote>2 &lt; 5 // true<br>'3' &lt; 7 // true<br>5 &lt; 5 // false<br>3 &lt; 2 // false<br>'8' &lt; 4 // false</blockquote>
```js
2 < 5 // true
'3' < 7 // true
5 < 5 // false
3 < 2 // false
'8' < 4 // false
```
</section>
## Instructions

View File

@ -9,7 +9,15 @@ videoUrl: 'https://scrimba.com/c/cNVR7Am'
<section id='description'>
The <code>less than or equal to</code> operator (<code>&lt;=</code>) compares the values of two numbers. If the number to the left is less than or equal to the number to the right, it returns <code>true</code>. If the number on the left is greater than the number on the right, it returns <code>false</code>. Like the equality operator, <code>less than or equal to</code> converts data types.
<strong>Examples</strong>
<blockquote>4 &lt;= 5 // true<br>'7' &lt;= 7 // true<br>5 &lt;= 5 // true<br>3 &lt;= 2 // false<br>'8' &lt;= 4 // false</blockquote>
```js
4 <= 5 // true
'7' <= 7 // true
5 <= 5 // true
3 <= 2 // false
'8' <= 4 // false
```
</section>
## Instructions

View File

@ -10,7 +10,12 @@ videoUrl: 'https://scrimba.com/c/cy87atr'
Strict equality (<code>===</code>) is the counterpart to the equality operator (<code>==</code>). However, unlike the equality operator, which attempts to convert both values being compared to a common type, the strict equality operator does not perform a type conversion.
If the values being compared have different types, they are considered unequal, and the strict equality operator will return false.
<strong>Examples</strong>
<blockquote>3 === 3 // true<br>3 === '3' // false</blockquote>
```js
3 === 3 // true
3 === '3' // false
```
In the second example, <code>3</code> is a <code>Number</code> type and <code>'3'</code> is a <code>String</code> type.
</section>

View File

@ -9,7 +9,13 @@ videoUrl: 'https://scrimba.com/c/cKekkUy'
<section id='description'>
The strict inequality operator (<code>!==</code>) is the logical opposite of the strict equality operator. It means "Strictly Not Equal" and returns <code>false</code> where strict equality would return <code>true</code> and <em>vice versa</em>. Strict inequality will not convert data types.
<strong>Examples</strong>
<blockquote>3 !== 3 // false<br>3 !== '3' // true<br>4 !== 3 // true</blockquote>
```js
3 !== 3 // false
3 !== '3' // true
4 !== 3 // true
```
</section>
## Instructions

View File

@ -9,9 +9,25 @@ videoUrl: 'https://scrimba.com/c/cvbRVtr'
<section id='description'>
Sometimes you will need to test more than one thing at a time. The <dfn>logical and</dfn> operator (<code>&&</code>) returns <code>true</code> if and only if the <dfn>operands</dfn> to the left and right of it are true.
The same effect could be achieved by nesting an if statement inside another if:
<blockquote>if (num > 5) {<br>&nbsp;&nbsp;if (num < 10) {<br>&nbsp;&nbsp;&nbsp;&nbsp;return "Yes";<br>&nbsp;&nbsp;}<br>}<br>return "No";</blockquote>
```js
if (num > 5) {
if (num < 10) {
return "Yes";
}
}
return "No";
```
will only return "Yes" if <code>num</code> is greater than <code>5</code> and less than <code>10</code>. The same logic can be written as:
<blockquote>if (num > 5 && num < 10) {<br>&nbsp;&nbsp;return "Yes";<br>}<br>return "No";</blockquote>
```js
if (num > 5 && num < 10) {
return "Yes";
}
return "No";
```
</section>
## Instructions

View File

@ -10,9 +10,26 @@ videoUrl: 'https://scrimba.com/c/cEPrGTN'
The <dfn>logical or</dfn> operator (<code>||</code>) returns <code>true</code> if either of the <dfn>operands</dfn> is <code>true</code>. Otherwise, it returns <code>false</code>.
The <dfn>logical or</dfn> operator is composed of two pipe symbols (<code>|</code>). This can typically be found between your Backspace and Enter keys.
The pattern below should look familiar from prior waypoints:
<blockquote>if (num > 10) {<br>&nbsp;&nbsp;return "No";<br>}<br>if (num < 5) {<br>&nbsp;&nbsp;return "No";<br>}<br>return "Yes";</blockquote>
```js
if (num > 10) {
return "No";
}
if (num < 5) {
return "No";
}
return "Yes";
```
will return "Yes" only if <code>num</code> is between <code>5</code> and <code>10</code> (5 and 10 included). The same logic can be written as:
<blockquote>if (num > 10 || num < 5) {<br>&nbsp;&nbsp;return "No";<br>}<br>return "Yes";</blockquote>
```js
if (num > 10 || num < 5) {
return "No";
}
return "Yes";
```
</section>
## Instructions

View File

@ -11,7 +11,13 @@ In programming, it is common to use assignments to modify the contents of a vari
<code>myVar = myVar + 5;</code>
to add <code>5</code> to <code>myVar</code>. Since this is such a common pattern, there are operators which do both a mathematical operation and assignment in one step.
One such operator is the <code>+=</code> operator.
<blockquote>var myVar = 1;<br>myVar += 5;<br>console.log(myVar); // Returns 6</blockquote>
```js
var myVar = 1;
myVar += 5;
console.log(myVar); // Returns 6
```
</section>
## Instructions

View File

@ -9,7 +9,11 @@ videoUrl: 'https://scrimba.com/c/cNpM8AN'
<section id='description'>
In JavaScript, when the <code>+</code> operator is used with a <code>String</code> value, it is called the <dfn>concatenation</dfn> operator. You can build a new string out of other strings by <dfn>concatenating</dfn> them together.
<strong>Example</strong>
<blockquote>'My name is Alan,' + ' I concatenate.'</blockquote>
```js
'My name is Alan,' + ' I concatenate.'
```
<strong>Note</strong><br>Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.
</section>

View File

@ -10,7 +10,14 @@ videoUrl: 'https://scrimba.com/c/c2R6BHa'
A for loop can also count backwards, so long as we can define the right conditions.
In order to count backwards by twos, we'll need to change our <code>initialization</code>, <code>condition</code>, and <code>final-expression</code>.
We'll start at <code>i = 10</code> and loop while <code>i &#62; 0</code>. We'll decrement <code>i</code> by 2 each loop with <code>i -= 2</code>.
<blockquote>var ourArray = [];<br>for (var i=10; i &#62; 0; i-=2) {<br>&nbsp;&nbsp;ourArray.push(i);<br>}</blockquote>
```js
var ourArray = [];
for (var i=10; i > 0; i-=2) {
ourArray.push(i);
}
```
<code>ourArray</code> will now contain <code>[10,8,6,4,2]</code>.
Let's change our <code>initialization</code> and <code>final-expression</code> so we can count backward by twos by odd numbers.
</section>

View File

@ -12,7 +12,11 @@ For example, computers distinguish between numbers, such as the number <code>12<
<dfn>Variables</dfn> allow computers to store and manipulate data in a dynamic fashion. They do this by using a "label" to point to the data rather than using the data itself. Any of the seven data types may be stored in a variable.
<code>Variables</code> are similar to the x and y variables you use in mathematics, which means they're a simple name to represent the data we want to refer to. Computer <code>variables</code> differ from mathematical variables in that they can store different values at different times.
We tell JavaScript to create or <dfn>declare</dfn> a variable by putting the keyword <code>var</code> in front of it, like so:
<blockquote>var ourName;</blockquote>
```js
var ourName;
```
creates a <code>variable</code> called <code>ourName</code>. In JavaScript we end statements with semicolons.
<code>Variable</code> names can be made up of numbers, letters, and <code>$</code> or <code>_</code>, but may not contain spaces or start with a number.
</section>

View File

@ -11,7 +11,11 @@ We can also divide one number by another.
JavaScript uses the <code>/</code> symbol for division.
<strong>Example</strong>
<blockquote>myVar = 16 / 2; // assigned 8</blockquote>
```js
myVar = 16 / 2; // assigned 8
```
</section>

View File

@ -9,7 +9,15 @@ videoUrl: 'https://scrimba.com/c/c2QwKH2'
<section id='description'>
It is possible to have both <dfn>local</dfn> and <dfn>global</dfn> variables with the same name. When you do this, the <code>local</code> variable takes precedence over the <code>global</code> variable.
In this example:
<blockquote>var someVar = "Hat";<br>function myFun() {<br>&nbsp;&nbsp;var someVar = "Head";<br>&nbsp;&nbsp;return someVar;<br>}</blockquote>
```js
var someVar = "Hat";
function myFun() {
var someVar = "Head";
return someVar;
}
```
The function <code>myFun</code> will return <code>"Head"</code> because the <code>local</code> version of the variable is present.
</section>

View File

@ -8,7 +8,17 @@ videoUrl: 'https://scrimba.com/c/caeJ2hm'
## Description
<section id='description'>
If you have multiple conditions that need to be addressed, you can chain <code>if</code> statements together with <code>else if</code> statements.
<blockquote>if (num > 15) {<br>&nbsp;&nbsp;return "Bigger than 15";<br>} else if (num < 5) {<br>&nbsp;&nbsp;return "Smaller than 5";<br>} else {<br>&nbsp;&nbsp;return "Between 5 and 15";<br>}</blockquote>
```js
if (num > 15) {
return "Bigger than 15";
} else if (num < 5) {
return "Smaller than 5";
} else {
return "Between 5 and 15";
}
```
</section>
## Instructions

View File

@ -8,7 +8,15 @@ videoUrl: 'https://scrimba.com/c/cek4Efq'
## Description
<section id='description'>
When a condition for an <code>if</code> statement is true, the block of code following it is executed. What about when that condition is false? Normally nothing would happen. With an <code>else</code> statement, an alternate block of code can be executed.
<blockquote>if (num > 10) {<br>&nbsp;&nbsp;return "Bigger than 10";<br>} else {<br>&nbsp;&nbsp;return "10 or Less";<br>}</blockquote>
```js
if (num > 10) {
return "Bigger than 10";
} else {
return "10 or Less";
}
```
</section>
## Instructions

View File

@ -9,7 +9,14 @@ videoUrl: 'https://scrimba.com/c/cm8n7T9'
<section id='description'>
For loops don't have to iterate one at a time. By changing our <code>final-expression</code>, we can count by even numbers.
We'll start at <code>i = 0</code> and loop while <code>i &#60; 10</code>. We'll increment <code>i</code> by 2 each loop with <code>i += 2</code>.
<blockquote>var ourArray = [];<br>for (var i = 0; i &#60; 10; i += 2) {<br>&nbsp;&nbsp;ourArray.push(i);<br>}</blockquote>
```js
var ourArray = [];
for (var i = 0; i < 10; i += 2) {
ourArray.push(i);
}
```
<code>ourArray</code> will now contain <code>[0,2,4,6,8]</code>.
Let's change our <code>initialization</code> so we can count by odd numbers.
</section>

View File

@ -8,7 +8,14 @@ videoUrl: 'https://scrimba.com/c/caeR3HB'
## Description
<section id='description'>
A common task in JavaScript is to iterate through the contents of an array. One way to do that is with a <code>for</code> loop. This code will output each element of the array <code>arr</code> to the console:
<blockquote>var arr = [10,9,8,7,6];<br>for (var i = 0; i < arr.length; i++) {<br>&nbsp;&nbsp; console.log(arr[i]);<br>}</blockquote>
```js
var arr = [10,9,8,7,6];
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
```
Remember that Arrays have zero-based numbering, which means the last index of the array is length - 1. Our <dfn>condition</dfn> for this loop is <code>i < arr.length</code>, which stops when <code>i</code> is at length - 1.
</section>

View File

@ -8,13 +8,40 @@ videoUrl: 'https://scrimba.com/c/cDqWGcp'
## Description
<section id='description'>
The next type of loop you will learn is called a <code>do...while</code> loop. It is called a <code>do...while</code> loop because it will first <code>do</code> one pass of the code inside the loop no matter what, and then continue to run the loop <code>while</code> the specified condition evaluates to <code>true</code>.
<blockquote>var ourArray = [];<br>var i = 0;<br>do {<br>&nbsp;&nbsp;ourArray.push(i);<br>&nbsp;&nbsp;i++;<br>} while (i < 5);</blockquote>
```js
var ourArray = [];
var i = 0;
do {
ourArray.push(i);
i++;
} while (i < 5);
```
The example above behaves similar to other types of loops, and the resulting array will look like <code>[0, 1, 2, 3, 4]</code>. However, what makes the <code>do...while</code> different from other loops is how it behaves when the condition fails on the first check. Let's see this in action:
Here is a regular <code>while</code> loop that will run the code in the loop as long as <code>i < 5</code>:
<blockquote>var ourArray = []; <br>var i = 5;<br>while (i < 5) {<br>&nbsp;&nbsp;ourArray.push(i);<br>&nbsp;&nbsp;i++;<br>}</blockquote>
```js
var ourArray = [];
var i = 5;
while (i < 5) {
ourArray.push(i);
i++;
}
```
In this example, we initialize the value of <code>myArray</code> to an empty array and the value of <code>i</code> to 5. When we execute the <code>while</code> loop, the condition evaluates to <code>false</code> because <code>i</code> is not less than 5, so we do not execute the code inside the loop. The result is that <code>ourArray</code> will end up with no values added to it, and it will still look like <code>[]</code> when all of the code in the example above has completed running.
Now, take a look at a <code>do...while</code> loop:
<blockquote>var ourArray = []; <br>var i = 5;<br>do {<br>&nbsp;&nbsp;ourArray.push(i);<br>&nbsp;&nbsp;i++;<br>} while (i < 5);</blockquote>
```js
var ourArray = [];
var i = 5;
do {
ourArray.push(i);
i++;
} while (i < 5);
```
In this case, we initialize the value of <code>i</code> to 5, just like we did with the <code>while</code> loop. When we get to the next line, there is no condition to evaluate, so we go to the code inside the curly braces and execute it. We will add a single element to the array and then increment <code>i</code> before we get to the condition check. When we finally evaluate the condition <code>i < 5</code> on the last line, we see that <code>i</code> is now 6, which fails the conditional check, so we exit the loop and are done. At the end of the above example, the value of <code>ourArray</code> is <code>[5]</code>.
Essentially, a <code>do...while</code> loop ensures that the code inside the loop will run at least once.
Let's try getting a <code>do...while</code> loop to work by pushing values to an array.

View File

@ -15,7 +15,14 @@ The <code>initialization</code> statement is executed one time only before the l
The <code>condition</code> statement is evaluated at the beginning of every loop iteration and will continue as long as it evaluates to <code>true</code>. When <code>condition</code> is <code>false</code> at the start of the iteration, the loop will stop executing. This means if <code>condition</code> starts as <code>false</code>, your loop will never execute.
The <code>final-expression</code> is executed at the end of each loop iteration, prior to the next <code>condition</code> check and is usually used to increment or decrement your loop counter.
In the following example we initialize with <code>i = 0</code> and iterate while our condition <code>i &#60; 5</code> is true. We'll increment <code>i</code> by <code>1</code> in each loop iteration with <code>i++</code> as our <code>final-expression</code>.
<blockquote>var ourArray = [];<br>for (var i = 0; i &#60; 5; i++) {<br>&nbsp;&nbsp;ourArray.push(i);<br>}</blockquote>
```js
var ourArray = [];
for (var i = 0; i < 5; i++) {
ourArray.push(i);
}
```
<code>ourArray</code> will now contain <code>[0,1,2,3,4]</code>.
</section>

View File

@ -9,7 +9,16 @@ videoUrl: 'https://scrimba.com/c/c8QbnCM'
<section id='description'>
You can run the same code multiple times by using a loop.
The first type of loop we will learn is called a <code>while</code> loop because it runs "while" a specified condition is true and stops once that condition is no longer true.
<blockquote>var ourArray = [];<br>var i = 0;<br>while(i &#60; 5) {<br>&nbsp;&nbsp;ourArray.push(i);<br>&nbsp;&nbsp;i++;<br>}</blockquote>
```js
var ourArray = [];
var i = 0;
while(i < 5) {
ourArray.push(i);
i++;
}
```
Let's try getting a while loop to work by pushing values to an array.
</section>

View File

@ -9,7 +9,16 @@ videoUrl: 'https://scrimba.com/c/cd62NhM'
<section id='description'>
Variables which are declared within a function, as well as the function parameters have <dfn>local</dfn> scope. That means, they are only visible within that function.
Here is a function <code>myTest</code> with a local variable called <code>loc</code>.
<blockquote>function myTest() {<br>&nbsp;&nbsp;var loc = "foo";<br>&nbsp;&nbsp;console.log(loc);<br>}<br>myTest(); // logs "foo"<br>console.log(loc); // loc is not defined</blockquote>
```js
function myTest() {
var loc = "foo";
console.log(loc);
}
myTest(); // logs "foo"
console.log(loc); // loc is not defined
```
<code>loc</code> is not defined outside of the function.
</section>

View File

@ -11,11 +11,40 @@ Order is important in <code>if</code>, <code>else if</code> statements.
The function is executed from top to bottom so you will want to be careful of what statement comes first.
Take these two functions as an example.
Here's the first:
<blockquote>function foo(x) {<br>&nbsp;&nbsp;if (x < 1) {<br>&nbsp;&nbsp;&nbsp;&nbsp;return "Less than one";<br>&nbsp;&nbsp;} else if (x < 2) {<br>&nbsp;&nbsp;&nbsp;&nbsp;return "Less than two";<br>&nbsp;&nbsp;} else {<br>&nbsp;&nbsp;&nbsp;&nbsp;return "Greater than or equal to two";<br>&nbsp;&nbsp;}<br>}</blockquote>
```js
function foo(x) {
if (x < 1) {
return "Less than one";
} else if (x < 2) {
return "Less than two";
} else {
return "Greater than or equal to two";
}
}
```
And the second just switches the order of the statements:
<blockquote>function bar(x) {<br>&nbsp;&nbsp;if (x < 2) {<br>&nbsp;&nbsp;&nbsp;&nbsp;return "Less than two";<br>&nbsp;&nbsp;} else if (x < 1) {<br>&nbsp;&nbsp;&nbsp;&nbsp;return "Less than one";<br>&nbsp;&nbsp;} else {<br>&nbsp;&nbsp;&nbsp;&nbsp;return "Greater than or equal to two";<br>&nbsp;&nbsp;}<br>}</blockquote>
```js
function bar(x) {
if (x < 2) {
return "Less than two";
} else if (x < 1) {
return "Less than one";
} else {
return "Greater than or equal to two";
}
}
```
While these two functions look nearly identical if we pass a number to both we get different outputs.
<blockquote>foo(0) // "Less than one"<br>bar(0) // "Less than two"</blockquote>
```js
foo(0) // "Less than one"
bar(0) // "Less than two"
```
</section>
## Instructions

View File

@ -10,7 +10,14 @@ videoUrl: 'https://scrimba.com/c/cRbVZAB'
Another way to change the data in an array is with the <code>.pop()</code> function.
<code>.pop()</code> is used to "pop" a value off of the end of an array. We can store this "popped off" value by assigning it to a variable. In other words, <code>.pop()</code> removes the last element from an array and returns that element.
Any type of entry can be "popped" off of an array - numbers, strings, even nested arrays.
<blockquote><code>var threeArr = [1, 4, 6];<br> var oneDown = threeArr.pop();<br> console.log(oneDown); // Returns 6<br> console.log(threeArr); // Returns [1, 4]</code></blockquote>
```js
var threeArr = [1, 4, 6];
var oneDown = threeArr.pop();
console.log(oneDown); // Returns 6
console.log(threeArr); // Returns [1, 4]
```
</section>
## Instructions

View File

@ -9,7 +9,13 @@ videoUrl: 'https://scrimba.com/c/cnqmVtJ'
<section id='description'>
An easy way to append data to the end of an array is via the <code>push()</code> function.
<code>.push()</code> takes one or more <dfn>parameters</dfn> and "pushes" them onto the end of the array.
<blockquote>var arr = [1,2,3];<br>arr.push(4);<br>// arr is now [1,2,3,4]</blockquote>
```js
var arr = [1,2,3];
arr.push(4);
// arr is now [1,2,3,4]
```
</section>
## Instructions

View File

@ -9,11 +9,41 @@ videoUrl: 'https://scrimba.com/c/c9yNMfR'
<section id='description'>
Sometimes you may want to store data in a flexible <dfn>Data Structure</dfn>. A JavaScript object is one way to handle flexible data. They allow for arbitrary combinations of <dfn>strings</dfn>, <dfn>numbers</dfn>, <dfn>booleans</dfn>, <dfn>arrays</dfn>, <dfn>functions</dfn>, and <dfn>objects</dfn>.
Here's an example of a complex data structure:
<blockquote>var ourMusic = [<br>&nbsp;&nbsp;{<br>&nbsp;&nbsp;&nbsp;&nbsp;"artist": "Daft Punk",<br>&nbsp;&nbsp;&nbsp;&nbsp;"title": "Homework",<br>&nbsp;&nbsp;&nbsp;&nbsp;"release_year": 1997,<br>&nbsp;&nbsp;&nbsp;&nbsp;"formats": [ <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"CD", <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"Cassette", <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"LP"<br>&nbsp;&nbsp;&nbsp;&nbsp;],<br>&nbsp;&nbsp;&nbsp;&nbsp;"gold": true<br>&nbsp;&nbsp;}<br>];</blockquote>
```js
var ourMusic = [
{
"artist": "Daft Punk",
"title": "Homework",
"release_year": 1997,
"formats": [
"CD",
"Cassette",
"LP"
],
"gold": true
}
];
```
This is an array which contains one object inside. The object has various pieces of <dfn>metadata</dfn> about an album. It also has a nested <code>"formats"</code> array. If you want to add more album records, you can do this by adding records to the top level array.
Objects hold data in a property, which has a key-value format. In the example above, <code>"artist": "Daft Punk"</code> is a property that has a key of <code>"artist"</code> and a value of <code>"Daft Punk"</code>.
<a href='http://www.json.org/' target=_blank>JavaScript Object Notation</a> or <code>JSON</code> is a related data interchange format used to store data.
<blockquote>{<br>&nbsp;&nbsp;"artist": "Daft Punk",<br>&nbsp;&nbsp;"title": "Homework",<br>&nbsp;&nbsp;"release_year": 1997,<br>&nbsp;&nbsp;"formats": [ <br>&nbsp;&nbsp;&nbsp;&nbsp;"CD",<br>&nbsp;&nbsp;&nbsp;&nbsp;"Cassette",<br>&nbsp;&nbsp;&nbsp;&nbsp;"LP"<br>&nbsp;&nbsp;],<br>&nbsp;&nbsp;"gold": true<br>}</blockquote>
```json
{
"artist": "Daft Punk",
"title": "Homework",
"release_year": 1997,
"formats": [
"CD",
"Cassette",
"LP"
],
"gold": true
}
```
<strong>Note</strong><br>You will need to place a comma after every object in the array, unless it is the last object in the array.
</section>

View File

@ -9,7 +9,12 @@ videoUrl: 'https://scrimba.com/c/czQM4A8'
<section id='description'>
Unlike strings, the entries of arrays are <dfn>mutable</dfn> and can be changed freely.
<strong>Example</strong>
<blockquote>var ourArray = [50,40,30];<br>ourArray[0] = 15; // equals [15,40,30]</blockquote>
```js
var ourArray = [50,40,30];
ourArray[0] = 15; // equals [15,40,30]
```
<strong>Note</strong><br>There shouldn't be any spaces between the array name and the square brackets, like <code>array [0]</code>. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.
</section>

View File

@ -8,7 +8,19 @@ videoUrl: 'https://scrimba.com/c/cdBKWCV'
## Description
<section id='description'>
If the <code>break</code> statement is omitted from a <code>switch</code> statement's <code>case</code>, the following <code>case</code> statement(s) are executed until a <code>break</code> is encountered. If you have multiple inputs with the same output, you can represent them in a <code>switch</code> statement like this:
<blockquote>switch(val) {<br>&nbsp;&nbsp;case 1:<br>&nbsp;&nbsp;case 2:<br>&nbsp;&nbsp;case 3:<br>&nbsp;&nbsp;&nbsp;&nbsp;result = "1, 2, or 3";<br>&nbsp;&nbsp;&nbsp;&nbsp;break;<br>&nbsp;&nbsp;case 4:<br>&nbsp;&nbsp;&nbsp;&nbsp;result = "4 alone";<br>}</blockquote>
```js
switch(val) {
case 1:
case 2:
case 3:
result = "1, 2, or 3";
break;
case 4:
result = "4 alone";
}
```
Cases for 1, 2, and 3 will all produce the same result.
</section>

View File

@ -11,7 +11,11 @@ We can also multiply one number by another.
JavaScript uses the <code>*</code> symbol for multiplication of two numbers.
<strong>Example</strong>
<blockquote>myVar = 13 * 13; // assigned 169</blockquote>
```js
myVar = 13 * 13; // assigned 169
```
</section>

View File

@ -8,7 +8,18 @@ videoUrl: 'https://scrimba.com/c/cRn6GHM'
## Description
<section id='description'>
If you have a multi-dimensional array, you can use the same logic as the prior waypoint to loop through both the array and any sub-arrays. Here is an example:
<blockquote>var arr = [<br>&nbsp;&nbsp;[1,2], [3,4], [5,6]<br>];<br>for (var i=0; i &lt; arr.length; i++) {<br>&nbsp;&nbsp;for (var j=0; j &lt; arr[i].length; j++) {<br>&nbsp;&nbsp;&nbsp;&nbsp;console.log(arr[i][j]);<br>&nbsp;&nbsp;}<br>}</blockquote>
```js
var arr = [
[1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) {
console.log(arr[i][j]);
}
}
```
This outputs each sub-element in <code>arr</code> one at a time. Note that for the inner loop, we are checking the <code>.length</code> of <code>arr[i]</code>, since <code>arr[i]</code> is itself an array.
</section>

View File

@ -9,7 +9,13 @@ videoUrl: 'https://scrimba.com/c/cy8rahW'
<section id='description'>
<dfn>Parameters</dfn> are variables that act as placeholders for the values that are to be input to a function when it is called. When a function is defined, it is typically defined along with one or more parameters. The actual values that are input (or <dfn>"passed"</dfn>) into a function when it is called are known as <dfn>arguments</dfn>.
Here is a function with two parameters, <code>param1</code> and <code>param2</code>:
<blockquote>function testFun(param1, param2) {<br>&nbsp;&nbsp;console.log(param1, param2);<br>}</blockquote>
```js
function testFun(param1, param2) {
console.log(param1, param2);
}
```
Then we can call <code>testFun</code>:
<code>testFun("Hello", "World");</code>
We have passed two arguments, <code>"Hello"</code> and <code>"World"</code>. Inside the function, <code>param1</code> will equal "Hello" and <code>param2</code> will equal "World". Note that you could call <code>testFun</code> again with different arguments and the parameters would take on the value of the new arguments.

View File

@ -10,9 +10,19 @@ videoUrl: 'https://scrimba.com/c/cm8PqCa'
In the last two challenges, we learned about the equality operator (<code>==</code>) and the strict equality operator (<code>===</code>). Let's do a quick review and practice using these operators some more.
If the values being compared are not of the same type, the equality operator will perform a type conversion, and then evaluate the values. However, the strict equality operator will compare both the data type and value as-is, without converting one type to the other.
<strong>Examples</strong>
<blockquote>3 == '3' // returns true because JavaScript performs type conversion from string to number<br>3 === '3' // returns false because the types are different and type conversion is not performed</blockquote>
```js
3 == '3' // returns true because JavaScript performs type conversion from string to number
3 === '3' // returns false because the types are different and type conversion is not performed
```
<strong>Note</strong><br>In JavaScript, you can determine the type of a variable or a value with the <code>typeof</code> operator, as follows:
<blockquote>typeof 3 // returns 'number'<br>typeof '3' // returns 'string'</blockquote>
```js
typeof 3 // returns 'number'
typeof '3' // returns 'string'
```
</section>
## Instructions

View File

@ -8,11 +8,25 @@ videoUrl: 'https://scrimba.com/c/cbQmnhM'
## Description
<section id='description'>
<dfn>String</dfn> values in JavaScript may be written with single or double quotes, as long as you start and end with the same type of quote. Unlike some other programming languages, single and double quotes work the same in JavaScript.
<blockquote>doubleQuoteStr = "This is a string"; <br/>singleQuoteStr = 'This is also a string';</blockquote>
```js
doubleQuoteStr = "This is a string";
singleQuoteStr = 'This is also a string';
```
The reason why you might want to use one type of quote over the other is if you want to use both in a string. This might happen if you want to save a conversation in a string and have the conversation in quotes. Another use for it would be saving an <code>&#60;a&#62;</code> tag with various attributes in quotes, all within a string.
<blockquote>conversation = 'Finn exclaims to Jake, "Algebraic!"';</blockquote>
```js
conversation = 'Finn exclaims to Jake, "Algebraic!"';
```
However, this becomes a problem if you need to use the outermost quotes within it. Remember, a string has the same kind of quote at the beginning and end. But if you have that same quote somewhere in the middle, the string will stop early and throw an error.
<blockquote>goodStr = 'Jake asks Finn, "Hey, let\'s go on an adventure?"'; <br/>badStr = 'Finn responds, "Let's go!"'; // Throws an error</blockquote>
```js
goodStr = 'Jake asks Finn, "Hey, let\'s go on an adventure?"';
badStr = 'Finn responds, "Let's go!"'; // Throws an error
```
In the <dfn>goodStr</dfn> above, you can use both quotes safely by using the backslash <code>\</code> as an escape character.
<strong>Note</strong><br/>The backslash <code>\</code> should not be confused with the forward slash <code>/</code>. They do not do the same thing.
</section>

View File

@ -8,9 +8,32 @@ videoUrl: 'https://scrimba.com/c/c3JE8fy'
## Description
<section id='description'>
If you have many options to choose from, a <code>switch</code> statement can be easier to write than many chained <code>if</code>/<code>else if</code> statements. The following:
<blockquote>if (val === 1) {<br>&nbsp;&nbsp;answer = "a";<br>} else if (val === 2) {<br>&nbsp;&nbsp;answer = "b";<br>} else {<br>&nbsp;&nbsp;answer = "c";<br>}</blockquote>
```js
if (val === 1) {
answer = "a";
} else if (val === 2) {
answer = "b";
} else {
answer = "c";
}
```
can be replaced with:
<blockquote>switch(val) {<br>&nbsp;&nbsp;case 1:<br>&nbsp;&nbsp;&nbsp;&nbsp;answer = "a";<br>&nbsp;&nbsp;&nbsp;&nbsp;break;<br>&nbsp;&nbsp;case 2:<br>&nbsp;&nbsp;&nbsp;&nbsp;answer = "b";<br>&nbsp;&nbsp;&nbsp;&nbsp;break;<br>&nbsp;&nbsp;default:<br>&nbsp;&nbsp;&nbsp;&nbsp;answer = "c";<br>}</blockquote>
```js
switch(val) {
case 1:
answer = "a";
break;
case 2:
answer = "b";
break;
default:
answer = "c";
}
```
</section>
## Instructions

View File

@ -9,7 +9,14 @@ videoUrl: 'https://scrimba.com/c/cy87wue'
<section id='description'>
We can pass values into a function with <dfn>arguments</dfn>. You can use a <code>return</code> statement to send a value back out of a function.
<strong>Example</strong>
<blockquote>function plusThree(num) {<br>&nbsp;&nbsp;return num + 3;<br>}<br>var answer = plusThree(5); // 8</blockquote>
```js
function plusThree(num) {
return num + 3;
}
var answer = plusThree(5); // 8
```
<code>plusThree</code> takes an <dfn>argument</dfn> for <code>num</code> and returns a value equal to <code>num + 3</code>.
</section>

View File

@ -9,7 +9,16 @@ videoUrl: 'https://scrimba.com/c/cQe39Sq'
<section id='description'>
When a <code>return</code> statement is reached, the execution of the current function stops and control returns to the calling location.
<strong>Example</strong>
<blockquote>function myFun() {<br>&nbsp;&nbsp;console.log("Hello");<br>&nbsp;&nbsp;return "World";<br>&nbsp;&nbsp;console.log("byebye")<br>}<br>myFun();</blockquote>
```js
function myFun() {
console.log("Hello");
return "World";
console.log("byebye")
}
myFun();
```
The above outputs "Hello" to the console, returns "World", but <code>"byebye"</code> is never output, because the function exits at the <code>return</code> statement.
</section>

View File

@ -9,9 +9,25 @@ videoUrl: 'https://scrimba.com/c/cp62qAQ'
<section id='description'>
You may recall from <a href="learn/javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator" target="_blank">Comparison with the Equality Operator</a> that all comparison operators return a boolean <code>true</code> or <code>false</code> value.
Sometimes people use an if/else statement to do a comparison, like this:
<blockquote>function isEqual(a,b) {<br>&nbsp;&nbsp;if (a === b) {<br>&nbsp;&nbsp;&nbsp;&nbsp;return true;<br>&nbsp;&nbsp;} else {<br>&nbsp;&nbsp;&nbsp;&nbsp;return false;<br>&nbsp;&nbsp;}<br>}</blockquote>
```js
function isEqual(a,b) {
if (a === b) {
return true;
} else {
return false;
}
}
```
But there's a better way to do this. Since <code>===</code> returns <code>true</code> or <code>false</code>, we can return the result of the comparison:
<blockquote>function isEqual(a,b) {<br>&nbsp;&nbsp;return a === b;<br>}</blockquote>
```js
function isEqual(a,b) {
return a === b;
}
```
</section>
## Instructions

View File

@ -9,7 +9,22 @@ videoUrl: 'https://scrimba.com/c/c4mv4fm'
<section id='description'>
If you have many options to choose from, use a <code>switch</code> statement. A <code>switch</code> statement tests a value and can have many <code>case</code> statements which define various possible values. Statements are executed from the first matched <code>case</code> value until a <code>break</code> is encountered.
Here is a <dfn>pseudocode</dfn> example:
<blockquote>switch(num) {<br>&nbsp;&nbsp;case value1:<br>&nbsp;&nbsp;&nbsp;&nbsp;statement1;<br>&nbsp;&nbsp;&nbsp;&nbsp;break;<br>&nbsp;&nbsp;case value2:<br>&nbsp;&nbsp;&nbsp;&nbsp;statement2;<br>&nbsp;&nbsp;&nbsp;&nbsp;break;<br>...<br>&nbsp;&nbsp;case valueN:<br>&nbsp;&nbsp;&nbsp;&nbsp;statementN;<br>&nbsp;&nbsp;&nbsp;&nbsp;break;<br>}</blockquote>
```js
switch(num) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
case valueN:
statementN;
break;
}
```
<code>case</code> values are tested with strict equality (<code>===</code>). The <code>break</code> tells JavaScript to stop executing statements. If the <code>break</code> is omitted, the next statement will be executed.
</section>

View File

@ -11,7 +11,12 @@ In JavaScript, you can store a value in a variable with the <dfn>assignment</dfn
<code>myVariable = 5;</code>
This assigns the <code>Number</code> value <code>5</code> to <code>myVariable</code>.
Assignment always goes from right to left. Everything to the right of the <code>=</code> operator is resolved before the value is assigned to the variable to the left of the operator.
<blockquote>myVar = 5;<br>myNum = myVar;</blockquote>
```js
myVar = 5;
myNum = myVar;
```
This assigns <code>5</code> to <code>myVar</code> and then resolves <code>myVar</code> to <code>5</code> again and assigns it to <code>myNum</code>.
</section>

View File

@ -11,7 +11,11 @@ We can also subtract one number from another.
JavaScript uses the <code>-</code> symbol for subtraction.
<strong>Example</strong>
<blockquote>myVar = 12 - 6; // assigned 6</blockquote>
```js
myVar = 12 - 6; // assigned 6
```
</section>

View File

@ -9,7 +9,16 @@ videoUrl: 'https://scrimba.com/c/cm8Q7Ua'
<section id='description'>
Sometimes it is useful to check if the property of a given object exists or not. We can use the <code>.hasOwnProperty(propname)</code> method of objects to determine if that object has the given property name. <code>.hasOwnProperty()</code> returns <code>true</code> or <code>false</code> if the property is found or not.
<strong>Example</strong>
<blockquote>var myObj = {<br>&nbsp;&nbsp;top: "hat",<br>&nbsp;&nbsp;bottom: "pants"<br>};<br>myObj.hasOwnProperty("top"); // true<br>myObj.hasOwnProperty("middle"); // false</blockquote>
```js
var myObj = {
top: "hat",
bottom: "pants"
};
myObj.hasOwnProperty("top"); // true
myObj.hasOwnProperty("middle"); // false
```
</section>
## Instructions

View File

@ -9,9 +9,19 @@ videoUrl: 'https://scrimba.com/c/cWPVaUR'
<section id='description'>
In JavaScript, <code>String</code> values are <dfn>immutable</dfn>, which means that they cannot be altered once created.
For example, the following code:
<blockquote>var myStr = "Bob";<br>myStr[0] = "J";</blockquote>
```js
var myStr = "Bob";
myStr[0] = "J";
```
cannot change the value of <code>myStr</code> to "Job", because the contents of <code>myStr</code> cannot be altered. Note that this does <em>not</em> mean that <code>myStr</code> cannot be changed, just that the individual characters of a <dfn>string literal</dfn> cannot be changed. The only way to change <code>myStr</code> would be to assign it with a new string, like this:
<blockquote>var myStr = "Bob";<br>myStr = "Job";</blockquote>
```js
var myStr = "Bob";
myStr = "Job";
```
</section>
## Instructions

View File

@ -12,7 +12,13 @@ In JavaScript all variables and function names are case sensitive. This means th
<h4>Best Practice</h4>
Write variable names in JavaScript in <dfn>camelCase</dfn>. In <dfn>camelCase</dfn>, multi-word variable names have the first word in lowercase and the first letter of each subsequent word is capitalized.
<strong>Examples:</strong>
<blockquote>var someVariable;<br>var anotherVariableName;<br>var thisVariableNameIsSoLong;</blockquote>
```js
var someVariable;
var anotherVariableName;
var thisVariableNameIsSoLong;
```
</section>
## Instructions

View File

@ -9,7 +9,15 @@ videoUrl: 'https://scrimba.com/c/ce2p7cL'
<section id='description'>
A function can include the <code>return</code> statement but it does not have to. In the case that the function doesn't have a <code>return</code> statement, when you call it, the function processes the inner code but the returned value is <code>undefined</code>.
<strong>Example</strong>
<blockquote>var sum = 0;<br>function addSum(num) {<br>&nbsp;&nbsp;sum = sum + num;<br>}<br>var returnedValue = addSum(3); // sum will be modified but returned value is undefined</blockquote>
```js
var sum = 0;
function addSum(num) {
sum = sum + num;
}
var returnedValue = addSum(3); // sum will be modified but returned value is undefined
```
<code>addSum</code> is a function without a <code>return</code> statement. The function will change the global <code>sum</code> variable but the returned value of the function is <code>undefined</code>.
</section>

View File

@ -9,7 +9,16 @@ videoUrl: 'https://scrimba.com/c/c9yEJT4'
<section id='description'>
After you've created a JavaScript object, you can update its properties at any time just like you would update any other variable. You can use either dot or bracket notation to update.
For example, let's look at <code>ourDog</code>:
<blockquote>var ourDog = {<br>&nbsp;&nbsp;"name": "Camper",<br>&nbsp;&nbsp;"legs": 4,<br>&nbsp;&nbsp;"tails": 1,<br>&nbsp;&nbsp;"friends": ["everything!"]<br>};</blockquote>
```js
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"]
};
```
Since he's a particularly happy dog, let's change his name to "Happy Camper". Here's how we update his object's name property:
<code>ourDog.name = "Happy Camper";</code> or
<code>ourDog["name"] = "Happy Camper";</code>

View File

@ -12,7 +12,18 @@ When the condition evaluates to <code>true</code>, the program executes the stat
<strong>Pseudocode</strong>
<blockquote>if (<i>condition is true</i>) {<br>&nbsp;&nbsp;<i>statement is executed</i><br>}</blockquote>
<strong>Example</strong>
<blockquote>function test (myCondition) {<br>&nbsp;&nbsp;if (myCondition) {<br>&nbsp;&nbsp;&nbsp;&nbsp; return "It was true";<br>&nbsp;&nbsp;}<br>&nbsp;&nbsp;return "It was false";<br>}<br>test(true); // returns "It was true"<br>test(false); // returns "It was false"</blockquote>
```js
function test (myCondition) {
if (myCondition) {
return "It was true";
}
return "It was false";
}
test(true); // returns "It was true"
test(false); // returns "It was false"
```
When <code>test</code> is called with a value of <code>true</code>, the <code>if</code> statement evaluates <code>myCondition</code> to see if it is <code>true</code> or not. Since it is <code>true</code>, the function returns <code>"It was true"</code>. When we call <code>test</code> with a value of <code>false</code>, <code>myCondition</code> is <em>not</em> <code>true</code> and the statement in the curly braces is not executed and the function returns <code>"It was false"</code>.
</section>

View File

@ -9,9 +9,29 @@ videoUrl: 'https://scrimba.com/c/cyWJBT4'
<section id='description'>
In the previous challenge, you used a single <code>conditional operator</code>. You can also chain them together to check for multiple conditions.
The following function uses if, else if, and else statements to check multiple conditions:
<blockquote>function findGreaterOrEqual(a, b) {<br>&nbsp;&nbsp;if (a === b) {<br>&nbsp;&nbsp;&nbsp;&nbsp;return "a and b are equal";<br>&nbsp;&nbsp;}<br>&nbsp;&nbsp;else if (a > b) {<br>&nbsp;&nbsp;&nbsp;&nbsp;return "a is greater";<br>&nbsp;&nbsp;}<br>&nbsp;&nbsp;else {<br>&nbsp;&nbsp;&nbsp;&nbsp;return "b is greater";<br>&nbsp;&nbsp;}<br>}</blockquote>
```js
function findGreaterOrEqual(a, b) {
if (a === b) {
return "a and b are equal";
}
else if (a > b) {
return "a is greater";
}
else {
return "b is greater";
}
}
```
The above function can be re-written using multiple <code>conditional operators</code>:
<blockquote>function findGreaterOrEqual(a, b) {<br>&nbsp;&nbsp;return (a === b) ? "a and b are equal" : (a > b) ? "a is greater" : "b is greater";<br>}</blockquote>
```js
function findGreaterOrEqual(a, b) {
return (a === b) ? "a and b are equal" : (a > b) ? "a is greater" : "b is greater";
}
```
</section>
## Instructions

View File

@ -11,9 +11,26 @@ The <dfn>conditional operator</dfn>, also called the <dfn>ternary operator</dfn>
The syntax is:
<code>condition ? statement-if-true : statement-if-false;</code>
The following function uses an if-else statement to check a condition:
<blockquote>function findGreater(a, b) {<br>&nbsp;&nbsp;if(a > b) {<br>&nbsp;&nbsp;&nbsp;&nbsp;return "a is greater";<br>&nbsp;&nbsp;}<br>&nbsp;&nbsp;else {<br>&nbsp;&nbsp;&nbsp;&nbsp;return "b is greater";<br>&nbsp;&nbsp;}<br>}</blockquote>
```js
function findGreater(a, b) {
if(a > b) {
return "a is greater";
}
else {
return "b is greater";
}
}
```
This can be re-written using the <code>conditional operator</code>:
<blockquote>function findGreater(a, b) {<br>&nbsp;&nbsp;return a > b ? "a is greater" : "b is greater";<br>}</blockquote>
```js
function findGreater(a, b) {
return a > b ? "a is greater" : "b is greater";
}
```
</section>
## Instructions

View File

@ -9,7 +9,25 @@ videoUrl: 'https://scrimba.com/c/cdBk8sM'
<section id='description'>
Objects can be thought of as a key/value storage, like a dictionary. If you have tabular data, you can use an object to "lookup" values rather than a <code>switch</code> statement or an <code>if/else</code> chain. This is most useful when you know that your input data is limited to a certain range.
Here is an example of a simple reverse alphabet lookup:
<blockquote>var alpha = {<br>&nbsp;&nbsp;1:"Z",<br>&nbsp;&nbsp;2:"Y",<br>&nbsp;&nbsp;3:"X",<br>&nbsp;&nbsp;4:"W",<br>&nbsp;&nbsp;...<br>&nbsp;&nbsp;24:"C",<br>&nbsp;&nbsp;25:"B",<br>&nbsp;&nbsp;26:"A"<br>};<br>alpha[2]; // "Y"<br>alpha[24]; // "C"<br><br>var value = 2;<br>alpha[value]; // "Y"</blockquote>
```js
var alpha = {
1:"Z",
2:"Y",
3:"X",
4:"W",
...
24:"C",
25:"B",
26:"A"
};
alpha[2]; // "Y"
alpha[24]; // "C"
var value = 2;
alpha[value]; // "Y"
```
</section>
## Instructions

View File

@ -10,7 +10,11 @@ videoUrl: 'https://scrimba.com/c/cP3vVsm'
We will now use our knowledge of strings to build a "<a href='https://en.wikipedia.org/wiki/Mad_Libs' target='_blank'>Mad Libs</a>" style word game we're calling "Word Blanks". You will create an (optionally humorous) "Fill in the Blanks" style sentence.
In a "Mad Libs" game, you are provided sentences with some missing words, like nouns, verbs, adjectives and adverbs. You then fill in the missing pieces with words of your choice in a way that the completed sentence makes sense.
Consider this sentence - "It was really <strong>____</strong>, and we <strong>____</strong> ourselves <strong>____</strong>". This sentence has three missing pieces- an adjective, a verb and an adverb, and we can add words of our choice to complete it. We can then assign the completed sentence to a variable as follows:
<blockquote>var sentence = "It was really " + "hot" + ", and we " + "laughed" + " ourselves " + "silly" + ".";</blockquote>
```js
var sentence = "It was really " + "hot" + ", and we " + "laughed" + " ourselves " + "silly" + ".";
```
</section>
## Instructions

View File

@ -9,7 +9,13 @@ videoUrl: 'https://scrimba.com/c/cL6dqfy'
<section id='description'>
In JavaScript, we can divide up our code into reusable parts called <dfn>functions</dfn>.
Here's an example of a function:
<blockquote>function functionName() {<br>&nbsp;&nbsp;console.log("Hello World");<br>}</blockquote>
```js
function functionName() {
console.log("Hello World");
}
```
You can call or <dfn>invoke</dfn> this function by using its name followed by parentheses, like this:
<code>functionName();</code>
Each time the function is called it will print out the message <code>"Hello World"</code> on the dev console. All of the code between the curly braces will be executed every time the function is called.

View File

@ -8,7 +8,15 @@ challengeType: 1
<section id='description'>
When a function or method doesn't take any arguments, you may forget to include the (empty) opening and closing parentheses when calling it. Often times the result of a function call is saved in a variable for other use in your code. This error can be detected by logging variable values (or their types) to the console and seeing that one is set to a function reference, instead of the expected value the function returns.
The variables in the following example are different:
<blockquote>function myFunction() {<br>&nbsp;&nbsp;return "You rock!";<br>}<br>let varOne = myFunction; // set to equal a function<br>let varTwo = myFunction(); // set to equal the string "You rock!"</blockquote>
```js
function myFunction() {
return "You rock!";
}
let varOne = myFunction; // set to equal a function
let varTwo = myFunction(); // set to equal the string "You rock!"
```
</section>
## Instructions

View File

@ -9,9 +9,22 @@ challengeType: 1
JavaScript allows the use of both single (<code>'</code>) and double (<code>"</code>) quotes to declare a string. Deciding which one to use generally comes down to personal preference, with some exceptions.
Having two choices is great when a string has contractions or another piece of text that's in quotes. Just be careful that you don't close the string too early, which causes a syntax error.
Here are some examples of mixing quotes:
<blockquote>// These are correct:<br>const grouchoContraction = "I've had a perfectly wonderful evening, but this wasn't it.";<br>const quoteInString = "Groucho Marx once said 'Quote me as saying I was mis-quoted.'";<br>// This is incorrect:<br>const uhOhGroucho = 'I've had a perfectly wonderful evening, but this wasn't it.';</blockquote>
```js
// These are correct:
const grouchoContraction = "I've had a perfectly wonderful evening, but this wasn't it.";
const quoteInString = "Groucho Marx once said 'Quote me as saying I was mis-quoted.'";
// This is incorrect:
const uhOhGroucho = 'I've had a perfectly wonderful evening, but this wasn't it.';
```
Of course, it is okay to use only one style of quotes. You can escape the quotes inside the string by using the backslash (\) escape character:
<blockquote>// Correct use of same quotes:<br>const allSameQuotes = 'I\'ve had a perfectly wonderful evening, but this wasn\'t it.';</blockquote>
```js
// Correct use of same quotes:
const allSameQuotes = 'I\'ve had a perfectly wonderful evening, but this wasn\'t it.';
```
</section>
## Instructions

View File

@ -8,7 +8,24 @@ challengeType: 1
<section id='description'>
<code>Off by one errors</code> (sometimes called OBOE) crop up when you're trying to target a specific index of a string or array (to slice or access a segment), or when looping over the indices of them. JavaScript indexing starts at zero, not one, which means the last index is always one less than the length of the item. If you try to access an index equal to the length, the program may throw an "index out of range" reference error or print <code>undefined</code>.
When you use string or array methods that take index ranges as arguments, it helps to read the documentation and understand if they are inclusive (the item at the given index is part of what's returned) or not. Here are some examples of off by one errors:
<blockquote>let alphabet = "abcdefghijklmnopqrstuvwxyz";<br>let len = alphabet.length;<br>for (let i = 0; i <= len; i++) {<br>&nbsp;&nbsp;// loops one too many times at the end<br>&nbsp;&nbsp;console.log(alphabet[i]);<br>}<br>for (let j = 1; j < len; j++) {<br>&nbsp;&nbsp;// loops one too few times and misses the first character at index 0<br>&nbsp;&nbsp;console.log(alphabet[j]);<br>}<br>for (let k = 0; k < len; k++) {<br>&nbsp;&nbsp;// Goldilocks approves - this is just right<br>&nbsp;&nbsp;console.log(alphabet[k]);<br>}</blockquote>
```js
let alphabet = "abcdefghijklmnopqrstuvwxyz";
let len = alphabet.length;
for (let i = 0; i <= len; i++) {
// loops one too many times at the end
console.log(alphabet[i]);
}
for (let j = 1; j < len; j++) {
// loops one too few times and misses the first character at index 0
console.log(alphabet[j]);
}
for (let k = 0; k < len; k++) {
// Goldilocks approves - this is just right
console.log(alphabet[k]);
}
```
</section>
## Instructions

View File

@ -10,7 +10,17 @@ Branching programs, i.e. ones that do different things if certain conditions are
This logic is spoken (in English, at least) as "if x equals y, then ..." which can literally translate into code using the <code>=</code>, or assignment operator. This leads to unexpected control flow in your program.
As covered in previous challenges, the assignment operator (<code>=</code>) in JavaScript assigns a value to a variable name. And the <code>==</code> and <code>===</code> operators check for equality (the triple <code>===</code> tests for strict equality, meaning both value and type are the same).
The code below assigns <code>x</code> to be 2, which evaluates as <code>true</code>. Almost every value on its own in JavaScript evaluates to <code>true</code>, except what are known as the "falsy" values: <code>false</code>, <code>0</code>, <code>""</code> (an empty string), <code>NaN</code>, <code>undefined</code>, and <code>null</code>.
<blockquote>let x = 1;<br>let y = 2;<br>if (x = y) {<br>&nbsp;&nbsp;// this code block will run for any value of y (unless y were originally set as a falsy)<br>} else {<br>&nbsp;&nbsp;// this code block is what should run (but won't) in this example<br>}</blockquote>
```js
let x = 1;
let y = 2;
if (x = y) {
// this code block will run for any value of y (unless y were originally set as a falsy)
} else {
// this code block is what should run (but won't) in this example
}
```
</section>
## Instructions

View File

@ -8,7 +8,15 @@ challengeType: 1
<section id='description'>
The final topic is the dreaded infinite loop. Loops are great tools when you need your program to run a code block a certain number of times or until a condition is met, but they need a terminal condition that ends the looping. Infinite loops are likely to freeze or crash the browser, and cause general program execution mayhem, which no one wants.
There was an example of an infinite loop in the introduction to this section - it had no terminal condition to break out of the <code>while</code> loop inside <code>loopy()</code>. Do NOT call this function!
<blockquote>function loopy() {<br>&nbsp;&nbsp;while(true) {<br>&nbsp;&nbsp;&nbsp;&nbsp;console.log("Hello, world!");<br>&nbsp;&nbsp;}<br>}</blockquote>
```js
function loopy() {
while(true) {
console.log("Hello, world!");
}
}
```
It's the programmer's job to ensure that the terminal condition, which tells the program when to break out of the loop code, is eventually reached. One error is incrementing or decrementing a counter variable in the wrong direction from the terminal condition. Another one is accidentally resetting a counter or index variable within the loop code, instead of incrementing or decrementing it.
</section>

View File

@ -8,7 +8,14 @@ challengeType: 1
<section id='description'>
You can use <code>typeof</code> to check the data structure, or type, of a variable. This is useful in debugging when working with multiple data types. If you think you're adding two numbers, but one is actually a string, the results can be unexpected. Type errors can lurk in calculations or function calls. Be careful especially when you're accessing and working with external data in the form of a JavaScript Object Notation (JSON) object.
Here are some examples using <code>typeof</code>:
<blockquote>console.log(typeof ""); // outputs "string"<br>console.log(typeof 0); // outputs "number"<br>console.log(typeof []); // outputs "object"<br>console.log(typeof {}); // outputs "object"</blockquote>
```js
console.log(typeof ""); // outputs "string"
console.log(typeof 0); // outputs "number"
console.log(typeof []); // outputs "object"
console.log(typeof {}); // outputs "object"
```
JavaScript recognizes six primitive (immutable) data types: <code>Boolean</code>, <code>Null</code>, <code>Undefined</code>, <code>Number</code>, <code>String</code>, and <code>Symbol</code> (new with ES6) and one type for mutable items: <code>Object</code>. Note that in JavaScript, arrays are technically a type of object.
</section>

View File

@ -9,13 +9,65 @@ challengeType: 1
When you declare a variable with the <code>var</code> keyword, it is declared globally, or locally if declared inside a function.
The <code>let</code> keyword behaves similarly, but with some extra features. When you declare a variable with the <code>let</code> keyword inside a block, statement, or expression, its scope is limited to that block, statement, or expression.
For example:
<blockquote>var numArray = [];<br>for (var i = 0; i < 3; i++) {<br>&nbsp;&nbsp;numArray.push(i);<br>}<br>console.log(numArray);<br>// returns [0, 1, 2]<br>console.log(i);<br>// returns 3</blockquote>
```js
var numArray = [];
for (var i = 0; i < 3; i++) {
numArray.push(i);
}
console.log(numArray);
// returns [0, 1, 2]
console.log(i);
// returns 3
```
With the <code>var</code> keyword, <code>i</code> is declared globally. So when <code>i++</code> is executed, it updates the global variable. This code is similar to the following:
<blockquote>var numArray = [];<br>var i;<br>for (i = 0; i < 3; i++) {<br>&nbsp;&nbsp;numArray.push(i);<br>}<br>console.log(numArray);<br>// returns [0, 1, 2]<br>console.log(i);<br>// returns 3</blockquote>
```js
var numArray = [];
var i;
for (i = 0; i < 3; i++) {
numArray.push(i);
}
console.log(numArray);
// returns [0, 1, 2]
console.log(i);
// returns 3
```
This behavior will cause problems if you were to create a function and store it for later use inside a for loop that uses the <code>i</code> variable. This is because the stored function will always refer to the value of the updated global <code>i</code> variable.
<blockquote>var printNumTwo;<br>for (var i = 0; i < 3; i++) {<br>&nbsp;&nbsp;if (i === 2) {<br>&nbsp;&nbsp;&nbsp;&nbsp;printNumTwo = function() {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return i;<br>&nbsp;&nbsp;&nbsp;&nbsp;};<br>&nbsp;&nbsp;}<br>}<br>console.log(printNumTwo());<br>// returns 3</blockquote>
```js
var printNumTwo;
for (var i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
// returns 3
```
As you can see, <code>printNumTwo()</code> prints 3 and not 2. This is because the value assigned to <code>i</code> was updated and the <code>printNumTwo()</code> returns the global <code>i</code> and not the value <code>i</code> had when the function was created in the for loop. The <code>let</code> keyword does not follow this behavior:
<blockquote>'use strict';<br>let printNumTwo;<br>for (let i = 0; i < 3; i++) {<br>&nbsp;&nbsp;if (i === 2) {<br>&nbsp;&nbsp;&nbsp;&nbsp;printNumTwo = function() {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return i;<br>&nbsp;&nbsp;&nbsp;&nbsp;};<br>&nbsp;&nbsp;}<br>}<br>console.log(printNumTwo());<br>// returns 2<br>console.log(i);<br>// returns "i is not defined"</blockquote>
```js
'use strict';
let printNumTwo;
for (let i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
// returns 2
console.log(i);
// returns "i is not defined"
```
<code>i</code> is not defined because it was not declared in the global scope. It is only declared within the for loop statement. <code>printNumTwo()</code> returned the correct value because three different <code>i</code> variables with unique values (0, 1, and 2) were created by the <code>let</code> keyword within the loop statement.
</section>

View File

@ -9,7 +9,13 @@ challengeType: 1
In the <code>export</code> lesson, you learned about the syntax referred to as a <dfn>named export</dfn>. This allowed you to make multiple functions and variables available for use in other files.
There is another <code>export</code> syntax you need to know, known as <dfn>export default</dfn>. Usually you will use this syntax if only one value is being exported from a file. It is also used to create a fallback value for a file or module.
Here is a quick example of <code>export default</code>:
<blockquote>export default function add(x,y) {<br>&nbsp;&nbsp;return x + y;<br>}</blockquote>
```js
export default function add(x,y) {
return x + y;
}
```
Note: Since <code>export default</code> is used to declare a fallback value for a module or file, you can only have one value be a default export in each module or file. Additionally, you cannot use <code>export default</code> with <code>var</code>, <code>let</code>, or <code>const</code>
</section>

View File

@ -9,7 +9,23 @@ challengeType: 1
A new feature of ES6 is the <dfn>template literal</dfn>. This is a special type of string that makes creating complex strings easier.
Template literals allow you to create multi-line strings and to use string interpolation features to create strings.
Consider the code below:
<blockquote>const person = {<br>&nbsp;&nbsp;name: "Zodiac Hasbro",<br>&nbsp;&nbsp;age: 56<br>};<br><br>// Template literal with multi-line and string interpolation<br>const greeting = `Hello, my name is ${person.name}!<br>I am ${person.age} years old.`;<br><br>console.log(greeting); // prints<br>// Hello, my name is Zodiac Hasbro!<br>// I am 56 years old.<br></blockquote>
```js
const person = {
name: "Zodiac Hasbro",
age: 56
};
// Template literal with multi-line and string interpolation
const greeting = `Hello, my name is ${person.name}!
I am ${person.age} years old.`;
console.log(greeting); // prints
// Hello, my name is Zodiac Hasbro!
// I am 56 years old.
```
A lot of things happened there.
Firstly, the example uses backticks (<code>`</code>), not quotes (<code>'</code> or <code>"</code>), to wrap the string.
Secondly, notice that the string is multi-line, both in the code and the output. This saves inserting <code>\n</code> within strings.

View File

@ -8,7 +8,13 @@ challengeType: 1
<section id='description'>
The keyword <code>let</code> is not the only new way to declare variables. In ES6, you can also declare variables using the <code>const</code> keyword.
<code>const</code> has all the awesome features that <code>let</code> has, with the added bonus that variables declared using <code>const</code> are read-only. They are a constant value, which means that once a variable is assigned with <code>const</code>, it cannot be reassigned.
<blockquote>"use strict";<br>const FAV_PET = "Cats";<br>FAV_PET = "Dogs"; // returns error</blockquote>
```js
"use strict";
const FAV_PET = "Cats";
FAV_PET = "Dogs"; // returns error
```
As you can see, trying to reassign a variable declared with <code>const</code> will throw an error. You should always name variables you don't want to reassign using the <code>const</code> keyword. This helps when you accidentally attempt to reassign a variable that is meant to stay constant. A common practice when naming constants is to use all uppercase letters, with words separated by an underscore.
<strong>Note:</strong> It is common for developers to use uppercase variable identifiers for immutable values and lowercase or camelCase for mutable values (objects and arrays). In a later challenge you will see an example of a lowercase variable identifier being used for an array.

View File

@ -7,17 +7,34 @@ challengeType: 1
## Description
<section id='description'>
One of the biggest problems with declaring variables with the <code>var</code> keyword is that you can overwrite variable declarations without an error.
<blockquote>var camper = 'James';<br>var camper = 'David';<br>console.log(camper);<br>// logs 'David'</blockquote>
```js
var camper = 'James';
var camper = 'David';
console.log(camper);
// logs 'David'
```
As you can see in the code above, the <code>camper</code> variable is originally declared as <code>James</code> and then overridden to be <code>David</code>.
In a small application, you might not run into this type of problem, but when your code becomes larger, you might accidentally overwrite a variable that you did not intend to overwrite.
Because this behavior does not throw an error, searching and fixing bugs becomes more difficult.<br>
A new keyword called <code>let</code> was introduced in ES6 to solve this potential issue with the <code>var</code> keyword.
If you were to replace <code>var</code> with <code>let</code> in the variable declarations of the code above, the result would be an error.
<blockquote>let camper = 'James';<br>let camper = 'David'; // throws an error</blockquote>
```js
let camper = 'James';
let camper = 'David'; // throws an error
```
This error can be seen in the console of your browser.
So unlike <code>var</code>, when using <code>let</code>, a variable with the same name can only be declared once.
Note the <code>"use strict"</code>. This enables Strict Mode, which catches common coding mistakes and "unsafe" actions. For instance:
<blockquote>"use strict";<br>x = 3.14; // throws an error because x is not declared</blockquote>
```js
"use strict";
x = 3.14; // throws an error because x is not declared
```
</section>
## Instructions

View File

@ -8,7 +8,12 @@ challengeType: 1
<section id='description'>
In the last challenge, you learned about <code>export default</code> and its uses. It is important to note that, to import a default export, you need to use a different <code>import</code> syntax.
In the following example, we have a function, <code>add</code>, that is the default export of a file, <code>"math_functions"</code>. Here is how to import it:
<blockquote>import add from "math_functions";<br>add(5,4); // Will return 9</blockquote>
```js
import add from "math_functions";
add(5,4); // Will return 9
```
The syntax differs in one key place - the imported value, <code>add</code>, is not surrounded by curly braces, <code>{}</code>. Unlike exported values, the primary method of importing a default export is to simply write the value's name after <code>import</code>.
</section>

View File

@ -9,7 +9,15 @@ challengeType: 1
The <code>const</code> declaration has many use cases in modern JavaScript.
Some developers prefer to assign all their variables using <code>const</code> by default, unless they know they will need to reassign the value. Only in that case, they use <code>let</code>.
However, it is important to understand that objects (including arrays and functions) assigned to a variable using <code>const</code> are still mutable. Using the <code>const</code> declaration only prevents reassignment of the variable identifier.
<blockquote>"use strict";<br>const s = [5, 6, 7];<br>s = [1, 2, 3]; // throws error, trying to assign a const<br>s[2] = 45; // works just as it would with an array declared with var or let<br>console.log(s); // returns [5, 6, 45]</blockquote>
```js
"use strict";
const s = [5, 6, 7];
s = [1, 2, 3]; // throws error, trying to assign a const
s[2] = 45; // works just as it would with an array declared with var or let
console.log(s); // returns [5, 6, 45]
```
As you can see, you can mutate the object <code>[5, 6, 7]</code> itself and the variable <code>s</code> will still point to the altered array <code>[5, 6, 45]</code>. Like all arrays, the array elements in <code>s</code> are mutable, but because <code>const</code> was used, you cannot use the variable identifier <code>s</code> to point to a different array using the assignment operator.
</section>

View File

@ -8,7 +8,19 @@ challengeType: 1
<section id='description'>
As seen in the previous challenge, <code>const</code> declaration alone doesn't really protect your data from mutation. To ensure your data doesn't change, JavaScript provides a function <code>Object.freeze</code> to prevent data mutation.
Once the object is frozen, you can no longer add, update, or delete properties from it. Any attempt at changing the object will be rejected without an error.
<blockquote>let obj = {<br>&nbsp;&nbsp;name:"FreeCodeCamp",<br>&nbsp;&nbsp;review:"Awesome"<br>};<br>Object.freeze(obj);<br>obj.review = "bad"; // will be ignored. Mutation not allowed<br>obj.newProp = "Test"; // will be ignored. Mutation not allowed<br>console.log(obj); <br>// { name: "FreeCodeCamp", review:"Awesome"}</blockquote>
```js
let obj = {
name:"FreeCodeCamp",
review:"Awesome"
};
Object.freeze(obj);
obj.review = "bad"; // will be ignored. Mutation not allowed
obj.newProp = "Test"; // will be ignored. Mutation not allowed
console.log(obj);
// { name: "FreeCodeCamp", review:"Awesome"}
```
</section>
## Instructions

View File

@ -8,7 +8,15 @@ challengeType: 1
<section id='description'>
In order to help us create more flexible functions, ES6 introduces <dfn>default parameters</dfn> for functions.
Check out this code:
<blockquote>function greeting(name = "Anonymous") {<br>&nbsp;&nbsp;return "Hello " + name;<br>}<br>console.log(greeting("John")); // Hello John<br>console.log(greeting()); // Hello Anonymous</blockquote>
```js
function greeting(name = "Anonymous") {
return "Hello " + name;
}
console.log(greeting("John")); // Hello John
console.log(greeting()); // Hello Anonymous
```
The default parameter kicks in when the argument is not specified (it is undefined). As you can see in the example above, the parameter <code>name</code> will receive its default value <code>"Anonymous"</code> when you do not provide a value for the parameter. You can add default values for as many parameters as you want.
</section>

View File

@ -9,9 +9,18 @@ challengeType: 1
In the past, the function <code>require()</code> would be used to import the functions and code in external files and modules. While handy, this presents a problem: some files and modules are rather large, and you may only need certain code from those external resources.
ES6 gives us a very handy tool known as <dfn>import</dfn>. With it, we can choose which parts of a module or file to load into a given file, saving time and memory.
Consider the following example. Imagine that <code>math_array_functions</code> has about 20 functions, but I only need one, <code>countItems</code>, in my current file. The old <code>require()</code> approach would force me to bring in all 20 functions. With this new <code>import</code> syntax, I can bring in just the desired function, like so:
<blockquote>import { countItems } from "math_array_functions"</blockquote>
```js
import { countItems } from "math_array_functions"
```
A description of the above code:
<blockquote>import { function } from "file_path_goes_here"<br>// We can also import variables the same way!</blockquote>
```js
import { function } from "file_path_goes_here"
// We can also import variables the same way!
```
There are a few ways to write an <code>import</code> statement, but the above is a very common use-case.
<strong>Note</strong><br>The whitespace surrounding the function inside the curly braces is a best practice - it makes it easier to read the <code>import</code> statement.
<strong>Note</strong><br>The lessons in this section handle non-browser features. <code>import</code>, and the statements we introduce in the rest of these lessons, won't work on a browser directly. However, we can use various tools to create code out of this to make it work in browser.

View File

@ -8,9 +8,20 @@ challengeType: 1
<section id='description'>
Suppose you have a file and you wish to import all of its contents into the current file. This can be done with the <code>import * as</code> syntax.
Here's an example where the contents of a file named <code>"math_functions"</code> are imported into a file in the same directory:
<blockquote>import * as myMathModule from "math_functions";<br>myMathModule.add(2,3);<br>myMathModule.subtract(5,3);</blockquote>
```js
import * as myMathModule from "math_functions";
myMathModule.add(2,3);
myMathModule.subtract(5,3);
```
And breaking down that code:
<blockquote>import * as object_with_name_of_your_choice from "file_path_goes_here"<br>object_with_name_of_your_choice.imported_function</blockquote>
```js
import * as object_with_name_of_your_choice from "file_path_goes_here"
object_with_name_of_your_choice.imported_function
```
You may use any name following the <code>import * as </code>portion of the statement. In order to utilize this method, it requires an object that receives the imported values (i.e., you must provide a name). From here, you will use the dot notation to call your imported values.
</section>

View File

@ -8,11 +8,29 @@ challengeType: 1
<section id='description'>
In JavaScript, we often don't need to name our functions, especially when passing a function as an argument to another function. Instead, we create inline functions. We don't need to name these functions because we do not reuse them anywhere else.
To achieve this, we often use the following syntax:
<blockquote>const myFunc = function() {<br>&nbsp;&nbsp;const myVar = "value";<br>&nbsp;&nbsp;return myVar;<br>}</blockquote>
```js
const myFunc = function() {
const myVar = "value";
return myVar;
}
```
ES6 provides us with the syntactic sugar to not have to write anonymous functions this way. Instead, you can use <strong>arrow function syntax</strong>:
<blockquote>const myFunc = () => {<br>&nbsp;&nbsp;const myVar = "value";<br>&nbsp;&nbsp;return myVar;<br>}</blockquote>
```js
const myFunc = () => {
const myVar = "value";
return myVar;
}
```
When there is no function body, and only a return value, arrow function syntax allows you to omit the keyword <code>return</code> as well as the brackets surrounding the code. This helps simplify smaller functions into one-line statements:
<blockquote>const myFunc = () => "value"</blockquote>
```js
const myFunc = () => "value"
```
This code will still return <code>value</code> by default.
</section>

View File

@ -9,9 +9,25 @@ challengeType: 1
ES6 provides a new syntax to help create objects, using the keyword <dfn>class</dfn>.
This is to be noted, that the <code>class</code> syntax is just a syntax, and not a full-fledged class based implementation of object oriented paradigm, unlike in languages like Java, or Python, or Ruby etc.
In ES5, we usually define a constructor function, and use the <code>new</code> keyword to instantiate an object.
<blockquote>var SpaceShuttle = function(targetPlanet){<br>&nbsp;&nbsp;this.targetPlanet = targetPlanet;<br>}<br>var zeus = new SpaceShuttle('Jupiter');</blockquote>
```js
var SpaceShuttle = function(targetPlanet){
this.targetPlanet = targetPlanet;
}
var zeus = new SpaceShuttle('Jupiter');
```
The class syntax simply replaces the constructor function creation:
<blockquote>class SpaceShuttle {<br>&nbsp;&nbsp;constructor(targetPlanet) {<br>&nbsp;&nbsp;&nbsp;&nbsp;this.targetPlanet = targetPlanet;<br>&nbsp;&nbsp;}<br>}<br>const zeus = new SpaceShuttle('Jupiter');</blockquote>
```js
class SpaceShuttle {
constructor(targetPlanet) {
this.targetPlanet = targetPlanet;
}
}
const zeus = new SpaceShuttle('Jupiter');
```
Notice that the <code>class</code> keyword declares a new function, and a constructor was added, which would be invoked when <code>new</code> is called - to create a new object.<br>
<strong>Notes:</strong><br><ul>
<li> UpperCamelCase should be used by convention for ES6 class names, as in <code>SpaceShuttle</code> used above.</li>

View File

@ -9,10 +9,20 @@ challengeType: 1
ES6 makes destructuring arrays as easy as destructuring objects.
One key difference between the spread operator and array destructuring is that the spread operator unpacks all contents of an array into a comma-separated list. Consequently, you cannot pick or choose which elements you want to assign to variables.
Destructuring an array lets us do exactly that:
<blockquote>const [a, b] = [1, 2, 3, 4, 5, 6];<br>console.log(a, b); // 1, 2</blockquote>
```js
const [a, b] = [1, 2, 3, 4, 5, 6];
console.log(a, b); // 1, 2
```
The variable <code>a</code> is assigned the first value of the array, and <code>b</code> is assigned the second value of the array.
We can also access the value at any index in an array with destructuring by using commas to reach the desired index:
<blockquote>const [a, b,,, c] = [1, 2, 3, 4, 5, 6];<br>console.log(a, b, c); // 1, 2, 5 </blockquote>
```js
const [a, b,,, c] = [1, 2, 3, 4, 5, 6];
console.log(a, b, c); // 1, 2, 5
```
</section>
## Instructions

View File

@ -8,7 +8,16 @@ challengeType: 1
<section id='description'>
We can similarly destructure <em>nested</em> objects into variables.
Consider the following code:
<blockquote>const a = {<br>&nbsp;&nbsp;start: { x: 5, y: 6 },<br>&nbsp;&nbsp;end: { x: 6, y: -9 }<br>};<br>const { start: { x: startX, y: startY }} = a;<br>console.log(startX, startY); // 5, 6</blockquote>
```js
const a = {
start: { x: 5, y: 6 },
end: { x: 6, y: -9 }
};
const { start: { x: startX, y: startY }} = a;
console.log(startX, startY); // 5, 6
```
In the example above, the variable <code>startX</code> is assigned the value of <code>a.start.x</code>.
</section>

View File

@ -9,11 +9,26 @@ challengeType: 1
We saw earlier how spread operator can effectively spread, or unpack, the contents of the array.
We can do something similar with objects as well. <dfn>Destructuring assignment</dfn> is special syntax for neatly assigning values taken directly from an object to variables.
Consider the following ES5 code:
<blockquote>var voxel = { x: 3.6, y: 7.4, z: 6.54 };<br>var x = voxel.x; // x = 3.6<br>var y = voxel.y; // y = 7.4<br>var z = voxel.z; // z = 6.54</blockquote>
```js
var voxel = { x: 3.6, y: 7.4, z: 6.54 };
var x = voxel.x; // x = 3.6
var y = voxel.y; // y = 7.4
var z = voxel.z; // z = 6.54
```
Here's the same assignment statement with ES6 destructuring syntax:
<blockquote>const { x, y, z } = voxel; // x = 3.6, y = 7.4, z = 6.54</blockquote>
```js
const { x, y, z } = voxel; // x = 3.6, y = 7.4, z = 6.54
```
If instead you want to store the values of <code>voxel.x</code> into <code>a</code>, <code>voxel.y</code> into <code>b</code>, and <code>voxel.z</code> into <code>c</code>, you have that freedom as well.
<blockquote>const { x: a, y: b, z: c } = voxel; // a = 3.6, b = 7.4, c = 6.54</blockquote>
```js
const { x: a, y: b, z: c } = voxel; // a = 3.6, b = 7.4, c = 6.54
```
You may read it as "get the field <code>x</code> and copy the value into <code>a</code>," and so on.
</section>

View File

@ -8,9 +8,22 @@ challengeType: 1
<section id='description'>
In some cases, you can destructure the object in a function argument itself.
Consider the code below:
<blockquote>const profileUpdate = (profileData) => {<br>&nbsp;&nbsp;const { name, age, nationality, location } = profileData;<br>&nbsp;&nbsp;// do something with these variables<br>}</blockquote>
```js
const profileUpdate = (profileData) => {
const { name, age, nationality, location } = profileData;
// do something with these variables
}
```
This effectively destructures the object sent into the function. This can also be done in-place:
<blockquote>const profileUpdate = ({ name, age, nationality, location }) => {<br>&nbsp;&nbsp;/* do something with these fields */<br>}</blockquote>
```js
const profileUpdate = ({ name, age, nationality, location }) => {
/* do something with these fields */
}
```
This removes some extra lines and makes our code look neat.
This has the added benefit of not having to manipulate an entire object in a function; only the fields that are needed are copied inside the function.
</section>

View File

@ -8,7 +8,13 @@ challengeType: 1
<section id='description'>
In some situations involving array destructuring, we might want to collect the rest of the elements into a separate array.
The result is similar to <code>Array.prototype.slice()</code>, as shown below:
<blockquote>const [a, b, ...arr] = [1, 2, 3, 4, 5, 7];<br>console.log(a, b); // 1, 2<br>console.log(arr); // [3, 4, 5, 7]</blockquote>
```js
const [a, b, ...arr] = [1, 2, 3, 4, 5, 7];
console.log(a, b); // 1, 2
console.log(arr); // [3, 4, 5, 7]
```
Variables <code>a</code> and <code>b</code> take the first and second values from the array. After that, because of rest parameter's presence, <code>arr</code> gets rest of the values in the form of an array.
The rest element only works correctly as the last variable in the list. As in, you cannot use the rest parameter to catch a subarray that leaves out last element of the original array.
</section>

View File

@ -8,9 +8,25 @@ challengeType: 1
<section id='description'>
In the previous challenge, you learned about <code>import</code> and how it can be leveraged to import small amounts of code from large files. In order for this to work, though, we must utilize one of the statements that goes with <code>import</code>, known as <dfn>export</dfn>. When we want some code - a function, or a variable - to be usable in another file, we must export it in order to import it into another file. Like <code>import</code>, <code>export</code> is a non-browser feature.
The following is what we refer to as a <dfn>named export</dfn>. With this, we can import any code we export into another file with the <code>import</code> syntax you learned in the last lesson. Here's an example:
<blockquote>const capitalizeString = (string) => {<br>&nbsp;&nbsp;return string.charAt(0).toUpperCase() + string.slice(1);<br>}<br>export { capitalizeString } // How to export functions.<br>export const foo = "bar"; // How to export variables.</blockquote>
```js
const capitalizeString = (string) => {
return string.charAt(0).toUpperCase() + string.slice(1);
}
export { capitalizeString } // How to export functions.
export const foo = "bar"; // How to export variables.
```
Alternatively, if you would like to compact all your <code>export</code> statements into one line, you can take this approach:
<blockquote>const capitalizeString = (string) => {<br>&nbsp;&nbsp;return string.charAt(0).toUpperCase() + string.slice(1);<br>}<br>const foo = "bar";<br>export { capitalizeString, foo }</blockquote>
```js
const capitalizeString = (string) => {
return string.charAt(0).toUpperCase() + string.slice(1);
}
const foo = "bar";
export { capitalizeString, foo }
```
Either approach is perfectly acceptable.
</section>

View File

@ -10,7 +10,27 @@ You can obtain values from an object, and set a value of a property within an ob
These are classically called <dfn>getters</dfn> and <dfn>setters</dfn>.
Getter functions are meant to simply return (get) the value of an object's private variable to the user without the user directly accessing the private variable.
Setter functions are meant to modify (set) the value of an object's private variable based on the value passed into the setter function. This change could involve calculations, or even overwriting the previous value completely.<br><br>
<blockquote>class Book {<br>&nbsp;&nbsp;constructor(author) {<br>&nbsp;&nbsp;&nbsp;&nbsp;this._author = author;<br>&nbsp;&nbsp;}<br>&nbsp;&nbsp;// getter<br>&nbsp;&nbsp;get writer() {<br>&nbsp;&nbsp;&nbsp;&nbsp;return this._author;<br>&nbsp;&nbsp;}<br>&nbsp;&nbsp;// setter<br>&nbsp;&nbsp;set writer(updatedAuthor) {<br>&nbsp;&nbsp;&nbsp;&nbsp;this._author = updatedAuthor;<br>&nbsp;&nbsp;}<br>}<br>const lol = new Book('anonymous');<br>console.log(lol.writer);&nbsp;&nbsp;// anonymous<br>lol.writer = 'wut';<br>console.log(lol.writer);&nbsp;&nbsp;// wut</blockquote>
```js
class Book {
constructor(author) {
this._author = author;
}
// getter
get writer() {
return this._author;
}
// setter
set writer(updatedAuthor) {
this._author = updatedAuthor;
}
}
const lol = new Book('anonymous');
console.log(lol.writer); // anonymous
lol.writer = 'wut';
console.log(lol.writer); // wut
```
Notice the syntax we are using to invoke the getter and setter - as if they are not even functions.
Getters and setters are important, because they hide internal implementation details.
<strong>Note:</strong> It is a convention to precede the name of a private variable with an underscore (<code>_</code>). The practice itself does not make a variable private.

View File

@ -8,7 +8,15 @@ challengeType: 1
<section id='description'>
In order to help us create more flexible functions, ES6 introduces the <dfn>rest parameter</dfn> for function parameters. With the rest parameter, you can create functions that take a variable number of arguments. These arguments are stored in an array that can be accessed later from inside the function.
Check out this code:
<blockquote>function howMany(...args) {<br>&nbsp;&nbsp;return "You have passed " + args.length + " arguments.";<br>}<br>console.log(howMany(0, 1, 2)); // You have passed 3 arguments<br>console.log(howMany("string", null, [1, 2, 3], { })); // You have passed 4 arguments.</blockquote>
```js
function howMany(...args) {
return "You have passed " + args.length + " arguments.";
}
console.log(howMany(0, 1, 2)); // You have passed 3 arguments.
console.log(howMany("string", null, [1, 2, 3], { })); // You have passed 4 arguments.
```
The rest parameter eliminates the need to check the <code>args</code> array and allows us to apply <code>map()</code>, <code>filter()</code> and <code>reduce()</code> on the parameters array.
</section>

View File

@ -8,13 +8,27 @@ challengeType: 1
<section id='description'>
ES6 introduces the <dfn>spread operator</dfn>, which allows us to expand arrays and other expressions in places where multiple parameters or elements are expected.
The ES5 code below uses <code>apply()</code> to compute the maximum value in an array:
<blockquote>var arr = [6, 89, 3, 45];<br>var maximus = Math.max.apply(null, arr); // returns 89</blockquote>
```js
var arr = [6, 89, 3, 45];
var maximus = Math.max.apply(null, arr); // returns 89
```
We had to use <code>Math.max.apply(null, arr)</code> because <code>Math.max(arr)</code> returns <code>NaN</code>. <code>Math.max()</code> expects comma-separated arguments, but not an array.
The spread operator makes this syntax much better to read and maintain.
<blockquote>const arr = [6, 89, 3, 45];<br>const maximus = Math.max(...arr); // returns 89</blockquote>
```js
const arr = [6, 89, 3, 45];
const maximus = Math.max(...arr); // returns 89
```
<code>...arr</code> returns an unpacked array. In other words, it <em>spreads</em> the array.
However, the spread operator only works in-place, like in an argument to a function or in an array literal. The following code will not work:
<blockquote>const spreaded = ...arr; // will throw a syntax error</blockquote>
```js
const spreaded = ...arr; // will throw a syntax error
```
</section>
## Instructions

View File

@ -7,11 +7,26 @@ challengeType: 1
## Description
<section id='description'>
Just like a regular function, you can pass arguments into an arrow function.
<blockquote>// doubles input value and returns it<br>const doubler = (item) => item * 2;</blockquote>
```js
// doubles input value and returns it
const doubler = (item) => item * 2;
```
If an arrow function has a single argument, the parentheses enclosing the argument may be omitted.
<blockquote>// the same function, without the argument parentheses<br>const doubler = item => item * 2;</blockquote>
```js
// the same function, without the argument parentheses
const doubler = item => item * 2;
```
It is possible to pass more than one argument into an arrow function.
<blockquote>// multiplies the first input value by the second and returns it<br>const multiplier = (item, multi) => item * multi;</blockquote>
```js
// multiplies the first input value by the second and returns it
const multiplier = (item, multi) => item * multi;
```
</section>
## Instructions

View File

@ -7,9 +7,27 @@ challengeType: 1
## Description
<section id='description'>
When defining functions within objects in ES5, we have to use the keyword <code>function</code> as follows:
<blockquote>const person = {<br>&nbsp;&nbsp;name: "Taylor",<br>&nbsp;&nbsp;sayHello: function() {<br>&nbsp;&nbsp;&nbsp;&nbsp;return `Hello! My name is ${this.name}.`;<br>&nbsp;&nbsp;}<br>};</blockquote>
```js
const person = {
name: "Taylor",
sayHello: function() {
return `Hello! My name is ${this.name}.`;
}
};
```
With ES6, You can remove the <code>function</code> keyword and colon altogether when defining functions in objects. Here's an example of this syntax:
<blockquote>const person = {<br>&nbsp;&nbsp;name: "Taylor",<br>&nbsp;&nbsp;sayHello() {<br>&nbsp;&nbsp;&nbsp;&nbsp;return `Hello! My name is ${this.name}.`;<br>&nbsp;&nbsp;}<br>};</blockquote>
```js
const person = {
name: "Taylor",
sayHello() {
return `Hello! My name is ${this.name}.`;
}
};
```
</section>
## Instructions

View File

@ -8,11 +8,22 @@ challengeType: 1
<section id='description'>
ES6 adds some nice support for easily defining object literals.
Consider the following code:
<blockquote>const getMousePosition = (x, y) => ({<br>&nbsp;&nbsp;x: x,<br>&nbsp;&nbsp;y: y<br>});</blockquote>
```js
const getMousePosition = (x, y) => ({
x: x,
y: y
});
```
<code>getMousePosition</code> is a simple function that returns an object containing two fields.
ES6 provides the syntactic sugar to eliminate the redundancy of having to write <code>x: x</code>. You can simply write <code>x</code> once, and it will be converted to<code>x: x</code> (or something equivalent) under the hood.
Here is the same function from above rewritten to use this new syntax:
<blockquote>const getMousePosition = (x, y) => ({ x, y });</blockquote>
```js
const getMousePosition = (x, y) => ({ x, y });
```
</section>
## Instructions

View File

@ -8,7 +8,14 @@ challengeType: 1
<section id='description'>
Functional programming is all about creating and using non-mutating functions.
The last challenge introduced the <code>concat</code> method as a way to combine arrays into a new one without mutating the original arrays. Compare <code>concat</code> to the <code>push</code> method. <code>Push</code> adds an item to the end of the same array it is called on, which mutates that array. Here's an example:
<blockquote>var arr = [1, 2, 3];<br>arr.push([4, 5, 6]);<br>// arr is changed to [1, 2, 3, [4, 5, 6]]<br>// Not the functional programming way</blockquote>
```js
var arr = [1, 2, 3];
arr.push([4, 5, 6]);
// arr is changed to [1, 2, 3, [4, 5, 6]]
// Not the functional programming way
```
<code>Concat</code> offers a way to add new items to the end of an array without any mutating side effects.
</section>

View File

@ -8,7 +8,13 @@ challengeType: 1
<section id='description'>
The <code>join</code> method is used to join the elements of an array together to create a string. It takes an argument for the delimiter that is used to separate the array elements in the string.
Here's an example:
<blockquote>var arr = ["Hello", "World"];<br>var str = arr.join(" ");<br>// Sets str to "Hello World"</blockquote>
```js
var arr = ["Hello", "World"];
var str = arr.join(" ");
// Sets str to "Hello World"
```
</section>
## Instructions

View File

@ -7,7 +7,12 @@ challengeType: 1
## Description
<section id='description'>
<code>Concatenation</code> means to join items end to end. JavaScript offers the <code>concat</code> method for both strings and arrays that work in the same way. For arrays, the method is called on one, then another array is provided as the argument to <code>concat</code>, which is added to the end of the first array. It returns a new array and does not mutate either of the original arrays. Here's an example:
<blockquote>[1, 2, 3].concat([4, 5, 6]);<br>// Returns a new array [1, 2, 3, 4, 5, 6]</blockquote>
```js
[1, 2, 3].concat([4, 5, 6]);
// Returns a new array [1, 2, 3, 4, 5, 6]
```
</section>
## Instructions

View File

@ -9,16 +9,45 @@ challengeType: 1
The <code>arity</code> of a function is the number of arguments it requires. <code>Currying</code> a function means to convert a function of N <code>arity</code> into N functions of <code>arity</code> 1.
In other words, it restructures a function so it takes one argument, then returns another function that takes the next argument, and so on.
Here's an example:
<blockquote>//Un-curried function<br>function unCurried(x, y) {<br>&nbsp;&nbsp;return x + y;<br>}<br><br>//Curried function<br>function curried(x) {<br>&nbsp;&nbsp;return function(y) {<br>&nbsp;&nbsp;&nbsp;&nbsp;return x + y;<br>&nbsp;&nbsp;}<br>}
<br>//Alternative using ES6
<br>const curried = x => y => x + y
<br>
<br>curried(1)(2) // Returns 3</blockquote>
```js
//Un-curried function
function unCurried(x, y) {
return x + y;
}
//Curried function
function curried(x) {
return function(y) {
return x + y;
}
}
//Alternative using ES6
const curried = x => y => x + y
curried(1)(2) // Returns 3
```
This is useful in your program if you can't supply all the arguments to a function at one time. You can save each function call into a variable, which will hold the returned function reference that takes the next argument when it's available. Here's an example using the <code>curried</code> function in the example above:
<blockquote>// Call a curried function in parts:<br>var funcForY = curried(1);<br>console.log(funcForY(2)); // Prints 3</blockquote>
```js
// Call a curried function in parts:
var funcForY = curried(1);
console.log(funcForY(2)); // Prints 3
```
Similarly, <code>partial application</code> can be described as applying a few arguments to a function at a time and returning another function that is applied to more arguments.
Here's an example:
<blockquote>//Impartial function<br>function impartial(x, y, z) {<br>&nbsp;&nbsp;return x + y + z;<br>}<br>var partialFn = impartial.bind(this, 1, 2);<br>partialFn(10); // Returns 13</blockquote>
```js
//Impartial function
function impartial(x, y, z) {
return x + y + z;
}
var partialFn = impartial.bind(this, 1, 2);
partialFn(10); // Returns 13
```
</section>
## Instructions

Some files were not shown because too many files have changed in this diff Show More