chore(curriculum): Remove files in wrong format

This commit is contained in:
Bouncey
2018-10-04 14:37:37 +01:00
committed by Stuart Taylor
parent 61222b1fb6
commit 8f39bc1288
2947 changed files with 118541 additions and 212907 deletions

View File

@ -0,0 +1,82 @@
---
id: a77dbc43c33f39daa4429b4f
title: Boo who
isRequired: true
challengeType: 5
---
## Description
<section id='description'>
Check if a value is classified as a boolean primitive. Return true or false.
Boolean primitives are true and false.
Remember to use <a href='http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514' target='_blank'>Read-Search-Ask</a> if you get stuck. Try to pair program. Write your own code.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>booWho(true)</code> should return true.
testString: 'assert.strictEqual(booWho(true), true, ''<code>booWho(true)</code> should return true.'');'
- text: <code>booWho(false)</code> should return true.
testString: 'assert.strictEqual(booWho(false), true, ''<code>booWho(false)</code> should return true.'');'
- text: '<code>booWho([1, 2, 3])</code> should return false.'
testString: 'assert.strictEqual(booWho([1, 2, 3]), false, ''<code>booWho([1, 2, 3])</code> should return false.'');'
- text: '<code>booWho([].slice)</code> should return false.'
testString: 'assert.strictEqual(booWho([].slice), false, ''<code>booWho([].slice)</code> should return false.'');'
- text: '<code>booWho({ "a": 1 })</code> should return false.'
testString: 'assert.strictEqual(booWho({ "a": 1 }), false, ''<code>booWho({ "a": 1 })</code> should return false.'');'
- text: <code>booWho(1)</code> should return false.
testString: 'assert.strictEqual(booWho(1), false, ''<code>booWho(1)</code> should return false.'');'
- text: <code>booWho(NaN)</code> should return false.
testString: 'assert.strictEqual(booWho(NaN), false, ''<code>booWho(NaN)</code> should return false.'');'
- text: <code>booWho("a")</code> should return false.
testString: 'assert.strictEqual(booWho("a"), false, ''<code>booWho("a")</code> should return false.'');'
- text: <code>booWho("true")</code> should return false.
testString: 'assert.strictEqual(booWho("true"), false, ''<code>booWho("true")</code> should return false.'');'
- text: <code>booWho("false")</code> should return false.
testString: 'assert.strictEqual(booWho("false"), false, ''<code>booWho("false")</code> should return false.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function booWho(bool) {
// What is the new fad diet for ghost developers? The Boolean.
return bool;
}
booWho(null);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function booWho(bool) {
return typeof bool === "boolean";
}
booWho(null);
```
</section>

View File

@ -0,0 +1,82 @@
---
id: a9bd25c716030ec90084d8a1
title: Chunky Monkey
isRequired: true
challengeType: 5
---
## Description
<section id='description'>
Write a function that splits an array (first argument) into groups the length of <code>size</code> (second argument) and returns them as a two-dimensional array.
Remember to use <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> if you get stuck. Write your own code.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>chunkArrayInGroups(["a", "b", "c", "d"], 2)</code> should return <code>[["a", "b"], ["c", "d"]]</code>.'
testString: 'assert.deepEqual(chunkArrayInGroups(["a", "b", "c", "d"], 2), [["a", "b"], ["c", "d"]], ''<code>chunkArrayInGroups(["a", "b", "c", "d"], 2)</code> should return <code>[["a", "b"], ["c", "d"]]</code>.'');'
- text: '<code>chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3)</code> should return <code>[[0, 1, 2], [3, 4, 5]]</code>.'
testString: 'assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3), [[0, 1, 2], [3, 4, 5]], ''<code>chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3)</code> should return <code>[[0, 1, 2], [3, 4, 5]]</code>.'');'
- text: '<code>chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2)</code> should return <code>[[0, 1], [2, 3], [4, 5]]</code>.'
testString: 'assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2), [[0, 1], [2, 3], [4, 5]], ''<code>chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2)</code> should return <code>[[0, 1], [2, 3], [4, 5]]</code>.'');'
- text: '<code>chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4)</code> should return <code>[[0, 1, 2, 3], [4, 5]]</code>.'
testString: 'assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4), [[0, 1, 2, 3], [4, 5]], ''<code>chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4)</code> should return <code>[[0, 1, 2, 3], [4, 5]]</code>.'');'
- text: '<code>chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3)</code> should return <code>[[0, 1, 2], [3, 4, 5], [6]]</code>.'
testString: 'assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3), [[0, 1, 2], [3, 4, 5], [6]], ''<code>chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3)</code> should return <code>[[0, 1, 2], [3, 4, 5], [6]]</code>.'');'
- text: '<code>chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4)</code> should return <code>[[0, 1, 2, 3], [4, 5, 6, 7], [8]]</code>.'
testString: 'assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4), [[0, 1, 2, 3], [4, 5, 6, 7], [8]], ''<code>chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4)</code> should return <code>[[0, 1, 2, 3], [4, 5, 6, 7], [8]]</code>.'');'
- text: '<code>chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2)</code> should return <code>[[0, 1], [2, 3], [4, 5], [6, 7], [8]]</code>.'
testString: 'assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2), [[0, 1], [2, 3], [4, 5], [6, 7], [8]], ''<code>chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2)</code> should return <code>[[0, 1], [2, 3], [4, 5], [6, 7], [8]]</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function chunkArrayInGroups(arr, size) {
// Break it up.
return arr;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function chunkArrayInGroups(arr, size) {
let out = [];
for (let i = 0; i < arr.length; i += size) {
out.push(arr.slice(i, i + size));
}
return out;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
```
</section>

View File

@ -0,0 +1,86 @@
---
id: acda2fb1324d9b0fa741e6b5
title: Confirm the Ending
isRequired: true
challengeType: 5
---
## Description
<section id='description'>
Check if a string (first argument, <code>str</code>) ends with the given target string (second argument, <code>target</code>).
This challenge <em>can</em> be solved with the <code>.endsWith()</code> method, which was introduced in ES2015. But for the purpose of this challenge, we would like you to use one of the JavaScript substring methods instead.
Remember to use <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> if you get stuck. Write your own code.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>confirmEnding("Bastian", "n")</code> should return true.'
testString: 'assert(confirmEnding("Bastian", "n") === true, ''<code>confirmEnding("Bastian", "n")</code> should return true.'');'
- text: '<code>confirmEnding("Congratulation", "on")</code> should return true.'
testString: 'assert(confirmEnding("Congratulation", "on") === true, ''<code>confirmEnding("Congratulation", "on")</code> should return true.'');'
- text: '<code>confirmEnding("Connor", "n")</code> should return false.'
testString: 'assert(confirmEnding("Connor", "n") === false, ''<code>confirmEnding("Connor", "n")</code> should return false.'');'
- text: '<code>confirmEnding("Walking on water and developing software from a specification are easy if both are frozen"&#44; "specification"&#41;</code> should return false.'
testString: 'assert(confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification") === false, ''<code>confirmEnding("Walking on water and developing software from a specification are easy if both are frozen"&#44; "specification"&#41;</code> should return false.'');'
- text: '<code>confirmEnding("He has to give me a new name", "name")</code> should return true.'
testString: 'assert(confirmEnding("He has to give me a new name", "name") === true, ''<code>confirmEnding("He has to give me a new name", "name")</code> should return true.'');'
- text: '<code>confirmEnding("Open sesame", "same")</code> should return true.'
testString: 'assert(confirmEnding("Open sesame", "same") === true, ''<code>confirmEnding("Open sesame", "same")</code> should return true.'');'
- text: '<code>confirmEnding("Open sesame", "pen")</code> should return false.'
testString: 'assert(confirmEnding("Open sesame", "pen") === false, ''<code>confirmEnding("Open sesame", "pen")</code> should return false.'');'
- text: '<code>confirmEnding("Open sesame", "game")</code> should return false.'
testString: 'assert(confirmEnding("Open sesame", "game") === false, ''<code>confirmEnding("Open sesame", "game")</code> should return false.'');'
- text: '<code>confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain")</code> should return false.'
testString: 'assert(confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain") === false, ''<code>confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain")</code> should return false.'');'
- text: '<code>confirmEnding("Abstraction", "action")</code> should return true.'
testString: 'assert(confirmEnding("Abstraction", "action") === true, ''<code>confirmEnding("Abstraction", "action")</code> should return true.'');'
- text: Do not use the built-in method <code>.endsWith()</code> to solve the challenge.
testString: 'assert(!(/\.endsWith\(.*?\)\s*?;?/.test(code)) && !(/\[''endsWith''\]/.test(code)), ''Do not use the built-in method <code>.endsWith()</code> to solve the challenge.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function confirmEnding(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
return str;
}
confirmEnding("Bastian", "n");
```
</div>
</section>
## Solution
<section id='solution'>
```js
function confirmEnding(str, target) {
return str.substring(str.length - target.length) === target;
}
confirmEnding("Bastian", "n");
```
</section>

View File

@ -0,0 +1,77 @@
---
id: 56533eb9ac21ba0edf2244b3
title: Convert Celsius to Fahrenheit
challengeType: 1
isRequired: true
---
## Description
<section id='description'>
The algorithm to convert from Celsius to Fahrenheit is the temperature in Celsius times <code>9/5</code>, plus <code>32</code>.
You are given a variable <code>celsius</code> representing a temperature in Celsius. Use the variable <code>fahrenheit</code> already defined and assign it the Fahrenheit temperature equivalent to the given Celsius temperature. Use the algorithm mentioned above to help convert the Celsius temperature to Fahrenheit.
Don't worry too much about the function and return statements as they will be covered in future challenges. For now, only use operators that you have already learned.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>convertToF(0)</code> should return a number
testString: 'assert(typeof convertToF(0) === ''number'', ''<code>convertToF(0)</code> should return a number'');'
- text: <code>convertToF(-30)</code> should return a value of <code>-22</code>
testString: 'assert(convertToF(-30) === -22, ''<code>convertToF(-30)</code> should return a value of <code>-22</code>'');'
- text: <code>convertToF(-10)</code> should return a value of <code>14</code>
testString: 'assert(convertToF(-10) === 14, ''<code>convertToF(-10)</code> should return a value of <code>14</code>'');'
- text: <code>convertToF(0)</code> should return a value of <code>32</code>
testString: 'assert(convertToF(0) === 32, ''<code>convertToF(0)</code> should return a value of <code>32</code>'');'
- text: <code>convertToF(20)</code> should return a value of <code>68</code>
testString: 'assert(convertToF(20) === 68, ''<code>convertToF(20)</code> should return a value of <code>68</code>'');'
- text: <code>convertToF(30)</code> should return a value of <code>86</code>
testString: 'assert(convertToF(30) === 86, ''<code>convertToF(30)</code> should return a value of <code>86</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function convertToF(celsius) {
let fahrenheit;
return fahrenheit;
}
convertToF(30);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function convertToF(celsius) {
let fahrenheit = celsius * 9/5 + 32;
return fahrenheit;
}
convertToF(30);
```
</section>

View File

@ -0,0 +1,75 @@
---
id: a302f7aae1aa3152a5b413bc
title: Factorialize a Number
isRequired: true
challengeType: 5
---
## Description
<section id='description'>
Return the factorial of the provided integer.
If the integer is represented with the letter n, a factorial is the product of all positive integers less than or equal to n.
Factorials are often represented with the shorthand notation <code>n!</code>
For example: <code>5! = 1 * 2 * 3 * 4 * 5 = 120</code>
Only integers greater than or equal to zero will be supplied to the function.
Remember to use <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> if you get stuck. Write your own code.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>factorialize(5)</code> should return a number.
testString: 'assert(typeof factorialize(5) === ''number'', ''<code>factorialize(5)</code> should return a number.'');'
- text: <code>factorialize(5)</code> should return 120.
testString: 'assert(factorialize(5) === 120, ''<code>factorialize(5)</code> should return 120.'');'
- text: <code>factorialize(10)</code> should return 3628800.
testString: 'assert(factorialize(10) === 3628800, ''<code>factorialize(10)</code> should return 3628800.'');'
- text: <code>factorialize(20)</code> should return 2432902008176640000.
testString: 'assert(factorialize(20) === 2432902008176640000, ''<code>factorialize(20)</code> should return 2432902008176640000.'');'
- text: <code>factorialize(0)</code> should return 1.
testString: 'assert(factorialize(0) === 1, ''<code>factorialize(0)</code> should return 1.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function factorialize(num) {
return num;
}
factorialize(5);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function factorialize(num) {
return num < 1 ? 1 : num * factorialize(num - 1);
}
factorialize(5);
```
</section>

View File

@ -0,0 +1,72 @@
---
id: adf08ec01beb4f99fc7a68f2
title: Falsy Bouncer
isRequired: true
challengeType: 5
---
## Description
<section id='description'>
Remove all falsy values from an array.
Falsy values in JavaScript are <code>false</code>, <code>null</code>, <code>0</code>, <code>""</code>, <code>undefined</code>, and <code>NaN</code>.
Hint: Try converting each value to a Boolean.
Remember to use <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> if you get stuck. Write your own code.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>bouncer([7, "ate", "", false, 9])</code> should return <code>[7, "ate", 9]</code>.'
testString: 'assert.deepEqual(bouncer([7, "ate", "", false, 9]), [7, "ate", 9], ''<code>bouncer([7, "ate", "", false, 9])</code> should return <code>[7, "ate", 9]</code>.'');'
- text: '<code>bouncer(["a", "b", "c"])</code> should return <code>["a", "b", "c"]</code>.'
testString: 'assert.deepEqual(bouncer(["a", "b", "c"]), ["a", "b", "c"], ''<code>bouncer(["a", "b", "c"])</code> should return <code>["a", "b", "c"]</code>.'');'
- text: '<code>bouncer([false, null, 0, NaN, undefined, ""])</code> should return <code>[]</code>.'
testString: 'assert.deepEqual(bouncer([false, null, 0, NaN, undefined, ""]), [], ''<code>bouncer([false, null, 0, NaN, undefined, ""])</code> should return <code>[]</code>.'');'
- text: '<code>bouncer([1, null, NaN, 2, undefined])</code> should return <code>[1, 2]</code>.'
testString: 'assert.deepEqual(bouncer([1, null, NaN, 2, undefined]), [1, 2], ''<code>bouncer([1, null, NaN, 2, undefined])</code> should return <code>[1, 2]</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function bouncer(arr) {
// Don't show a false ID to this bouncer.
return arr;
}
bouncer([7, "ate", "", false, 9]);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function bouncer(arr) {
return arr.filter(e => e);
}
bouncer([7, "ate", "", false, 9]);
```
</section>

View File

@ -0,0 +1,74 @@
---
id: a26cbbe9ad8655a977e1ceb5
title: Find the Longest Word in a String
isRequired: true
challengeType: 5
---
## Description
<section id='description'>
Return the length of the longest word in the provided sentence.
Your response should be a number.
Remember to use <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> if you get stuck. Write your own code.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>findLongestWordLength("The quick brown fox jumped over the lazy dog")</code> should return a number.
testString: 'assert(typeof findLongestWordLength("The quick brown fox jumped over the lazy dog") === "number", ''<code>findLongestWordLength("The quick brown fox jumped over the lazy dog")</code> should return a number.'');'
- text: <code>findLongestWordLength("The quick brown fox jumped over the lazy dog")</code> should return 6.
testString: 'assert(findLongestWordLength("The quick brown fox jumped over the lazy dog") === 6, ''<code>findLongestWordLength("The quick brown fox jumped over the lazy dog")</code> should return 6.'');'
- text: <code>findLongestWordLength("May the force be with you")</code> should return 5.
testString: 'assert(findLongestWordLength("May the force be with you") === 5, ''<code>findLongestWordLength("May the force be with you")</code> should return 5.'');'
- text: <code>findLongestWordLength("Google do a barrel roll")</code> should return 6.
testString: 'assert(findLongestWordLength("Google do a barrel roll") === 6, ''<code>findLongestWordLength("Google do a barrel roll")</code> should return 6.'');'
- text: <code>findLongestWordLength("What is the average airspeed velocity of an unladen swallow")</code> should return 8.
testString: 'assert(findLongestWordLength("What is the average airspeed velocity of an unladen swallow") === 8, ''<code>findLongestWordLength("What is the average airspeed velocity of an unladen swallow")</code> should return 8.'');'
- text: <code>findLongestWordLength("What if we try a super-long word such as otorhinolaryngology")</code> should return 19.
testString: 'assert(findLongestWordLength("What if we try a super-long word such as otorhinolaryngology") === 19, ''<code>findLongestWordLength("What if we try a super-long word such as otorhinolaryngology")</code> should return 19.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function findLongestWordLength(str) {
return str.length;
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");
```
</div>
</section>
## Solution
<section id='solution'>
```js
function findLongestWordLength(str) {
return str.split(' ').sort((a, b) => b.length - a.length)[0].length;
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");
```
</section>

View File

@ -0,0 +1,75 @@
---
id: a6e40f1041b06c996f7b2406
title: Finders Keepers
isRequired: true
challengeType: 5
---
## Description
<section id='description'>
Create a function that looks through an array (first argument) and returns the first element in the array that passes a truth test (second argument). If no element passes the test, return undefined.
Remember to use <a href='http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514' target='_blank'>Read-Search-Ask</a> if you get stuck. Try to pair program. Write your own code.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; })</code> should return 8.'
testString: 'assert.strictEqual(findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; }), 8, ''<code>findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; })</code> should return 8.'');'
- text: '<code>findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; })</code> should return undefined.'
testString: 'assert.strictEqual(findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; }), undefined, ''<code>findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; })</code> should return undefined.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function findElement(arr, func) {
let num = 0;
return num;
}
findElement([1, 2, 3, 4], num => num % 2 === 0);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function findElement(arr, func) {
let num;
arr.some(e => {
if (func(e)) {
num = e;
return true;
}
});
return num;
}
findElement([1, 2, 3, 4], num => num % 2 === 0);
```
</section>

View File

@ -0,0 +1,78 @@
{
"name": "Basic Algorithm Scripting",
"dashedName": "basic-algorithm-scripting",
"order": 6,
"time": "50 hours",
"template": "",
"required": [],
"superBlock": "javascript-algorithms-and-data-structures",
"superOrder": 2,
"challengeOrder": [
[
"56533eb9ac21ba0edf2244b3",
"Convert Celsius to Fahrenheit"
],
[
"a202eed8fc186c8434cb6d61",
"Reverse a String"
],
[
"a302f7aae1aa3152a5b413bc",
"Factorialize a Number"
],
[
"a26cbbe9ad8655a977e1ceb5",
"Find the Longest Word in a String"
],
[
"a789b3483989747d63b0e427",
"Return Largest Numbers in Arrays"
],
[
"acda2fb1324d9b0fa741e6b5",
"Confirm the Ending"
],
[
"afcc8d540bea9ea2669306b6",
"Repeat a String Repeat a String"
],
[
"ac6993d51946422351508a41",
"Truncate a String"
],
[
"a6e40f1041b06c996f7b2406",
"Finders Keepers"
],
[
"a77dbc43c33f39daa4429b4f",
"Boo who"
],
[
"ab6137d4e35944e21037b769",
"Title Case a Sentence"
],
[
"579e2a2c335b9d72dd32e05c",
"Slice and Splice"
],
[
"adf08ec01beb4f99fc7a68f2",
"Falsy Bouncer"
],
[
"a24c1a4622e3c05097f71d67",
"Where do I Belong"
],
[
"af2170cad53daa0770fabdea",
"Mutations"
],
[
"a9bd25c716030ec90084d8a1",
"Chunky Monkey"
]
],
"helpRoom": "HelpJavaScript",
"fileName": "02-javascript-algorithms-and-data-structures/basic-algorithm-scripting.json"
}

View File

@ -0,0 +1,86 @@
---
id: af2170cad53daa0770fabdea
title: Mutations
isRequired: true
challengeType: 5
---
## Description
<section id='description'>
Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array.
For example, <code>["hello", "Hello"]</code>, should return true because all of the letters in the second string are present in the first, ignoring case.
The arguments <code>["hello", "hey"]</code> should return false because the string "hello" does not contain a "y".
Lastly, <code>["Alien", "line"]</code>, should return true because all of the letters in "line" are present in "Alien".
Remember to use <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> if you get stuck. Write your own code.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>mutation(["hello", "hey"])</code> should return false.'
testString: 'assert(mutation(["hello", "hey"]) === false, ''<code>mutation(["hello", "hey"])</code> should return false.'');'
- text: '<code>mutation(["hello", "Hello"])</code> should return true.'
testString: 'assert(mutation(["hello", "Hello"]) === true, ''<code>mutation(["hello", "Hello"])</code> should return true.'');'
- text: '<code>mutation(["zyxwvutsrqponmlkjihgfedcba", "qrstu"])</code> should return true.'
testString: 'assert(mutation(["zyxwvutsrqponmlkjihgfedcba", "qrstu"]) === true, ''<code>mutation(["zyxwvutsrqponmlkjihgfedcba", "qrstu"])</code> should return true.'');'
- text: '<code>mutation(["Mary", "Army"])</code> should return true.'
testString: 'assert(mutation(["Mary", "Army"]) === true, ''<code>mutation(["Mary", "Army"])</code> should return true.'');'
- text: '<code>mutation(["Mary", "Aarmy"])</code> should return true.'
testString: 'assert(mutation(["Mary", "Aarmy"]) === true, ''<code>mutation(["Mary", "Aarmy"])</code> should return true.'');'
- text: '<code>mutation(["Alien", "line"])</code> should return true.'
testString: 'assert(mutation(["Alien", "line"]) === true, ''<code>mutation(["Alien", "line"])</code> should return true.'');'
- text: '<code>mutation(["floor", "for"])</code> should return true.'
testString: 'assert(mutation(["floor", "for"]) === true, ''<code>mutation(["floor", "for"])</code> should return true.'');'
- text: '<code>mutation(["hello", "neo"])</code> should return false.'
testString: 'assert(mutation(["hello", "neo"]) === false, ''<code>mutation(["hello", "neo"])</code> should return false.'');'
- text: '<code>mutation(["voodoo", "no"])</code> should return false.'
testString: 'assert(mutation(["voodoo", "no"]) === false, ''<code>mutation(["voodoo", "no"])</code> should return false.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function mutation(arr) {
return arr;
}
mutation(["hello", "hey"]);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function mutation(arr) {
let hash = Object.create(null);
arr[0].toLowerCase().split('').forEach(c => hash[c] = true);
return !arr[1].toLowerCase().split('').filter(c => !hash[c]).length;
}
mutation(["hello", "hey"]);
```
</section>

View File

@ -0,0 +1,77 @@
---
id: afcc8d540bea9ea2669306b6
title: Repeat a String Repeat a String
isRequired: true
challengeType: 5
---
## Description
<section id='description'>
Repeat a given string <code>str</code> (first argument) for <code>num</code> times (second argument). Return an empty string if <code>num</code> is not a positive number.
Remember to use <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> if you get stuck. Write your own code.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>repeatStringNumTimes("*", 3)</code> should return <code>"***"</code>.'
testString: 'assert(repeatStringNumTimes("*", 3) === "***", ''<code>repeatStringNumTimes("*", 3)</code> should return <code>"***"</code>.'');'
- text: '<code>repeatStringNumTimes("abc", 3)</code> should return <code>"abcabcabc"</code>.'
testString: 'assert(repeatStringNumTimes("abc", 3) === "abcabcabc", ''<code>repeatStringNumTimes("abc", 3)</code> should return <code>"abcabcabc"</code>.'');'
- text: '<code>repeatStringNumTimes("abc", 4)</code> should return <code>"abcabcabcabc"</code>.'
testString: 'assert(repeatStringNumTimes("abc", 4) === "abcabcabcabc", ''<code>repeatStringNumTimes("abc", 4)</code> should return <code>"abcabcabcabc"</code>.'');'
- text: '<code>repeatStringNumTimes("abc", 1)</code> should return <code>"abc"</code>.'
testString: 'assert(repeatStringNumTimes("abc", 1) === "abc", ''<code>repeatStringNumTimes("abc", 1)</code> should return <code>"abc"</code>.'');'
- text: '<code>repeatStringNumTimes("*", 8)</code> should return <code>"********"</code>.'
testString: 'assert(repeatStringNumTimes("*", 8) === "********", ''<code>repeatStringNumTimes("*", 8)</code> should return <code>"********"</code>.'');'
- text: '<code>repeatStringNumTimes("abc", -2)</code> should return <code>""</code>.'
testString: 'assert(repeatStringNumTimes("abc", -2) === "", ''<code>repeatStringNumTimes("abc", -2)</code> should return <code>""</code>.'');'
- text: The built-in <code>repeat()</code>-method should not be used
testString: 'assert(!/\.repeat/g.test(code), ''The built-in <code>repeat()</code>-method should not be used'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function repeatStringNumTimes(str, num) {
// repeat after me
return str;
}
repeatStringNumTimes("abc", 3);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function repeatStringNumTimes(str, num) {
if (num < 0) return '';
return num === 1 ? str : str + repeatStringNumTimes(str, num-1);
}
repeatStringNumTimes("abc", 3);
```
</section>

View File

@ -0,0 +1,71 @@
---
id: a789b3483989747d63b0e427
title: Return Largest Numbers in Arrays
isRequired: true
challengeType: 5
---
## Description
<section id='description'>
Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.
Remember, you can iterate through an array with a simple for loop, and access each member with array syntax <code>arr[i]</code>.
Remember to use <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> if you get stuck. Write your own code.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])</code> should return an array.'
testString: 'assert(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]).constructor === Array, ''<code>largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])</code> should return an array.'');'
- text: '<code>largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]])</code> should return <code>[27, 5, 39, 1001]</code>.'
testString: 'assert.deepEqual(largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]), [27, 5, 39, 1001], ''<code>largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]])</code> should return <code>[27, 5, 39, 1001]</code>.'');'
- text: '<code>largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]])</code> should return <code>[9, 35, 97, 1000000]</code>.'
testString: 'assert.deepEqual(largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]), [9, 35, 97, 1000000], ''<code>largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]])</code> should return <code>[9, 35, 97, 1000000]</code>.'');'
- text: '<code>largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]])</code> should return <code>[25, 48, 21, -3]</code>.'
testString: 'assert.deepEqual(largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]), [25, 48, 21, -3], ''<code>largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]])</code> should return <code>[25, 48, 21, -3]</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function largestOfFour(arr) {
// You can do this!
return arr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function largestOfFour(arr) {
return arr.map(subArr => Math.max.apply(null, subArr));
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
```
</section>

View File

@ -0,0 +1,71 @@
---
id: a202eed8fc186c8434cb6d61
title: Reverse a String
isRequired: true
challengeType: 5
---
## Description
<section id='description'>
Reverse the provided string.
You may need to turn the string into an array before you can reverse it.
Your result must be a string.
Remember to use <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> if you get stuck. Write your own code.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>reverseString("hello")</code> should return a string.
testString: 'assert(typeof reverseString("hello") === "string", ''<code>reverseString("hello")</code> should return a string.'');'
- text: <code>reverseString("hello")</code> should become <code>"olleh"</code>.
testString: 'assert(reverseString("hello") === "olleh", ''<code>reverseString("hello")</code> should become <code>"olleh"</code>.'');'
- text: <code>reverseString("Howdy")</code> should become <code>"ydwoH"</code>.
testString: 'assert(reverseString("Howdy") === "ydwoH", ''<code>reverseString("Howdy")</code> should become <code>"ydwoH"</code>.'');'
- text: <code>reverseString("Greetings from Earth")</code> should return <code>"htraE morf sgniteerG"</code>.
testString: 'assert(reverseString("Greetings from Earth") === "htraE morf sgniteerG", ''<code>reverseString("Greetings from Earth")</code> should return <code>"htraE morf sgniteerG"</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function reverseString(str) {
return str;
}
reverseString("hello");
```
</div>
</section>
## Solution
<section id='solution'>
```js
function reverseString(str) {
return str.split('').reverse().join('');
}
reverseString("hello");
```
</section>

View File

@ -0,0 +1,91 @@
---
id: 579e2a2c335b9d72dd32e05c
title: Slice and Splice
isRequired: true
isBeta: true
challengeType: 5
---
## Description
<section id='description'>
You are given two arrays and an index.
Use the array methods <code>slice</code> and <code>splice</code> to copy each element of the first array into the second array, in order.
Begin inserting elements at index <code>n</code> of the second array.
Return the resulting array. The input arrays should remain the same after the function runs.
Remember to use <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> if you get stuck. Write your own code.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>frankenSplice([1, 2, 3], [4, 5], 1)</code> should return <code>[4, 1, 2, 3, 5]</code>.'
testString: 'assert.deepEqual(frankenSplice([1, 2, 3], [4, 5], 1), [4, 1, 2, 3, 5], ''<code>frankenSplice([1, 2, 3], [4, 5], 1)</code> should return <code>[4, 1, 2, 3, 5]</code>.'');'
- text: '<code>frankenSplice([1, 2], ["a", "b"], 1)</code> should return <code>["a", 1, 2, "b"]</code>.'
testString: 'assert.deepEqual(frankenSplice(testArr1, testArr2, 1), ["a", 1, 2, "b"], ''<code>frankenSplice([1, 2], ["a", "b"], 1)</code> should return <code>["a", 1, 2, "b"]</code>.'');'
- text: '<code>frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2)</code> should return <code>["head", "shoulders", "claw", "tentacle", "knees", "toes"]</code>.'
testString: 'assert.deepEqual(frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2), ["head", "shoulders", "claw", "tentacle", "knees", "toes"], ''<code>frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2)</code> should return <code>["head", "shoulders", "claw", "tentacle", "knees", "toes"]</code>.'');'
- text: All elements from the first array should be added to the second array in their original order.
testString: 'assert.deepEqual(frankenSplice([1, 2, 3, 4], [], 0), [1, 2, 3, 4], ''All elements from the first array should be added to the second array in their original order.'');'
- text: The first array should remain the same after the function runs.
testString: 'assert(testArr1[0] === 1 && testArr1[1] === 2, ''The first array should remain the same after the function runs.'');'
- text: The second array should remain the same after the function runs.
testString: 'assert(testArr2[0] === "a" && testArr2[1] === "b", ''The second array should remain the same after the function runs.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function frankenSplice(arr1, arr2, n) {
// It's alive. It's alive!
return arr2;
}
frankenSplice([1, 2, 3], [4, 5, 6], 1);
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
function frankenSplice(arr1, arr2, n) {
// It's alive. It's alive!
let result = arr2.slice();
for (let i = 0; i < arr1.length; i++) {
result.splice(n+i, 0, arr1[i]);
}
return result;
}
frankenSplice([1, 2, 3], [4, 5], 1);
```
</section>

View File

@ -0,0 +1,70 @@
---
id: ab6137d4e35944e21037b769
title: Title Case a Sentence
isRequired: true
challengeType: 5
---
## Description
<section id='description'>
Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lower case.
For the purpose of this exercise, you should also capitalize connecting words like "the" and "of".
Remember to use <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> if you get stuck. Write your own code.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>titleCase("I&#39;m a little tea pot")</code> should return a string.'
testString: 'assert(typeof titleCase("I''m a little tea pot") === "string", ''<code>titleCase("I&#39;m a little tea pot")</code> should return a string.'');'
- text: '<code>titleCase("I&#39;m a little tea pot")</code> should return <code>I&#39;m A Little Tea Pot</code>.'
testString: 'assert(titleCase("I''m a little tea pot") === "I''m A Little Tea Pot", ''<code>titleCase("I&#39;m a little tea pot")</code> should return <code>I&#39;m A Little Tea Pot</code>.'');'
- text: <code>titleCase("sHoRt AnD sToUt")</code> should return <code>Short And Stout</code>.
testString: 'assert(titleCase("sHoRt AnD sToUt") === "Short And Stout", ''<code>titleCase("sHoRt AnD sToUt")</code> should return <code>Short And Stout</code>.'');'
- text: <code>titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")</code> should return <code>Here Is My Handle Here Is My Spout</code>.
testString: 'assert(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT") === "Here Is My Handle Here Is My Spout", ''<code>titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")</code> should return <code>Here Is My Handle Here Is My Spout</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function titleCase(str) {
return str;
}
titleCase("I'm a little tea pot");
```
</div>
</section>
## Solution
<section id='solution'>
```js
function titleCase(str) {
return str.split(' ').map(word => word.charAt(0).toUpperCase() + word.substring(1).toLowerCase()).join(' ');
}
titleCase("I'm a little tea pot");
```
</section>

View File

@ -0,0 +1,78 @@
---
id: ac6993d51946422351508a41
title: Truncate a String
isRequired: true
challengeType: 5
---
## Description
<section id='description'>
Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a <code>...</code> ending.
Remember to use <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> if you get stuck. Write your own code.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>truncateString("A-tisket a-tasket A green and yellow basket", 8)</code> should return "A-tisket...".'
testString: 'assert(truncateString("A-tisket a-tasket A green and yellow basket", 8) === "A-tisket...", ''<code>truncateString("A-tisket a-tasket A green and yellow basket", 8)</code> should return "A-tisket...".'');'
- text: '<code>truncateString("Peter Piper picked a peck of pickled peppers", 11)</code> should return "Peter Piper...".'
testString: 'assert(truncateString("Peter Piper picked a peck of pickled peppers", 11) === "Peter Piper...", ''<code>truncateString("Peter Piper picked a peck of pickled peppers", 11)</code> should return "Peter Piper...".'');'
- text: '<code>truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length)</code> should return "A-tisket a-tasket A green and yellow basket".'
testString: 'assert(truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length) === "A-tisket a-tasket A green and yellow basket", ''<code>truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length)</code> should return "A-tisket a-tasket A green and yellow basket".'');'
- text: '<code>truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2)</code> should return "A-tisket a-tasket A green and yellow basket".'
testString: 'assert(truncateString(''A-tisket a-tasket A green and yellow basket'', ''A-tisket a-tasket A green and yellow basket''.length + 2) === ''A-tisket a-tasket A green and yellow basket'', ''<code>truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2)</code> should return "A-tisket a-tasket A green and yellow basket".'');'
- text: '<code>truncateString("A-", 1)</code> should return "A...".'
testString: 'assert(truncateString("A-", 1) === "A...", ''<code>truncateString("A-", 1)</code> should return "A...".'');'
- text: '<code>truncateString("Absolutely Longer", 2)</code> should return "Ab...".'
testString: 'assert(truncateString("Absolutely Longer", 2) === "Ab...", ''<code>truncateString("Absolutely Longer", 2)</code> should return "Ab...".'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function truncateString(str, num) {
// Clear out that junk in your trunk
return str;
}
truncateString("A-tisket a-tasket A green and yellow basket", 8);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function truncateString(str, num) {
if (num >= str.length) {
return str;
}
return str.slice(0, num) + '...';
}
truncateString("A-tisket a-tasket A green and yellow basket", 8);
```
</section>

View File

@ -0,0 +1,104 @@
---
id: a24c1a4622e3c05097f71d67
title: Where do I Belong
isRequired: true
challengeType: 5
---
## Description
<section id='description'>
Return the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. The returned value should be a number.
For example, <code>getIndexToIns([1,2,3,4], 1.5)</code> should return <code>1</code> because it is greater than <code>1</code> (index 0), but less than <code>2</code> (index 1).
Likewise, <code>getIndexToIns([20,3,5], 19)</code> should return <code>2</code> because once the array has been sorted it will look like <code>[3,5,20]</code> and <code>19</code> is less than <code>20</code> (index 2) and greater than <code>5</code> (index 1).
Remember to use <a href="http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514" target="_blank">Read-Search-Ask</a> if you get stuck. Write your own code.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>getIndexToIns([10, 20, 30, 40, 50], 35)</code> should return <code>3</code>.'
testString: 'assert(getIndexToIns([10, 20, 30, 40, 50], 35) === 3, ''<code>getIndexToIns([10, 20, 30, 40, 50], 35)</code> should return <code>3</code>.'');'
- text: '<code>getIndexToIns([10, 20, 30, 40, 50], 35)</code> should return a number.'
testString: 'assert(typeof(getIndexToIns([10, 20, 30, 40, 50], 35)) === "number", ''<code>getIndexToIns([10, 20, 30, 40, 50], 35)</code> should return a number.'');'
- text: '<code>getIndexToIns([10, 20, 30, 40, 50], 30)</code> should return <code>2</code>.'
testString: 'assert(getIndexToIns([10, 20, 30, 40, 50], 30) === 2, ''<code>getIndexToIns([10, 20, 30, 40, 50], 30)</code> should return <code>2</code>.'');'
- text: '<code>getIndexToIns([10, 20, 30, 40, 50], 30)</code> should return a number.'
testString: 'assert(typeof(getIndexToIns([10, 20, 30, 40, 50], 30)) === "number", ''<code>getIndexToIns([10, 20, 30, 40, 50], 30)</code> should return a number.'');'
- text: '<code>getIndexToIns([40, 60], 50)</code> should return <code>1</code>.'
testString: 'assert(getIndexToIns([40, 60], 50) === 1, ''<code>getIndexToIns([40, 60], 50)</code> should return <code>1</code>.'');'
- text: '<code>getIndexToIns([40, 60], 50)</code> should return a number.'
testString: 'assert(typeof(getIndexToIns([40, 60], 50)) === "number", ''<code>getIndexToIns([40, 60], 50)</code> should return a number.'');'
- text: '<code>getIndexToIns([3, 10, 5], 3)</code> should return <code>0</code>.'
testString: 'assert(getIndexToIns([3, 10, 5], 3) === 0, ''<code>getIndexToIns([3, 10, 5], 3)</code> should return <code>0</code>.'');'
- text: '<code>getIndexToIns([3, 10, 5], 3)</code> should return a number.'
testString: 'assert(typeof(getIndexToIns([3, 10, 5], 3)) === "number", ''<code>getIndexToIns([3, 10, 5], 3)</code> should return a number.'');'
- text: '<code>getIndexToIns([5, 3, 20, 3], 5)</code> should return <code>2</code>.'
testString: 'assert(getIndexToIns([5, 3, 20, 3], 5) === 2, ''<code>getIndexToIns([5, 3, 20, 3], 5)</code> should return <code>2</code>.'');'
- text: '<code>getIndexToIns([5, 3, 20, 3], 5)</code> should return a number.'
testString: 'assert(typeof(getIndexToIns([5, 3, 20, 3], 5)) === "number", ''<code>getIndexToIns([5, 3, 20, 3], 5)</code> should return a number.'');'
- text: '<code>getIndexToIns([2, 20, 10], 19)</code> should return <code>2</code>.'
testString: 'assert(getIndexToIns([2, 20, 10], 19) === 2, ''<code>getIndexToIns([2, 20, 10], 19)</code> should return <code>2</code>.'');'
- text: '<code>getIndexToIns([2, 20, 10], 19)</code> should return a number.'
testString: 'assert(typeof(getIndexToIns([2, 20, 10], 19)) === "number", ''<code>getIndexToIns([2, 20, 10], 19)</code> should return a number.'');'
- text: '<code>getIndexToIns([2, 5, 10], 15)</code> should return <code>3</code>.'
testString: 'assert(getIndexToIns([2, 5, 10], 15) === 3, ''<code>getIndexToIns([2, 5, 10], 15)</code> should return <code>3</code>.'');'
- text: '<code>getIndexToIns([2, 5, 10], 15)</code> should return a number.'
testString: 'assert(typeof(getIndexToIns([2, 5, 10], 15)) === "number", ''<code>getIndexToIns([2, 5, 10], 15)</code> should return a number.'');'
- text: '<code>getIndexToIns([], 1)</code> should return <code>0</code>.'
testString: 'assert(getIndexToIns([], 1) === 0, ''<code>getIndexToIns([], 1)</code> should return <code>0</code>.'');'
- text: '<code>getIndexToIns([], 1)</code> should return a number.'
testString: 'assert(typeof(getIndexToIns([], 1)) === "number", ''<code>getIndexToIns([], 1)</code> should return a number.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function getIndexToIns(arr, num) {
// Find my place in this sorted array.
return num;
}
getIndexToIns([40, 60], 50);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function getIndexToIns(arr, num) {
arr = arr.sort((a, b) => a - b);
for (let i = 0; i < arr.length; i++) {
if (arr[i] >= num) {
return i;
}
}
return arr.length;
}
getIndexToIns([40, 60], 50);
```
</section>

View File

@ -0,0 +1,80 @@
---
id: 587d7b7d367417b2b2512b1d
title: ' Iterate Through the Keys of an Object with a for...in Statement'
challengeType: 1
---
## Description
<section id='description'>
Sometimes you may need to iterate through all the keys within an object. This requires a specific syntax in JavaScript called a <dfn>for...in</dfn> statement. For our <code>users</code> object, this could look like:
<blockquote>for (let user in users) {<br>&nbsp;&nbsp;console.log(user);<br>};<br><br>// logs:<br>Alan<br>Jeff<br>Sarah<br>Ryan</blockquote>
In this statement, we defined a variable <code>user</code>, and as you can see, this variable was reset during each iteration to each of the object's keys as the statement looped through the object, resulting in each user's name being printed to the console.
<strong>NOTE:</strong><br>Objects do not maintain an ordering to stored keys like arrays do; thus a keys position on an object, or the relative order in which it appears, is irrelevant when referencing or accessing that key.
</section>
## Instructions
<section id='instructions'>
We've defined a function, <code>countOnline</code>; use a <dfn>for...in</dfn> statement within this function to loop through the users in the <code>users</code> object and return the number of users whose <code>online</code> property is set to <code>true</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The <code>users</code> object contains users <code>Jeff</code> and <code>Ryan</code> with <code>online</code> set to <code>true</code> and users <code>Alan</code> and <code>Sarah</code> with <code>online</code> set to <code>false</code>
testString: 'assert(users.Alan.online === false && users.Jeff.online === true && users.Sarah.online === false && users.Ryan.online === true, ''The <code>users</code> object contains users <code>Jeff</code> and <code>Ryan</code> with <code>online</code> set to <code>true</code> and users <code>Alan</code> and <code>Sarah</code> with <code>online</code> set to <code>false</code>'');'
- text: The function <code>countOnline</code> returns the number of users with the <code>online</code> property set to <code>true</code>
testString: 'assert((function() { users.Harry = {online: true}; users.Sam = {online: true}; users.Carl = {online: true}; return countOnline(users) })() === 5, ''The function <code>countOnline</code> returns the number of users with the <code>online</code> property set to <code>true</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
let users = {
Alan: {
age: 27,
online: false
},
Jeff: {
age: 32,
online: true
},
Sarah: {
age: 48,
online: false
},
Ryan: {
age: 19,
online: true
}
};
function countOnline(obj) {
// change code below this line
// change code above this line
}
console.log(countOnline(users));
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,69 @@
---
id: 5a661e0f1068aca922b3ef17
title: Access an Array's Contents Using Bracket Notation
challengeType: 1
---
## Description
<section id='description'>
The fundamental feature of any data structure is, of course, the ability to not only store data, but to be able to retrieve that data on command. So, now that we've learned how to create an array, let's begin to think about how we can access that array's information.
When we define a simple array as seen below, there are 3 items in it:
<blockquote>let ourArray = ["a", "b", "c"];</blockquote>
In an array, each array item has an <dfn>index</dfn>. This index doubles as the position of that item in the array, and how you reference it. However, it is important to note, that JavaScript arrays are <dfn>zero-indexed</dfn>, meaning that the first element of an array is actually at the <em><strong>zeroth</strong></em> position, not the first.
In order to retrieve an element from an array we can enclose an index in brackets and append it to the end of an array, or more commonly, to a variable which references an array object. This is known as <dfn>bracket notation</dfn>.
For example, if we want to retrieve the <code>"a"</code> from <code>ourArray</code> and assign it to a variable, we can do so with the following code:
<blockquote>let ourVariable = ourArray[0];<br>// ourVariable equals "a"</blockquote>
In addition to accessing the value associated with an index, you can also <em>set</em> an index to a value using the same notation:
<blockquote>ourArray[1] = "not b anymore";<br>// ourArray now equals ["a", "not b anymore", "c"];</blockquote>
Using bracket notation, we have now reset the item at index 1 from <code>"b"</code>, to <code>"not b anymore"</code>.
</section>
## Instructions
<section id='instructions'>
In order to complete this challenge, set the 2nd position (index <code>1</code>) of <code>myArray</code> to anything you want, besides <code>"b"</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>myArray[0]</code> is equal to <code>"a"</code>'
testString: 'assert.strictEqual(myArray[0], "a", ''<code>myArray[0]</code> is equal to <code>"a"</code>'');'
- text: '<code>myArray[1]</code> is no longer set to <code>"b"</code>'
testString: 'assert.notStrictEqual(myArray[1], "b", ''<code>myArray[1]</code> is no longer set to <code>"b"</code>'');'
- text: '<code>myArray[2]</code> is equal to <code>"c"</code>'
testString: 'assert.strictEqual(myArray[2], "c", ''<code>myArray[2]</code> is equal to <code>"c"</code>'');'
- text: '<code>myArray[3]</code> is equal to <code>"d"</code>'
testString: 'assert.strictEqual(myArray[3], "d", ''<code>myArray[3]</code> is equal to <code>"d"</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
let myArray = ["a", "b", "c", "d"];
// change code below this line
//change code above this line
console.log(myArray);
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,76 @@
---
id: 587d7b7c367417b2b2512b1a
title: Access Property Names with Bracket Notation
challengeType: 1
---
## Description
<section id='description'>
In the first object challenge we mentioned the use of bracket notation as a way to access property values using the evaluation of a variable. For instance, imagine that our <code>foods</code> object is being used in a program for a supermarket cash register. We have some function that sets the <code>selectedFood</code> and we want to check our <code>foods</code> object for the presence of that food. This might look like:
<blockquote>let selectedFood = getCurrentFood(scannedItem);<br>let inventory = foods[selectedFood];</blockquote>
This code will evaluate the value stored in the <code>selectedFood</code> variable and return the value of that key in the <code>foods</code> object, or <code>undefined</code> if it is not present. Bracket notation is very useful because sometimes object properties are not known before runtime or we need to access them in a more dynamic way.
</section>
## Instructions
<section id='instructions'>
We've defined a function, <code>checkInventory</code>, which receives a scanned item as an argument. Return the current value of the <code>scannedItem</code> key in the <code>foods</code> object. You can assume that only valid keys will be provided as an argument to <code>checkInventory</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>checkInventory</code> is a function
testString: 'assert.strictEqual(typeof checkInventory, ''function'', ''<code>checkInventory</code> is a function'');'
- text: 'The <code>foods</code> object should have only the following key-value pairs: <code>apples: 25</code>, <code>oranges: 32</code>, <code>plums: 28</code>, <code>bananas: 13</code>, <code>grapes: 35</code>, <code>strawberries: 27</code>'
testString: 'assert.deepEqual(foods, {apples: 25, oranges: 32, plums: 28, bananas: 13, grapes: 35, strawberries: 27}, ''The <code>foods</code> object should have only the following key-value pairs: <code>apples: 25</code>, <code>oranges: 32</code>, <code>plums: 28</code>, <code>bananas: 13</code>, <code>grapes: 35</code>, <code>strawberries: 27</code>'');'
- text: <code>checkInventory("apples")</code> should return <code>25</code>
testString: 'assert.strictEqual(checkInventory(''apples''), 25, ''<code>checkInventory("apples")</code> should return <code>25</code>'');'
- text: <code>checkInventory("bananas")</code> should return <code>13</code>
testString: 'assert.strictEqual(checkInventory(''bananas''), 13, ''<code>checkInventory("bananas")</code> should return <code>13</code>'');'
- text: <code>checkInventory("strawberries")</code> should return <code>27</code>
testString: 'assert.strictEqual(checkInventory(''strawberries''), 27, ''<code>checkInventory("strawberries")</code> should return <code>27</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
let foods = {
apples: 25,
oranges: 32,
plums: 28,
bananas: 13,
grapes: 35,
strawberries: 27
};
// do not change code above this line
function checkInventory(scannedItem) {
// change code below this line
}
// change code below this line to test different cases:
console.log(checkInventory("apples"));
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,65 @@
---
id: 587d78b2367417b2b2512b0e
title: Add Items to an Array with push() and unshift()
challengeType: 1
---
## Description
<section id='description'>
An array's length, like the data types it can contain, is not fixed. Arrays can be defined with a length of any number of elements, and elements can be added or removed over time; in other words, arrays are <dfn>mutable</dfn>. In this challenge, we will look at two methods with which we can programmatically modify an array: <code>Array.push()</code> and <code>Array.unshift()</code>.
Both methods take one or more elements as parameters and add those elements to the array the method is being called on; the <code>push()</code> method adds elements to the end of an array, and <code>unshift()</code> adds elements to the beginning. Consider the following:
<blockquote>let twentyThree = 'XXIII';<br>let romanNumerals = ['XXI', 'XXII'];<br><br>romanNumerals.unshift('XIX', 'XX');<br>// now equals ['XIX', 'XX', 'XXI', 'XXII']<br><br>romanNumerals.push(twentyThree);<br>// now equals ['XIX', 'XX', 'XXI', 'XXII', 'XXIII']
Notice that we can also pass variables, which allows us even greater flexibility in dynamically modifying our array's data.
</section>
## Instructions
<section id='instructions'>
We have defined a function, <code>mixedNumbers</code>, which we are passing an array as an argument. Modify the function by using <code>push()</code> and <code>unshift()</code> to add <code>'I', 2, 'three'</code> to the beginning of the array and <code>7, 'VIII', 9</code> to the end so that the returned array contains representations of the numbers 1-9 in order.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>mixedNumbers(["IV", 5, "six"])</code> should now return <code>["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]</code>'
testString: 'assert.deepEqual(mixedNumbers([''IV'', 5, ''six'']), [''I'', 2, ''three'', ''IV'', 5, ''six'', 7, ''VIII'', 9], ''<code>mixedNumbers(["IV", 5, "six"])</code> should now return <code>["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]</code>'');'
- text: The <code>mixedNumbers</code> function should utilize the <code>push()</code> method
testString: 'assert.notStrictEqual(mixedNumbers.toString().search(/\.push\(/), -1, ''The <code>mixedNumbers</code> function should utilize the <code>push()</code> method'');'
- text: The <code>mixedNumbers</code> function should utilize the <code>unshift()</code> method
testString: 'assert.notStrictEqual(mixedNumbers.toString().search(/\.unshift\(/), -1, ''The <code>mixedNumbers</code> function should utilize the <code>unshift()</code> method'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function mixedNumbers(arr) {
// change code below this line
// change code above this line
return arr;
}
// do not change code below this line
console.log(mixedNumbers(['IV', 5, 'six']));
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,66 @@
---
id: 587d78b3367417b2b2512b11
title: Add Items Using splice()
challengeType: 1
---
## Description
<section id='description'>
Remember in the last challenge we mentioned that <code>splice()</code> can take up to three parameters? Well, we can go one step further with <code>splice()</code> &mdash; in addition to removing elements, we can use that third parameter, which represents one or more elements, to <em>add</em> them as well. This can be incredibly useful for quickly switching out an element, or a set of elements, for another. For instance, let's say you're storing a color scheme for a set of DOM elements in an array, and want to dynamically change a color based on some action:
<blockquote>function colorChange(arr, index, newColor) {<br>&nbsp;&nbsp;arr.splice(index, 1, newColor);<br>&nbsp;&nbsp;return arr;<br>}<br><br>let colorScheme = ['#878787', '#a08794', '#bb7e8c', '#c9b6be', '#d1becf'];<br><br>colorScheme = colorChange(colorScheme, 2, '#332327');<br>// we have removed '#bb7e8c' and added '#332327' in its place<br>// colorScheme now equals ['#878787', '#a08794', '#332327', '#c9b6be', '#d1becf']</blockquote>
This function takes an array of hex values, an index at which to remove an element, and the new color to replace the removed element with. The return value is an array containing a newly modified color scheme! While this example is a bit oversimplified, we can see the value that utilizing <code>splice()</code> to its maximum potential can have.
</section>
## Instructions
<section id='instructions'>
We have defined a function, <code>htmlColorNames</code>, which takes an array of HTML colors as an argument. Modify the function using <code>splice()</code> to remove the first two elements of the array and add <code>'DarkSalmon'</code> and <code>'BlanchedAlmond'</code> in their respective places.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>htmlColorNames</code> should return <code>["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurqoise", "FireBrick"]</code>'
testString: 'assert.deepEqual(htmlColorNames([''DarkGoldenRod'', ''WhiteSmoke'', ''LavenderBlush'', ''PaleTurqoise'', ''FireBrick'']), [''DarkSalmon'', ''BlanchedAlmond'', ''LavenderBlush'', ''PaleTurqoise'', ''FireBrick''], ''<code>htmlColorNames</code> should return <code>["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurqoise", "FireBrick"]</code>'');'
- text: The <code>htmlColorNames</code> function should utilize the <code>splice()</code> method
testString: 'assert(/.splice/.test(code), ''The <code>htmlColorNames</code> function should utilize the <code>splice()</code> method'');'
- text: You should not use <code>shift()</code> or <code>unshift()</code>.
testString: 'assert(!/shift|unshift/.test(code), ''You should not use <code>shift()</code> or <code>unshift()</code>.'');'
- text: You should not use array bracket notation.
testString: 'assert(!/\[\d\]\s*=/.test(code), ''You should not use array bracket notation.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function htmlColorNames(arr) {
// change code below this line
// change code above this line
return arr;
}
// do not change code below this line
console.log(htmlColorNames(['DarkGoldenRod', 'WhiteSmoke', 'LavenderBlush', 'PaleTurqoise', 'FireBrick']));
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,74 @@
---
id: 587d7b7c367417b2b2512b18
title: Add Key-Value Pairs to JavaScript Objects
challengeType: 1
---
## Description
<section id='description'>
At their most basic, objects are just collections of <dfn>key-value pairs</dfn>, or in other words, pieces of data mapped to unique identifiers that we call <dfn>properties</dfn> or <dfn>keys</dfn>. Let's take a look at a very simple example:
<blockquote>let FCC_User = {<br>&nbsp;&nbsp;username: 'awesome_coder',<br>&nbsp;&nbsp;followers: 572,<br>&nbsp;&nbsp;points: 1741,<br>&nbsp;&nbsp;completedProjects: 15<br>};</blockquote>
The above code defines an object called <code>FCC_User</code> that has four <dfn>properties</dfn>, each of which map to a specific value. If we wanted to know the number of <code>followers</code> <code>FCC_User</code> has, we can access that property by writing:
<blockquote>let userData = FCC_User.followers;<br>// userData equals 572</blockquote>
This is called <dfn>dot notation</dfn>. Alternatively, we can also access the property with brackets, like so:
<blockquote>let userData = FCC_User['followers']<br>// userData equals 572</blockquote>
Notice that with <dfn>bracket notation</dfn>, we enclosed <code>followers</code> in quotes. This is because the brackets actually allow us to pass a variable in to be evaluated as a property name (hint: keep this in mind for later!). Had we passed <code>followers</code> in without the quotes, the JavaScript engine would have attempted to evaluate it as a variable, and a <code>ReferenceError: followers is not defined</code> would have been thrown.
</section>
## Instructions
<section id='instructions'>
Using the same syntax, we can also <em><strong>add new</strong></em> key-value pairs to objects. We've created a <code>foods</code> object with three entries. Add three more entries: <code>bananas</code> with a value of <code>13</code>, <code>grapes</code> with a value of <code>35</code>, and <code>strawberries</code> with a value of <code>27</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>foods</code> is an object
testString: 'assert(typeof foods === ''object'', ''<code>foods</code> is an object'');'
- text: The <code>foods</code> object has a key <code>"bananas"</code> with a value of <code>13</code>
testString: 'assert(foods.bananas === 13, ''The <code>foods</code> object has a key <code>"bananas"</code> with a value of <code>13</code>'');'
- text: The <code>foods</code> object has a key <code>"grapes"</code> with a value of <code>35</code>
testString: 'assert(foods.grapes === 35, ''The <code>foods</code> object has a key <code>"grapes"</code> with a value of <code>35</code>'');'
- text: The <code>foods</code> object has a key <code>"strawberries"</code> with a value of <code>27</code>
testString: 'assert(foods.strawberries === 27, ''The <code>foods</code> object has a key <code>"strawberries"</code> with a value of <code>27</code>'');'
- text: The key-value pairs should be set using dot or bracket notation
testString: 'assert(code.search(/bananas:/) === -1 && code.search(/grapes:/) === -1 && code.search(/strawberries:/) === -1, ''The key-value pairs should be set using dot or bracket notation'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
let foods = {
apples: 25,
oranges: 32,
plums: 28
};
// change code below this line
// change code above this line
console.log(foods);
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,67 @@
---
id: 587d7b7b367417b2b2512b14
title: Check For The Presence of an Element With indexOf()
challengeType: 1
---
## Description
<section id='description'>
Since arrays can be changed, or <em>mutated</em>, at any time, there's no guarantee about where a particular piece of data will be on a given array, or if that element even still exists. Luckily, JavaScript provides us with another built-in method, <code>indexOf()</code>, that allows us to quickly and easily check for the presence of an element on an array. <code>indexOf()</code> takes an element as a parameter, and when called, it returns the position, or index, of that element, or <code>-1</code> if the element does not exist on the array.
For example:
<blockquote>let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears'];<br><br>fruits.indexOf('dates') // returns -1<br>fruits.indexOf('oranges') // returns 2<br>fruits.indexOf('pears') // returns 1, the first index at which the element exists</blockquote>
</section>
## Instructions
<section id='instructions'>
<code>indexOf()</code> can be incredibly useful for quickly checking for the presence of an element on an array. We have defined a function, <code>quickCheck</code>, that takes an array and an element as arguments. Modify the function using <code>indexOf()</code> so that it returns <code>true</code> if the passed element exists on the array, and <code>false</code> if it does not.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>quickCheck(["squash", "onions", "shallots"], "mushrooms")</code> should return <code>false</code>'
testString: 'assert.strictEqual(quickCheck([''squash'', ''onions'', ''shallots''], ''mushrooms''), false, ''<code>quickCheck(["squash", "onions", "shallots"], "mushrooms")</code> should return <code>false</code>'');'
- text: '<code>quickCheck(["squash", "onions", "shallots"], "onions")</code> should return <code>true</code>'
testString: 'assert.strictEqual(quickCheck([''squash'', ''onions'', ''shallots''], ''onions''), true, ''<code>quickCheck(["squash", "onions", "shallots"], "onions")</code> should return <code>true</code>'');'
- text: '<code>quickCheck([3, 5, 9, 125, 45, 2], 125)</code> should return <code>true</code>'
testString: 'assert.strictEqual(quickCheck([3, 5, 9, 125, 45, 2], 125), true, ''<code>quickCheck([3, 5, 9, 125, 45, 2], 125)</code> should return <code>true</code>'');'
- text: '<code>quickCheck([true, false, false], undefined)</code> should return <code>false</code>'
testString: 'assert.strictEqual(quickCheck([true, false, false], undefined), false, ''<code>quickCheck([true, false, false], undefined)</code> should return <code>false</code>'');'
- text: The <code>quickCheck</code> function should utilize the <code>indexOf()</code> method
testString: 'assert.notStrictEqual(quickCheck.toString().search(/\.indexOf\(/), -1, ''The <code>quickCheck</code> function should utilize the <code>indexOf()</code> method'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function quickCheck(arr, elem) {
// change code below this line
// change code above this line
}
// change code here to test different cases:
console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,80 @@
---
id: 587d7b7d367417b2b2512b1c
title: Check if an Object has a Property
challengeType: 1
---
## Description
<section id='description'>
Now we can add, modify, and remove keys from objects. But what if we just wanted to know if an object has a specific property? JavaScript provides us with two different ways to do this. One uses the <code>hasOwnProperty()</code> method and the other uses the <code>in</code> keyword. If we have an object <code>users</code> with a property of <code>Alan</code>, we could check for its presence in either of the following ways:
<blockquote>users.hasOwnProperty('Alan');<br>'Alan' in users;<br>// both return true</blockquote>
</section>
## Instructions
<section id='instructions'>
We've created an object, <code>users</code>, with some users in it and a function <code>isEveryoneHere</code>, which we pass the <code>users</code> object to as an argument. Finish writing this function so that it returns <code>true</code> only if the <code>users</code> object contains all four names, <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code>, as keys, and <code>false</code> otherwise.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 'The <code>users</code> object only contains the keys <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code>'
testString: 'assert(''Alan'' in users && ''Jeff'' in users && ''Sarah'' in users && ''Ryan'' in users && Object.keys(users).length === 4, ''The <code>users</code> object only contains the keys <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code>'');'
- text: 'The function <code>isEveryoneHere</code> returns <code>true</code> if <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code> are properties on the <code>users</code> object'
testString: 'assert(isEveryoneHere(users) === true, ''The function <code>isEveryoneHere</code> returns <code>true</code> if <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code> are properties on the <code>users</code> object'');'
- text: 'The function <code>isEveryoneHere</code> returns <code>false</code> if <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code> are not properties on the <code>users</code> object'
testString: 'assert((function() { delete users.Alan; delete users.Jeff; delete users.Sarah; delete users.Ryan; return isEveryoneHere(users) })() === false, ''The function <code>isEveryoneHere</code> returns <code>false</code> if <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code> are not properties on the <code>users</code> object'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
let users = {
Alan: {
age: 27,
online: true
},
Jeff: {
age: 32,
online: true
},
Sarah: {
age: 48,
online: true
},
Ryan: {
age: 19,
online: true
}
};
function isEveryoneHere(obj) {
// change code below this line
// change code above this line
}
console.log(isEveryoneHere(users));
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,61 @@
---
id: 587d7b7b367417b2b2512b17
title: Combine Arrays with the Spread Operator
challengeType: 1
---
## Description
<section id='description'>
Another huge advantage of the <dfn>spread</dfn> operator, is the ability to combine arrays, or to insert all the elements of one array into another, at any index. With more traditional syntaxes, we can concatenate arrays, but this only allows us to combine arrays at the end of one, and at the start of another. Spread syntax makes the following operation extremely simple:
<blockquote>let thisArray = ['sage', 'rosemary', 'parsley', 'thyme'];<br><br>let thatArray = ['basil', 'cilantro', ...thisArray, 'coriander'];<br>// thatArray now equals ['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']</blockquote>
Using spread syntax, we have just achieved an operation that would have been more complex and more verbose had we used traditional methods.
</section>
## Instructions
<section id='instructions'>
We have defined a function <code>spreadOut</code> that returns the variable <code>sentence</code>, modify the function using the <dfn>spread</dfn> operator so that it returns the array <code>['learning', 'to', 'code', 'is', 'fun']</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>spreadOut</code> should return <code>["learning", "to", "code", "is", "fun"]</code>'
testString: 'assert.deepEqual(spreadOut(), [''learning'', ''to'', ''code'', ''is'', ''fun''], ''<code>spreadOut</code> should return <code>["learning", "to", "code", "is", "fun"]</code>'');'
- text: The <code>spreadOut</code> function should utilize spread syntax
testString: 'assert.notStrictEqual(spreadOut.toString().search(/[...]/), -1, ''The <code>spreadOut</code> function should utilize spread syntax'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function spreadOut() {
let fragment = ['to', 'code'];
let sentence; // change this line
return sentence;
}
// do not change code below this line
console.log(spreadOut());
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,72 @@
---
id: 587d7b7b367417b2b2512b13
title: Copy an Array with the Spread Operator
challengeType: 1
---
## Description
<section id='description'>
While <code>slice()</code> allows us to be selective about what elements of an array to copy, among several other useful tasks, ES6's new <dfn>spread operator</dfn> allows us to easily copy <em>all</em> of an array's elements, in order, with a simple and highly readable syntax. The spread syntax simply looks like this: <code>...</code>
In practice, we can use the spread operator to copy an array like so:
<blockquote>let thisArray = [true, true, undefined, false, null];<br>let thatArray = [...thisArray];<br>// thatArray equals [true, true, undefined, false, null]<br>// thisArray remains unchanged, and is identical to thatArray</blockquote>
</section>
## Instructions
<section id='instructions'>
We have defined a function, <code>copyMachine</code> which takes <code>arr</code> (an array) and <code>num</code> (a number) as arguments. The function is supposed to return a new array made up of <code>num</code> copies of <code>arr</code>. We have done most of the work for you, but it doesn't work quite right yet. Modify the function using spread syntax so that it works correctly (hint: another method we have already covered might come in handy here!).
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>copyMachine([true, false, true], 2)</code> should return <code>[[true, false, true], [true, false, true]]</code>'
testString: 'assert.deepEqual(copyMachine([true, false, true], 2), [[true, false, true], [true, false, true]], ''<code>copyMachine([true, false, true], 2)</code> should return <code>[[true, false, true], [true, false, true]]</code>'');'
- text: '<code>copyMachine([1, 2, 3], 5)</code> should return <code>[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]</code>'
testString: 'assert.deepEqual(copyMachine([1, 2, 3], 5), [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]], ''<code>copyMachine([1, 2, 3], 5)</code> should return <code>[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]</code>'');'
- text: '<code>copyMachine([true, true, null], 1)</code> should return <code>[[true, true, null]]</code>'
testString: 'assert.deepEqual(copyMachine([true, true, null], 1), [[true, true, null]], ''<code>copyMachine([true, true, null], 1)</code> should return <code>[[true, true, null]]</code>'');'
- text: '<code>copyMachine(["it works"], 3)</code> should return <code>[["it works"], ["it works"], ["it works"]]</code>'
testString: 'assert.deepEqual(copyMachine([''it works''], 3), [[''it works''], [''it works''], [''it works'']], ''<code>copyMachine(["it works"], 3)</code> should return <code>[["it works"], ["it works"], ["it works"]]</code>'');'
- text: The <code>copyMachine</code> function should utilize the <code>spread operator</code> with array <code>arr</code>
testString: 'assert.notStrictEqual(copyMachine.toString().indexOf(''.concat(_toConsumableArray(arr))''), -1, ''The <code>copyMachine</code> function should utilize the <code>spread operator</code> with array <code>arr</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function copyMachine(arr, num) {
let newArr = [];
while (num >= 1) {
// change code below this line
// change code above this line
num--;
}
return newArr;
}
// change code here to test different cases:
console.log(copyMachine([true, false, true], 2));
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,61 @@
---
id: 587d7b7a367417b2b2512b12
title: Copy Array Items Using slice()
challengeType: 1
---
## Description
<section id='description'>
The next method we will cover is <code>slice()</code>. <code>slice()</code>, rather than modifying an array, copies, or <em>extracts</em>, a given number of elements to a new array, leaving the array it is called upon untouched. <code>slice()</code> takes only 2 parameters &mdash; the first is the index at which to begin extraction, and the second is the index at which to stop extraction (extraction will occur up to, but not including the element at this index). Consider this:
<blockquote>let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];<br><br>let todaysWeather = weatherConditions.slice(1, 3);<br>// todaysWeather equals ['snow', 'sleet'];<br>// weatherConditions still equals ['rain', 'snow', 'sleet', 'hail', 'clear']<br></blockquote>
In effect, we have created a new array by extracting elements from an existing array.
</section>
## Instructions
<section id='instructions'>
We have defined a function, <code>forecast</code>, that takes an array as an argument. Modify the function using <code>slice()</code> to extract information from the argument array and return a new array that contains the elements <code>'warm'</code> and <code>'sunny'</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>forecast</code> should return <code>["warm", "sunny"]'
testString: 'assert.deepEqual(forecast([''cold'', ''rainy'', ''warm'', ''sunny'', ''cool'', ''thunderstorms'']), [''warm'', ''sunny''], ''<code>forecast</code> should return <code>["warm", "sunny"]'');'
- text: The <code>forecast</code> function should utilize the <code>slice()</code> method
testString: 'assert(/\.slice\(/.test(code), ''The <code>forecast</code> function should utilize the <code>slice()</code> method'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function forecast(arr) {
// change code below this line
return arr;
}
// do not change code below this line
console.log(forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']));
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,73 @@
---
id: 587d7b7b367417b2b2512b16
title: Create complex multi-dimensional arrays
challengeType: 1
---
## Description
<section id='description'>
Awesome! You have just learned a ton about arrays! This has been a fairly high level overview, and there is plenty more to learn about working with arrays, much of which you will see in later sections. But before moving on to looking at <dfn>Objects</dfn>, lets take one more look, and see how arrays can become a bit more complex than what we have seen in previous challenges.
One of the most powerful features when thinking of arrays as data structures, is that arrays can contain, or even be completely made up of other arrays. We have seen arrays that contain arrays in previous challenges, but fairly simple ones. However, arrays can contain an infinite depth of arrays that can contain other arrays, each with their own arbitrary levels of depth, and so on. In this way, an array can very quickly become very complex data structure, known as a <dfn>multi-dimensional</dfn>, or nested array. Consider the following example:
<blockquote>let nestedArray = [ // top, or first level - the outer most array<br>&nbsp;&nbsp;['deep'], // an array within an array, 2 levels of depth<br>&nbsp;&nbsp;[<br>&nbsp;&nbsp;&nbsp;&nbsp;['deeper'], ['deeper'] // 2 arrays nested 3 levels deep<br>&nbsp;&nbsp;],<br>&nbsp;&nbsp;[<br>&nbsp;&nbsp;&nbsp;&nbsp;[<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;['deepest'], ['deepest'] // 2 arrays nested 4 levels deep<br>&nbsp;&nbsp;&nbsp;&nbsp;],<br>&nbsp;&nbsp;&nbsp;&nbsp;[<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;['deepest-est?'] // an array nested 5 levels deep<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;]<br>&nbsp;&nbsp;&nbsp;&nbsp;]<br>&nbsp;&nbsp;]<br>];</blockquote>
While this example may seem convoluted, this level of complexity is not unheard of, or even unusual, when dealing with large amounts of data.
However, we can still very easily access the deepest levels of an array this complex with bracket notation:
<blockquote>console.log(nestedArray[2][1][0][0][0]);<br>// logs: deepest-est?</blockquote>
And now that we know where that piece of data is, we can reset it if we need to:
<blockquote>nestedArray[2][1][0][0][0] = 'deeper still';<br><br>console.log(nestedArray[2][1][0][0][0]);<br>// now logs: deeper still</blockquote>
</section>
## Instructions
<section id='instructions'>
We have defined a variable, <code>myNestedArray</code>, set equal to an array. Modify <code>myNestedArray</code>, using any combination of <dfn>strings</dfn>, <dfn>numbers</dfn>, and <dfn>booleans</dfn> for data elements, so that it has exactly five levels of depth (remember, the outer-most array is level 1). Somewhere on the third level, include the string <code>'deep'</code>, on the fourth level, include the string <code>'deeper'</code>, and on the fifth level, include the string <code>'deepest'</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>myNestedArray</code> should contain only numbers, booleans, and strings as data elements'
testString: 'assert.strictEqual((function(arr) { let flattened = (function flatten(arr) { const flat = [].concat(...arr); return flat.some (Array.isArray) ? flatten(flat) : flat; })(arr); for (let i = 0; i < flattened.length; i++) { if ( typeof flattened[i] !== ''number'' && typeof flattened[i] !== ''string'' && typeof flattened[i] !== ''boolean'') { return false } } return true })(myNestedArray), true, ''<code>myNestedArray</code> should contain only numbers, booleans, and strings as data elements'');'
- text: <code>myNestedArray</code> should have exactly 5 levels of depth
testString: 'assert.strictEqual((function(arr) {let depth = 0;function arrayDepth(array, i, d) { if (Array.isArray(array[i])) { arrayDepth(array[i], 0, d + 1);} else { depth = (d > depth) ? d : depth;}if (i < array.length) { arrayDepth(array, i + 1, d);} }arrayDepth(arr, 0, 0);return depth;})(myNestedArray), 4, ''<code>myNestedArray</code> should have exactly 5 levels of depth'');'
- text: <code>myNestedArray</code> should contain exactly one occurrence of the string <code>"deep"</code> on an array nested 3 levels deep
testString: 'assert((function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, ''deep'').length === 1 && (function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, ''deep'')[0] === 2, ''<code>myNestedArray</code> should contain exactly one occurrence of the string <code>"deep"</code> on an array nested 3 levels deep'');'
- text: <code>myNestedArray</code> should contain exactly one occurrence of the string <code>"deeper"</code> on an array nested 4 levels deep
testString: 'assert((function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, ''deeper'').length === 1 && (function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, ''deeper'')[0] === 3, ''<code>myNestedArray</code> should contain exactly one occurrence of the string <code>"deeper"</code> on an array nested 4 levels deep'');'
- text: <code>myNestedArray</code> should contain exactly one occurrence of the string <code>"deepest"</code> on an array nested 5 levels deep
testString: 'assert((function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, ''deepest'').length === 1 && (function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, ''deepest'')[0] === 4, ''<code>myNestedArray</code> should contain exactly one occurrence of the string <code>"deepest"</code> on an array nested 5 levels deep'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
let myNestedArray = [
// change code below this line
['unshift', false, 1, 2, 3, 'complex', 'nested'],
['loop', 'shift', 6, 7, 1000, 'method'],
['concat', false, true, 'spread', 'array'],
['mutate', 1327.98, 'splice', 'slice', 'push'],
['iterate', 1.3849, 7, '8.4876', 'arbitrary', 'depth']
// change code above this line
];
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,77 @@
---
id: 587d7b7d367417b2b2512b1e
title: Generate an Array of All Object Keys with Object.keys()
challengeType: 1
---
## Description
<section id='description'>
We can also generate an array which contains all the keys stored in an object using the <code>Object.keys()</code> method and passing in an object as the argument. This will return an array with strings representing each property in the object. Again, there will be no specific order to the entries in the array.
</section>
## Instructions
<section id='instructions'>
Finish writing the <code>getArrayOfUsers</code> function so that it returns an array containing all the properties in the object it receives as an argument.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 'The <code>users</code> object only contains the keys <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code>'
testString: 'assert(''Alan'' in users && ''Jeff'' in users && ''Sarah'' in users && ''Ryan'' in users && Object.keys(users).length === 4, ''The <code>users</code> object only contains the keys <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code>'');'
- text: The <code>getArrayOfUsers</code> function returns an array which contains all the keys in the <code>users</code> object
testString: 'assert((function() { users.Sam = {}; users.Lewis = {}; let R = getArrayOfUsers(users); return (R.indexOf(''Alan'') !== -1 && R.indexOf(''Jeff'') !== -1 && R.indexOf(''Sarah'') !== -1 && R.indexOf(''Ryan'') !== -1 && R.indexOf(''Sam'') !== -1 && R.indexOf(''Lewis'') !== -1); })() === true, ''The <code>getArrayOfUsers</code> function returns an array which contains all the keys in the <code>users</code> object'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
let users = {
Alan: {
age: 27,
online: false
},
Jeff: {
age: 32,
online: true
},
Sarah: {
age: 48,
online: false
},
Ryan: {
age: 19,
online: true
}
};
function getArrayOfUsers(obj) {
// change code below this line
// change code above this line
}
console.log(getArrayOfUsers(users));
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,70 @@
---
id: 587d7b7b367417b2b2512b15
title: Iterate Through All an Array's Items Using For Loops
challengeType: 1
---
## Description
<section id='description'>
Sometimes when working with arrays, it is very handy to be able to iterate through each item to find one or more elements that we might need, or to manipulate an array based on which data items meet a certain set of criteria. JavaScript offers several built in methods that each iterate over arrays in slightly different ways to achieve different results (such as <code>every()</code>, <code>forEach()</code>, <code>map()</code>, etc.), however the technique which is most flexible and offers us the greatest amount of control is a simple <code>for</code> loop.
Consider the following:
<blockquote>function greaterThanTen(arr) {<br>&nbsp;&nbsp;let newArr = [];<br>&nbsp;&nbsp;for (let i = 0; i < arr.length; i++) {<br>&nbsp;&nbsp;&nbsp;&nbsp;if (arr[i] > 10) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;newArr.push(arr[i]);<br>&nbsp;&nbsp;&nbsp;&nbsp;}<br>&nbsp;&nbsp;}<br>&nbsp;&nbsp;return newArr;<br>}<br><br>greaterThanTen([2, 12, 8, 14, 80, 0, 1]);<br>// returns [12, 14, 80]</blockquote>
Using a <code>for</code> loop, this function iterates through and accesses each element of the array, and subjects it to a simple test that we have created. In this way, we have easily and programmatically determined which data items are greater than <code>10</code>, and returned a new array containing those items.
</section>
## Instructions
<section id='instructions'>
We have defined a function, <code>filteredArray</code>, which takes <code>arr</code>, a nested array, and <code>elem</code> as arguments, and returns a new array. <code>elem</code> represents an element that may or may not be present on one or more of the arrays nested within <code>arr</code>. Modify the function, using a <code>for</code> loop, to return a filtered version of the passed array such that any array nested within <code>arr</code> containing <code>elem</code> has been removed.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)</code> should return <code>[ [10, 8, 3], [14, 6, 23] ]</code>'
testString: 'assert.deepEqual(filteredArray([ [10, 8, 3], [14, 6, 23], [3, 18, 6] ], 18), [[10, 8, 3], [14, 6, 23]], ''<code>filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)</code> should return <code>[ [10, 8, 3], [14, 6, 23] ]</code>'');'
- text: '<code>filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2)</code> should return <code>[ ["flutes", 4] ]</code>'
testString: 'assert.deepEqual(filteredArray([ [''trumpets'', 2], [''flutes'', 4], [''saxophones'', 2] ], 2), [[''flutes'', 4]], ''<code>filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2)</code> should return <code>[ ["flutes", 4] ]</code>'');'
- text: '<code>filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter")</code> should return <code>[ ["amy", "beth", "sam"] ]</code>'
testString: 'assert.deepEqual(filteredArray([[''amy'', ''beth'', ''sam''], [''dave'', ''sean'', ''peter'']], ''peter''), [[''amy'', ''beth'', ''sam'']], ''<code>filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter")</code> should return <code>[ ["amy", "beth", "sam"] ]</code>'');'
- text: '<code>filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)</code> should return <code>[ ]</code>'
testString: 'assert.deepEqual(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3), [], ''<code>filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)</code> should return <code>[ ]</code>'');'
- text: The <code>filteredArray</code> function should utilize a <code>for</code> loop
testString: 'assert.notStrictEqual(filteredArray.toString().search(/for/), -1, ''The <code>filteredArray</code> function should utilize a <code>for</code> loop'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function filteredArray(arr, elem) {
let newArr = [];
// change code below this line
// change code above this line
return newArr;
}
// change code here to test different cases:
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,94 @@
{
"name": "Basic Data Structures",
"dashedName": "basic-data-structures",
"order": 5,
"time": "1 hour",
"template": "",
"required": [],
"superBlock": "javascript-algorithms-and-data-structures",
"superOrder": 2,
"challengeOrder": [
[
"587d7b7e367417b2b2512b20",
"Use an Array to Store a Collection of Data"
],
[
"5a661e0f1068aca922b3ef17",
"Access an Array's Contents Using Bracket Notation"
],
[
"587d78b2367417b2b2512b0e",
"Add Items to an Array with push() and unshift()"
],
[
"587d78b2367417b2b2512b0f",
"Remove Items from an Array with pop() and shift()"
],
[
"587d78b2367417b2b2512b10",
"Remove Items Using splice()"
],
[
"587d78b3367417b2b2512b11",
"Add Items Using splice()"
],
[
"587d7b7a367417b2b2512b12",
"Copy Array Items Using slice()"
],
[
"587d7b7b367417b2b2512b13",
"Copy an Array with the Spread Operator"
],
[
"587d7b7b367417b2b2512b17",
"Combine Arrays with the Spread Operator"
],
[
"587d7b7b367417b2b2512b14",
"Check For The Presence of an Element With indexOf()"
],
[
"587d7b7b367417b2b2512b15",
"Iterate Through All an Array's Items Using For Loops"
],
[
"587d7b7b367417b2b2512b16",
"Create complex multi-dimensional arrays"
],
[
"587d7b7c367417b2b2512b18",
"Add Key-Value Pairs to JavaScript Objects"
],
[
"587d7b7c367417b2b2512b19",
"Modify an Object Nested Within an Object"
],
[
"587d7b7c367417b2b2512b1a",
"Access Property Names with Bracket Notation"
],
[
"587d7b7c367417b2b2512b1b",
"Use the delete Keyword to Remove Object Properties"
],
[
"587d7b7d367417b2b2512b1c",
"Check if an Object has a Property"
],
[
"587d7b7d367417b2b2512b1d",
" Iterate Through the Keys of an Object with a for...in Statement"
],
[
"587d7b7d367417b2b2512b1e",
"Generate an Array of All Object Keys with Object.keys()"
],
[
"587d7b7d367417b2b2512b1f",
"Modify an Array Stored in an Object"
]
],
"helpRoom": "Help",
"fileName": "02-javascript-algorithms-and-data-structures/basic-data-structures.json"
}

View File

@ -0,0 +1,80 @@
---
id: 587d7b7d367417b2b2512b1f
title: Modify an Array Stored in an Object
challengeType: 1
---
## Description
<section id='description'>
Now you've seen all the basic operations for JavaScript objects. You can add, modify, and remove key-value pairs, check if keys exist, and iterate over all the keys in an object. As you continue learning JavaScript you will see even more versatile applications of objects. Additionally, the optional Advanced Data Structures lessons later in the curriculum also cover the ES6 <dfn>Map</dfn> and <dfn>Set</dfn> objects, both of which are similar to ordinary objects but provide some additional features. Now that you've learned the basics of arrays and objects, you're fully prepared to begin tackling more complex problems using JavaScript!
</section>
## Instructions
<section id='instructions'>
Take a look at the object we've provided in the code editor. The <code>user</code> object contains three keys. The <code>data</code> key contains five keys, one of which contains an array of <code>friends</code>. From this, you can see how flexible objects are as data structures. We've started writing a function <code>addFriend</code>. Finish writing it so that it takes a <code>user</code> object and adds the name of the <code>friend</code> argument to the array stored in <code>user.data.friends</code> and returns that array.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 'The <code>user</code> object has <code>name</code>, <code>age</code>, and <code>data</code> keys'
testString: 'assert(''name'' in user && ''age'' in user && ''data'' in user, ''The <code>user</code> object has <code>name</code>, <code>age</code>, and <code>data</code> keys'');'
- text: The <code>addFriend</code> function accepts a <code>user</code> object and a <code>friend</code> string as arguments and adds the friend to the array of <code>friends</code> in the <code>user</code> object
testString: 'assert((function() { let L1 = user.data.friends.length; addFriend(user, ''Sean''); let L2 = user.data.friends.length; return (L2 === L1 + 1); })(), ''The <code>addFriend</code> function accepts a <code>user</code> object and a <code>friend</code> string as arguments and adds the friend to the array of <code>friends</code> in the <code>user</code> object'');'
- text: '<code>addFriend(user, "Pete")</code> should return <code>["Sam", "Kira", "Tomo", "Pete"]</code>'
testString: 'assert.deepEqual((function() { delete user.data.friends; user.data.friends = [''Sam'', ''Kira'', ''Tomo'']; return addFriend(user, ''Pete'') })(), [''Sam'', ''Kira'', ''Tomo'', ''Pete''], ''<code>addFriend(user, "Pete")</code> should return <code>["Sam", "Kira", "Tomo", "Pete"]</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
let user = {
name: 'Kenneth',
age: 28,
data: {
username: 'kennethCodesAllDay',
joinDate: 'March 26, 2016',
organization: 'freeCodeCamp',
friends: [
'Sam',
'Kira',
'Tomo'
],
location: {
city: 'San Francisco',
state: 'CA',
country: 'USA'
}
}
};
function addFriend(userObj, friend) {
// change code below this line
// change code above this line
}
console.log(addFriend(user, 'Pete'));
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,71 @@
---
id: 587d7b7c367417b2b2512b19
title: Modify an Object Nested Within an Object
challengeType: 1
---
## Description
<section id='description'>
Now let's take a look at a slightly more complex object. Object properties can be nested to an arbitrary depth, and their values can be any type of data supported by JavaScript, including arrays and even other objects. Consider the following:
<blockquote>let nestedObject = {<br>&nbsp;&nbsp;id: 28802695164,<br>&nbsp;&nbsp;date: 'December 31, 2016',<br>&nbsp;&nbsp;data: {<br>&nbsp;&nbsp;&nbsp;&nbsp;totalUsers: 99,<br>&nbsp;&nbsp;&nbsp;&nbsp;online: 80,<br>&nbsp;&nbsp;&nbsp;&nbsp;onlineStatus: {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;active: 67,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;away: 13<br>&nbsp;&nbsp;&nbsp;&nbsp;}<br>&nbsp;&nbsp;}<br>};</blockquote>
<code>nestedObject</code> has three unique keys: <code>id</code>, whose value is a number, <code>date</code> whose value is a string, and <code>data</code>, whose value is an object which has yet another object nested within it. While structures can quickly become complex, we can still use the same notations to access the information we need.
</section>
## Instructions
<section id='instructions'>
Here we've defined an object, <code>userActivity</code>, which includes another object nested within it. You can modify properties on this nested object in the same way you modified properties in the last challenge. Set the value of the <code>online</code> key to <code>45</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>userActivity</code> has <code>id</code>, <code>date</code> and <code>data</code> properties'
testString: 'assert(''id'' in userActivity && ''date'' in userActivity && ''data'' in userActivity, ''<code>userActivity</code> has <code>id</code>, <code>date</code> and <code>data</code> properties'');'
- text: <code>userActivity</code> has a <code>data</code> key set to an object with keys <code>totalUsers</code> and <code>online</code>
testString: 'assert(''totalUsers'' in userActivity.data && ''online'' in userActivity.data, ''<code>userActivity</code> has a <code>data</code> key set to an object with keys <code>totalUsers</code> and <code>online</code>'');'
- text: The <code>online</code> property nested in the <code>data</code> key of <code>userActivity</code> should be set to <code>45</code>
testString: 'assert(userActivity.data.online === 45, ''The <code>online</code> property nested in the <code>data</code> key of <code>userActivity</code> should be set to <code>45</code>'');'
- text: The <code>online</code> property is set using dot or bracket notation
testString: 'assert.strictEqual(code.search(/online: 45/), -1, ''The <code>online</code> property is set using dot or bracket notation'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
let userActivity = {
id: 23894201352,
date: 'January 1, 2017',
data: {
totalUsers: 51,
online: 42
}
};
// change code below this line
// change code above this line
console.log(userActivity);
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,65 @@
---
id: 587d78b2367417b2b2512b0f
title: Remove Items from an Array with pop() and shift()
challengeType: 1
---
## Description
<section id='description'>
Both <code>push()</code> and <code>unshift()</code> have corresponding methods that are nearly functional opposites: <code>pop()</code> and <code>shift()</code>. As you may have guessed by now, instead of adding, <code>pop()</code> <em>removes</em> an element from the end of an array, while <code>shift()</code> removes an element from the beginning. The key difference between <code>pop()</code> and <code>shift()</code> and their cousins <code>push()</code> and <code>unshift()</code>, is that neither method takes parameters, and each only allows an array to be modified by a single element at a time.
Let's take a look:
<blockquote>let greetings = ['whats up?', 'hello', 'see ya!'];<br><br>greetings.pop();<br>// now equals ['whats up?', 'hello']<br><br>greetings.shift();<br>// now equals ['hello']</blockquote>
We can also return the value of the removed element with either method like this:
<blockquote>let popped = greetings.pop();<br>// returns 'hello'<br>// greetings now equals []</blockquote>
</section>
## Instructions
<section id='instructions'>
We have defined a function, <code>popShift</code>, which takes an array as an argument and returns a new array. Modify the function, using <code>pop()</code> and <code>shift()</code>, to remove the first and last elements of the argument array, and assign the removed elements to their corresponding variables, so that the returned array contains their values.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>popShift(["challenge", "is", "not", "complete"])</code> should return <code>["challenge", "complete"]</code>'
testString: 'assert.deepEqual(popShift([''challenge'', ''is'', ''not'', ''complete'']), ["challenge", "complete"], ''<code>popShift(["challenge", "is", "not", "complete"])</code> should return <code>["challenge", "complete"]</code>'');'
- text: The <code>popShift</code> function should utilize the <code>pop()</code> method
testString: 'assert.notStrictEqual(popShift.toString().search(/\.pop\(/), -1, ''The <code>popShift</code> function should utilize the <code>pop()</code> method'');'
- text: The <code>popShift</code> function should utilize the <code>shift()</code> method
testString: 'assert.notStrictEqual(popShift.toString().search(/\.shift\(/), -1, ''The <code>popShift</code> function should utilize the <code>shift()</code> method'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function popShift(arr) {
let popped; // change this line
let shifted; // change this line
return [shifted, popped];
}
// do not change code below this line
console.log(popShift(['challenge', 'is', 'not', 'complete']));
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,64 @@
---
id: 587d78b2367417b2b2512b10
title: Remove Items Using splice()
challengeType: 1
---
## Description
<section id='description'>
Ok, so we've learned how to remove elements from the beginning and end of arrays using <code>shift()</code> and <code>pop()</code>, but what if we want to remove an element from somewhere in the middle? Or remove more than one element at once? Well, that's where <code>splice()</code> comes in. <code>splice()</code> allows us to do just that: <strong>remove any number of consecutive elements</strong> from anywhere in an array.
<code>splice()</code> can take up to 3 parameters, but for now, we'll focus on just the first 2. The first two parameters of <code>splice()</code> are integers which represent indexes, or positions, of the array that <code>splice()</code> is being called upon. And remember, arrays are <em>zero-indexed</em>, so to indicate the first element of an array, we would use <code>0</code>. <code>splice()</code>'s first parameter represents the index on the array from which to begin removing elements, while the second parameter indicates the number of elements to delete. For example:
<blockquote>let array = ['today', 'was', 'not', 'so', 'great'];<br><br>array.splice(2, 2);<br>// remove 2 elements beginning with the 3rd element<br>// array now equals ['today', 'was', 'great']</blockquote>
<code>splice()</code> not only modifies the array it's being called on, but it also returns a new array containing the value of the removed elements:
<blockquote>let array = ['I', 'am', 'feeling', 'really', 'happy'];<br><br>let newArray = array.splice(3, 2);<br>// newArray equals ['really', 'happy']</blockquote>
</section>
## Instructions
<section id='instructions'>
We've defined a function, <code>sumOfTen</code>, which takes an array as an argument and returns the sum of that array's elements. Modify the function, using <code>splice()</code>, so that it returns a value of <code>10</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>sumOfTen</code> should return 10
testString: 'assert.strictEqual(sumOfTen([2, 5, 1, 5, 2, 1]), 10, ''<code>sumOfTen</code> should return 10'');'
- text: The <code>sumOfTen</code> function should utilize the <code>splice()</code> method
testString: 'assert.notStrictEqual(sumOfTen.toString().search(/\.splice\(/), -1, ''The <code>sumOfTen</code> function should utilize the <code>splice()</code> method'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function sumOfTen(arr) {
// change code below this line
// change code above this line
return arr.reduce((a, b) => a + b);
}
// do not change code below this line
console.log(sumOfTen([2, 5, 1, 5, 2, 1]));
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,62 @@
---
id: 587d7b7e367417b2b2512b20
title: Use an Array to Store a Collection of Data
challengeType: 1
---
## Description
<section id='description'>
The below is an example of the simplest implementation of an array data structure. This is known as a <dfn>one-dimensional array</dfn>, meaning it only has one level, or that it does not have any other arrays nested within it. Notice it contains <dfn>booleans</dfn>, <dfn>strings</dfn>, and <dfn>numbers</dfn>, among other valid JavaScript data types:
<blockquote>let simpleArray = ['one', 2, 'three, true, false, undefined, null];<br>console.log(simpleArray.length);<br>// logs 7</blockquote>
All array's have a length property, which as shown above, can be very easily accessed with the syntax <code>Array.length</code>.
A more complex implementation of an array can be seen below. This is known as a <dfn>multi-dimensional array</dfn>, or an array that contains other arrays. Notice that this array also contains JavaScript <dfn>objects</dfn>, which we will examine very closely in our next section, but for now, all you need to know is that arrays are also capable of storing complex objects.
<blockquote>let complexArray = [<br>&nbsp;&nbsp;[<br>&nbsp;&nbsp;&nbsp;&nbsp;{<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;one: 1,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;two: 2<br>&nbsp;&nbsp;&nbsp;&nbsp;},<br>&nbsp;&nbsp;&nbsp;&nbsp;{<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;three: 3,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;four: 4<br>&nbsp;&nbsp;&nbsp;&nbsp;}<br>&nbsp;&nbsp;],<br>&nbsp;&nbsp;[<br>&nbsp;&nbsp;&nbsp;&nbsp;{<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;a: "a",<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;b: "b"<br>&nbsp;&nbsp;&nbsp;&nbsp;},<br>&nbsp;&nbsp;&nbsp;&nbsp;{<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;c: "c",<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;d: “d”<br>&nbsp;&nbsp;&nbsp;&nbsp;}<br>&nbsp;&nbsp;]<br>];</blockquote>
</section>
## Instructions
<section id='instructions'>
We have defined a variable called <code>yourArray</code>. Complete the statement by assigning an array of at least 5 elements in length to the <code>yourArray</code> variable. Your array should contain at least one <dfn>string</dfn>, one <dfn>number</dfn>, and one <dfn>boolean</dfn>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: yourArray is an array
testString: 'assert.strictEqual(Array.isArray(yourArray), true, ''yourArray is an array'');'
- text: <code>yourArray</code> is at least 5 elements long
testString: 'assert.isAtLeast(yourArray.length, 5, ''<code>yourArray</code> is at least 5 elements long'');'
- text: <code>yourArray</code> contains at least one <code>boolean</code>
testString: 'assert(yourArray.filter( el => typeof el === ''boolean'').length >= 1, ''<code>yourArray</code> contains at least one <code>boolean</code>'');'
- text: <code>yourArray</code> contains at least one <code>number</code>
testString: 'assert(yourArray.filter( el => typeof el === ''number'').length >= 1, ''<code>yourArray</code> contains at least one <code>number</code>'');'
- text: <code>yourArray</code> contains at least one <code>string</code>
testString: 'assert(yourArray.filter( el => typeof el === ''string'').length >= 1, ''<code>yourArray</code> contains at least one <code>string</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
let yourArray; // change this line
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,68 @@
---
id: 587d7b7c367417b2b2512b1b
title: Use the delete Keyword to Remove Object Properties
challengeType: 1
---
## Description
<section id='description'>
Now you know what objects are and their basic features and advantages. In short, they are key-value stores which provide a flexible, intuitive way to structure data, <strong><em>and</em></strong>, they provide very fast lookup time. Throughout the rest of these challenges, we will describe several common operations you can perform on objects so you can become comfortable applying these useful data structures in your programs.
In earlier challenges, we have both added to and modified an object's key-value pairs. Here we will see how we can <em>remove</em> a key-value pair from an object.
Let's revisit our <code>foods</code> object example one last time. If we wanted to remove the <code>apples</code> key, we can remove it by using the <code>delete</code> keyword like this:
<blockquote>delete foods.apples;</blockquote>
</section>
## Instructions
<section id='instructions'>
Use the delete keyword to remove the <code>oranges</code>, <code>plums</code>, and <code>strawberries</code> keys from the <code>foods</code> object.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 'The <code>foods</code> object only has three keys: <code>apples</code>, <code>grapes</code>, and <code>bananas</code>'
testString: 'assert(!foods.hasOwnProperty(''oranges'') && !foods.hasOwnProperty(''plums'') && !foods.hasOwnProperty(''strawberries'') && Object.keys(foods).length === 3, ''The <code>foods</code> object only has three keys: <code>apples</code>, <code>grapes</code>, and <code>bananas</code>'');'
- text: 'The <code>oranges</code>, <code>plums</code>, and <code>strawberries</code> keys are removed using <code>delete</code>'
testString: 'assert(code.search(/oranges:/) !== -1 && code.search(/plums:/) !== -1 && code.search(/strawberries:/) !== -1, ''The <code>oranges</code>, <code>plums</code>, and <code>strawberries</code> keys are removed using <code>delete</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
let foods = {
apples: 25,
oranges: 32,
plums: 28,
bananas: 13,
grapes: 35,
strawberries: 27
};
// change code below this line
// change code above this line
console.log(foods);
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,76 @@
---
id: 56bbb991ad1ed5201cd392ca
title: Access Array Data with Indexes
challengeType: 1
guideUrl: 'https://guide.freecodecamp.org/certificates/access-array-data-with-indexes'
---
## Description
<section id='description'>
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>.
<strong>Example</strong>
<blockquote>var array = [50,60,70];<br>array[0]; // equals 50<br>var data = array[1]; // equals 60</blockquote>
<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>
## Instructions
<section id='instructions'>
Create a variable called <code>myData</code> and set it to equal the first value of <code>myArray</code> using bracket notation.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The variable <code>myData</code> should equal the first value of <code>myArray</code>.
testString: 'assert((function(){if(typeof myArray !== ''undefined'' && typeof myData !== ''undefined'' && myArray[0] === myData){return true;}else{return false;}})(), ''The variable <code>myData</code> should equal the first value of <code>myArray</code>.'');'
- text: The data in variable <code>myArray</code> should be accessed using bracket notation.
testString: 'assert((function(){if(code.match(/\s*=\s*myArray\[0\]/g)){return true;}else{return false;}})(), ''The data in variable <code>myArray</code> should be accessed using bracket notation.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Example
var ourArray = [50,60,70];
var ourData = ourArray[0]; // equals 50
// Setup
var myArray = [50,60,70];
// Only change code below this line.
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var myArray = [50,60,70];
var myData = myArray[0];
```
</section>

View File

@ -0,0 +1,72 @@
---
id: 56592a60ddddeae28f7aa8e1
title: Access Multi-Dimensional Arrays With Indexes
challengeType: 1
guideUrl: 'https://guide.freecodecamp.org/certificates/access-array-data-with-indexes'
---
## Description
<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>
<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>
## Instructions
<section id='instructions'>
Using bracket notation select an element from <code>myArray</code> such that <code>myData</code> is equal to <code>8</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>myData</code> should be equal to <code>8</code>.
testString: 'assert(myData === 8, ''<code>myData</code> should be equal to <code>8</code>.'');'
- text: You should be using bracket notation to read the correct value from <code>myArray</code>.
testString: 'assert(/myArray\[2\]\[1\]/g.test(code) && !/myData\s*=\s*(?:.*[-+*/%]|\d)/g.test(code), ''You should be using bracket notation to read the correct value from <code>myArray</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Setup
var myArray = [[1,2,3], [4,5,6], [7,8,9], [[10,11,12], 13, 14]];
// Only change code below this line.
var myData = myArray[0][0];
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var myArray = [[1,2,3],[4,5,6], [7,8,9], [[10,11,12], 13, 14]];
var myData = myArray[2][1];
```
</section>

View File

@ -0,0 +1,109 @@
---
id: 56533eb9ac21ba0edf2244cd
title: Accessing Nested Arrays
challengeType: 1
guideUrl: 'https://guide.freecodecamp.org/certificates/access-array-data-with-indexes'
---
## Description
<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>
</section>
## Instructions
<section id='instructions'>
Retrieve the second tree from the variable <code>myPlants</code> using object dot and array bracket notation.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>secondTree</code> should equal "pine"
testString: 'assert(secondTree === "pine", ''<code>secondTree</code> should equal "pine"'');'
- text: Use dot and bracket notation to access <code>myPlants</code>
testString: 'assert(/=\s*myPlants\[1\].list\[1\]/.test(code), ''Use dot and bracket notation to access <code>myPlants</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Setup
var myPlants = [
{
type: "flowers",
list: [
"rose",
"tulip",
"dandelion"
]
},
{
type: "trees",
list: [
"fir",
"pine",
"birch"
]
}
];
// Only change code below this line
var secondTree = ""; // Change this line
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var myPlants = [
{
type: "flowers",
list: [
"rose",
"tulip",
"dandelion"
]
},
{
type: "trees",
list: [
"fir",
"pine",
"birch"
]
}
];
// Only change code below this line
var secondTree = myPlants[1].list[1];
```
</section>

View File

@ -0,0 +1,90 @@
---
id: 56533eb9ac21ba0edf2244cc
title: Accessing Nested Objects
challengeType: 1
guideUrl: 'https://guide.freecodecamp.org/certificates/accessing-nested-objects-in-json'
---
## Description
<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>
</section>
## Instructions
<section id='instructions'>
Access the <code>myStorage</code> object and assign the contents of the <code>glove box</code> property to the <code>gloveBoxContents</code> variable. Use bracket notation for properties with a space in their name.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>gloveBoxContents</code> should equal "maps"
testString: 'assert(gloveBoxContents === "maps", ''<code>gloveBoxContents</code> should equal "maps"'');'
- text: Use dot and bracket notation to access <code>myStorage</code>
testString: 'assert(/=\s*myStorage\.car\.inside\[\s*("|'')glove box\1\s*\]/g.test(code), ''Use dot and bracket notation to access <code>myStorage</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Setup
var myStorage = {
"car": {
"inside": {
"glove box": "maps",
"passenger seat": "crumbs"
},
"outside": {
"trunk": "jack"
}
}
};
var gloveBoxContents = undefined; // Change this line
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var myStorage = {
"car":{
"inside":{
"glove box":"maps",
"passenger seat":"crumbs"
},
"outside":{
"trunk":"jack"
}
}
};
var gloveBoxContents = myStorage.car.inside["glove box"];
```
</section>

View File

@ -0,0 +1,89 @@
---
id: 56533eb9ac21ba0edf2244c8
title: Accessing Object Properties with Bracket Notation
challengeType: 1
guideUrl: 'https://guide.freecodecamp.org/certificates/accessing-objects-properties-with-bracket-notation'
---
## Description
<section id='description'>
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>
Note that property names with spaces in them must be in quotes (single or double).
</section>
## Instructions
<section id='instructions'>
Read the values of the properties <code>"an entree"</code> and <code>"the drink"</code> of <code>testObj</code> using bracket notation and assign them to <code>entreeValue</code> and <code>drinkValue</code> respectively.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>entreeValue</code> should be a string
testString: 'assert(typeof entreeValue === ''string'' , ''<code>entreeValue</code> should be a string'');'
- text: The value of <code>entreeValue</code> should be <code>"hamburger"</code>
testString: 'assert(entreeValue === ''hamburger'' , ''The value of <code>entreeValue</code> should be <code>"hamburger"</code>'');'
- text: <code>drinkValue</code> should be a string
testString: 'assert(typeof drinkValue === ''string'' , ''<code>drinkValue</code> should be a string'');'
- text: The value of <code>drinkValue</code> should be <code>"water"</code>
testString: 'assert(drinkValue === ''water'' , ''The value of <code>drinkValue</code> should be <code>"water"</code>'');'
- text: You should use bracket notation twice
testString: 'assert(code.match(/testObj\s*?\[(''|")[^''"]+\1\]/g).length > 1, ''You should use bracket notation twice'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Setup
var testObj = {
"an entree": "hamburger",
"my side": "veggies",
"the drink": "water"
};
// Only change code below this line
var entreeValue = testObj; // Change this line
var drinkValue = testObj; // Change this line
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var testObj = {
"an entree": "hamburger",
"my side": "veggies",
"the drink": "water"
};
var entreeValue = testObj["an entree"];
var drinkValue = testObj['the drink'];
```
</section>

View File

@ -0,0 +1,88 @@
---
id: 56533eb9ac21ba0edf2244c7
title: Accessing Object Properties with Dot Notation
challengeType: 1
---
## Description
<section id='description'>
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>
</section>
## Instructions
<section id='instructions'>
Read in the property values of <code>testObj</code> using dot notation. Set the variable <code>hatValue</code> equal to the object's property <code>hat</code> and set the variable <code>shirtValue</code> equal to the object's property <code>shirt</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>hatValue</code> should be a string
testString: 'assert(typeof hatValue === ''string'' , ''<code>hatValue</code> should be a string'');'
- text: The value of <code>hatValue</code> should be <code>"ballcap"</code>
testString: 'assert(hatValue === ''ballcap'' , ''The value of <code>hatValue</code> should be <code>"ballcap"</code>'');'
- text: <code>shirtValue</code> should be a string
testString: 'assert(typeof shirtValue === ''string'' , ''<code>shirtValue</code> should be a string'');'
- text: The value of <code>shirtValue</code> should be <code>"jersey"</code>
testString: 'assert(shirtValue === ''jersey'' , ''The value of <code>shirtValue</code> should be <code>"jersey"</code>'');'
- text: You should use dot notation twice
testString: 'assert(code.match(/testObj\.\w+/g).length > 1, ''You should use dot notation twice'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Setup
var testObj = {
"hat": "ballcap",
"shirt": "jersey",
"shoes": "cleats"
};
// Only change code below this line
var hatValue = testObj; // Change this line
var shirtValue = testObj; // Change this line
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var testObj = {
"hat": "ballcap",
"shirt": "jersey",
"shoes": "cleats"
};
var hatValue = testObj.hat;
var shirtValue = testObj.shirt;
```
</section>

View File

@ -0,0 +1,94 @@
---
id: 56533eb9ac21ba0edf2244c9
title: Accessing Object Properties with Variables
challengeType: 1
guideUrl: 'https://guide.freecodecamp.org/certificates/accessing-objects-properties-with-variables'
---
## Description
<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>
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>
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>
## Instructions
<section id='instructions'>
Use the <code>playerNumber</code> variable to look up player <code>16</code> in <code>testObj</code> using bracket notation. Then assign that name to the <code>player</code> variable.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>playerNumber</code> should be a number
testString: 'assert(typeof playerNumber === ''number'', ''<code>playerNumber</code> should be a number'');'
- text: The variable <code>player</code> should be a string
testString: 'assert(typeof player === ''string'', ''The variable <code>player</code> should be a string'');'
- text: The value of <code>player</code> should be "Montana"
testString: 'assert(player === ''Montana'', ''The value of <code>player</code> should be "Montana"'');'
- text: You should use bracket notation to access <code>testObj</code>
testString: 'assert(/testObj\s*?\[.*?\]/.test(code),''You should use bracket notation to access <code>testObj</code>'');'
- text: You should not assign the value <code>Montana</code> to the variable <code>player</code> directly.
testString: 'assert(!code.match(/player\s*=\s*"|\''\s*Montana\s*"|\''\s*;/gi),''You should not assign the value <code>Montana</code> to the variable <code>player</code> directly.'');'
- text: You should be using the variable <code>playerNumber</code> in your bracket notation
testString: 'assert(/testObj\s*?\[\s*playerNumber\s*\]/.test(code),''You should be using the variable <code>playerNumber</code> in your bracket notation'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Setup
var testObj = {
12: "Namath",
16: "Montana",
19: "Unitas"
};
// Only change code below this line;
var playerNumber; // Change this Line
var player = testObj; // Change this Line
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var testObj = {
12: "Namath",
16: "Montana",
19: "Unitas"
};
var playerNumber = 16;
var player = testObj[playerNumber];
```
</section>

View File

@ -0,0 +1,92 @@
---
id: 56bbb991ad1ed5201cd392d2
title: Add New Properties to a JavaScript Object
challengeType: 1
---
## Description
<section id='description'>
You can add new properties to existing JavaScript objects the same way you would modify them.
Here's how we would add a <code>"bark"</code> property to <code>ourDog</code>:
<code>ourDog.bark = "bow-wow";</code>
or
<code>ourDog["bark"] = "bow-wow";</code>
Now when we evaluate <code>ourDog.bark</code>, we'll get his bark, "bow-wow".
</section>
## Instructions
<section id='instructions'>
Add a <code>"bark"</code> property to <code>myDog</code> and set it to a dog sound, such as "woof". You may use either dot or bracket notation.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Add the property <code>"bark"</code> to <code>myDog</code>.
testString: 'assert(myDog.bark !== undefined, ''Add the property <code>"bark"</code> to <code>myDog</code>.'');'
- text: Do not add <code>"bark"</code> to the setup section
testString: 'assert(!/bark[^\n]:/.test(code), ''Do not add <code>"bark"</code> to the setup section'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Example
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"]
};
ourDog.bark = "bow-wow";
// Setup
var myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"]
};
// Only change code below this line.
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"]
};
myDog.bark = "Woof Woof";
```
</section>

View File

@ -0,0 +1,67 @@
---
id: cf1111c1c11feddfaeb3bdef
title: Add Two Numbers with JavaScript
challengeType: 1
---
## Description
<section id='description'>
<code>Number</code> is a data type in JavaScript which represents numeric data.
Now let's try to add two numbers using JavaScript.
JavaScript uses the <code>+</code> symbol as addition operation when placed between two numbers.
<strong>Example</strong>
<blockquote>myVar = 5 + 10; // assigned 15</blockquote>
</section>
## Instructions
<section id='instructions'>
Change the <code>0</code> so that sum will equal <code>20</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>sum</code> should equal <code>20</code>
testString: 'assert(sum === 20, ''<code>sum</code> should equal <code>20</code>'');'
- text: Use the <code>+</code> operator
testString: 'assert(/\+/.test(code), ''Use the <code>+</code> operator'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var sum = 10 + 0;
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var sum = 10 + 10;
```
</section>

View File

@ -0,0 +1,98 @@
---
id: 56533eb9ac21ba0edf2244de
title: Adding a Default Option in Switch Statements
challengeType: 1
guideUrl: 'https://guide.freecodecamp.org/certificates/adding-a-default-option-in-switch-statements'
---
## Description
<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>
</section>
## Instructions
<section id='instructions'>
Write a switch statement to set <code>answer</code> for the following conditions:<br><code>"a"</code> - "apple"<br><code>"b"</code> - "bird"<br><code>"c"</code> - "cat"<br><code>default</code> - "stuff"
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>switchOfStuff("a")</code> should have a value of "apple"
testString: 'assert(switchOfStuff("a") === "apple", ''<code>switchOfStuff("a")</code> should have a value of "apple"'');'
- text: <code>switchOfStuff("b")</code> should have a value of "bird"
testString: 'assert(switchOfStuff("b") === "bird", ''<code>switchOfStuff("b")</code> should have a value of "bird"'');'
- text: <code>switchOfStuff("c")</code> should have a value of "cat"
testString: 'assert(switchOfStuff("c") === "cat", ''<code>switchOfStuff("c")</code> should have a value of "cat"'');'
- text: <code>switchOfStuff("d")</code> should have a value of "stuff"
testString: 'assert(switchOfStuff("d") === "stuff", ''<code>switchOfStuff("d")</code> should have a value of "stuff"'');'
- text: <code>switchOfStuff(4)</code> should have a value of "stuff"
testString: 'assert(switchOfStuff(4) === "stuff", ''<code>switchOfStuff(4)</code> should have a value of "stuff"'');'
- text: You should not use any <code>if</code> or <code>else</code> statements
testString: 'assert(!/else/g.test(code) || !/if/g.test(code), ''You should not use any <code>if</code> or <code>else</code> statements'');'
- text: You should use a <code>default</code> statement
testString: 'assert(switchOfStuff("string-to-trigger-default-case") === "stuff", ''You should use a <code>default</code> statement'');'
- text: You should have at least 3 <code>break</code> statements
testString: 'assert(code.match(/break/g).length > 2, ''You should have at least 3 <code>break</code> statements'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function switchOfStuff(val) {
var answer = "";
// Only change code below this line
// Only change code above this line
return answer;
}
// Change this value to test
switchOfStuff(1);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function switchOfStuff(val) {
var answer = "";
switch(val) {
case "a":
answer = "apple";
break;
case "b":
answer = "bird";
break;
case "c":
answer = "cat";
break;
default:
answer = "stuff";
}
return answer;
}
```
</section>

View File

@ -0,0 +1,78 @@
---
id: 56533eb9ac21ba0edf2244ed
title: Appending Variables to Strings
challengeType: 1
guideUrl: 'https://guide.freecodecamp.org/certificates/appending-variables-to-strings'
---
## Description
<section id='description'>
Just as we can build a string over multiple lines out of string <dfn>literals</dfn>, we can also append variables to a string using the plus equals (<code>+=</code>) operator.
</section>
## Instructions
<section id='instructions'>
Set <code>someAdjective</code> and append it to <code>myStr</code> using the <code>+=</code> operator.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>someAdjective</code> should be set to a string at least 3 characters long
testString: 'assert(typeof someAdjective !== ''undefined'' && someAdjective.length > 2, ''<code>someAdjective</code> should be set to a string at least 3 characters long'');'
- text: Append <code>someAdjective</code> to <code>myStr</code> using the <code>+=</code> operator
testString: 'assert(code.match(/myStr\s*\+=\s*someAdjective\s*/).length > 0, ''Append <code>someAdjective</code> to <code>myStr</code> using the <code>+=</code> operator'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Example
var anAdjective = "awesome!";
var ourStr = "freeCodeCamp is ";
ourStr += anAdjective;
// Only change code below this line
var someAdjective;
var myStr = "Learning to code is ";
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var anAdjective = "awesome!";
var ourStr = "freeCodeCamp is ";
ourStr += anAdjective;
var someAdjective = "neat";
var myStr = "Learning to code is ";
myStr += someAdjective;
```
</section>

View File

@ -0,0 +1,90 @@
---
id: 56533eb9ac21ba0edf2244c3
title: Assignment with a Returned Value
challengeType: 1
guideUrl: 'https://guide.freecodecamp.org/certificates/assignment-with-a-returned-value'
---
## Description
<section id='description'>
If you'll recall from our discussion of <a href="javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator" target="_blank">Storing Values with the Assignment Operator</a>, everything to the right of the equal sign is resolved before the value is assigned. This means we can take the return value of a function and assign it to a variable.
Assume we have pre-defined a function <code>sum</code> which adds two numbers together, then:
<code>ourSum = sum(5, 12);</code>
will call <code>sum</code> function, which returns a value of <code>17</code> and assigns it to <code>ourSum</code> variable.
</section>
## Instructions
<section id='instructions'>
Call the <code>processArg</code> function with an argument of <code>7</code> and assign its return value to the variable <code>processed</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>processed</code> should have a value of <code>2</code>
testString: 'assert(processed === 2, ''<code>processed</code> should have a value of <code>2</code>'');'
- text: You should assign <code>processArg</code> to <code>processed</code>
testString: 'assert(/processed\s*=\s*processArg\(\s*7\s*\)\s*;/.test(code), ''You should assign <code>processArg</code> to <code>processed</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Example
var changed = 0;
function change(num) {
return (num + 5) / 3;
}
changed = change(10);
// Setup
var processed = 0;
function processArg(num) {
return (num + 3) / 5;
}
// Only change code below this line
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var processed = 0;
function processArg(num) {
return (num + 3) / 5;
}
processed = processArg(7);
```
</section>

View File

@ -0,0 +1,96 @@
---
id: 56bbb991ad1ed5201cd392d0
title: Build JavaScript Objects
challengeType: 1
---
## Description
<section id='description'>
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>
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>
However, if your object has any non-string properties, JavaScript will automatically typecast them as strings.
</section>
## Instructions
<section id='instructions'>
Make an object that represents a dog called <code>myDog</code> which contains the properties <code>"name"</code> (a string), <code>"legs"</code>, <code>"tails"</code> and <code>"friends"</code>.
You can set these object properties to whatever values you want, as long <code>"name"</code> is a string, <code>"legs"</code> and <code>"tails"</code> are numbers, and <code>"friends"</code> is an array.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>myDog</code> should contain the property <code>name</code> and it should be a <code>string</code>.
testString: 'assert((function(z){if(z.hasOwnProperty("name") && z.name !== undefined && typeof z.name === "string"){return true;}else{return false;}})(myDog), ''<code>myDog</code> should contain the property <code>name</code> and it should be a <code>string</code>.'');'
- text: <code>myDog</code> should contain the property <code>legs</code> and it should be a <code>number</code>.
testString: 'assert((function(z){if(z.hasOwnProperty("legs") && z.legs !== undefined && typeof z.legs === "number"){return true;}else{return false;}})(myDog), ''<code>myDog</code> should contain the property <code>legs</code> and it should be a <code>number</code>.'');'
- text: <code>myDog</code> should contain the property <code>tails</code> and it should be a <code>number</code>.
testString: 'assert((function(z){if(z.hasOwnProperty("tails") && z.tails !== undefined && typeof z.tails === "number"){return true;}else{return false;}})(myDog), ''<code>myDog</code> should contain the property <code>tails</code> and it should be a <code>number</code>.'');'
- text: <code>myDog</code> should contain the property <code>friends</code> and it should be an <code>array</code>.
testString: 'assert((function(z){if(z.hasOwnProperty("friends") && z.friends !== undefined && Array.isArray(z.friends)){return true;}else{return false;}})(myDog), ''<code>myDog</code> should contain the property <code>friends</code> and it should be an <code>array</code>.'');'
- text: <code>myDog</code> should only contain all the given properties.
testString: 'assert((function(z){return Object.keys(z).length === 4;})(myDog), ''<code>myDog</code> should only contain all the given properties.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Example
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"]
};
// Only change code below this line.
var myDog = {
};
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var myDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"]
};
```
</section>

View File

@ -0,0 +1,99 @@
---
id: 56533eb9ac21ba0edf2244dc
title: Chaining If Else Statements
challengeType: 1
---
## 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>
</section>
## Instructions
<section id='instructions'>
Write chained <code>if</code>/<code>else if</code> statements to fulfill the following conditions:
<code>num &lt; 5</code> - return "Tiny"<br><code>num &lt; 10</code> - return "Small"<br><code>num &lt; 15</code> - return "Medium"<br><code>num &lt; 20</code> - return "Large"<br><code>num >= 20</code> - return "Huge"
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: You should have at least four <code>else</code> statements
testString: 'assert(code.match(/else/g).length > 3, ''You should have at least four <code>else</code> statements'');'
- text: You should have at least four <code>if</code> statements
testString: 'assert(code.match(/if/g).length > 3, ''You should have at least four <code>if</code> statements'');'
- text: You should have at least one <code>return</code> statement
testString: 'assert(code.match(/return/g).length >= 1, ''You should have at least one <code>return</code> statement'');'
- text: <code>testSize(0)</code> should return "Tiny"
testString: 'assert(testSize(0) === "Tiny", ''<code>testSize(0)</code> should return "Tiny"'');'
- text: <code>testSize(4)</code> should return "Tiny"
testString: 'assert(testSize(4) === "Tiny", ''<code>testSize(4)</code> should return "Tiny"'');'
- text: <code>testSize(5)</code> should return "Small"
testString: 'assert(testSize(5) === "Small", ''<code>testSize(5)</code> should return "Small"'');'
- text: <code>testSize(8)</code> should return "Small"
testString: 'assert(testSize(8) === "Small", ''<code>testSize(8)</code> should return "Small"'');'
- text: <code>testSize(10)</code> should return "Medium"
testString: 'assert(testSize(10) === "Medium", ''<code>testSize(10)</code> should return "Medium"'');'
- text: <code>testSize(14)</code> should return "Medium"
testString: 'assert(testSize(14) === "Medium", ''<code>testSize(14)</code> should return "Medium"'');'
- text: <code>testSize(15)</code> should return "Large"
testString: 'assert(testSize(15) === "Large", ''<code>testSize(15)</code> should return "Large"'');'
- text: <code>testSize(17)</code> should return "Large"
testString: 'assert(testSize(17) === "Large", ''<code>testSize(17)</code> should return "Large"'');'
- text: <code>testSize(20)</code> should return "Huge"
testString: 'assert(testSize(20) === "Huge", ''<code>testSize(20)</code> should return "Huge"'');'
- text: <code>testSize(25)</code> should return "Huge"
testString: 'assert(testSize(25) === "Huge", ''<code>testSize(25)</code> should return "Huge"'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function testSize(num) {
// Only change code below this line
return "Change Me";
// Only change code above this line
}
// Change this value to test
testSize(7);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function testSize(num) {
if (num < 5) {
return "Tiny";
} else if (num < 10) {
return "Small";
} else if (num < 15) {
return "Medium";
} else if (num < 20) {
return "Large";
} else {
return "Huge";
}
}
```
</section>

View File

@ -0,0 +1,61 @@
---
id: bd7123c9c441eddfaeb4bdef
title: Comment Your JavaScript Code
challengeType: 1
---
## Description
<section id='description'>
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>
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>
<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>
## Instructions
<section id='instructions'>
Try creating one of each type of comment.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Create a <code>//</code> style comment that contains at least five letters.
testString: 'assert(code.match(/(\/\/)...../g), ''Create a <code>//</code> style comment that contains at least five letters.'');'
- text: Create a <code>/* */</code> style comment that contains at least five letters.
testString: 'assert(code.match(/(\/\*)([^\/]{5,})(?=\*\/)/gm), ''Create a <code>/* */</code> style comment that contains at least five letters.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
```
</div>
</section>
## Solution
<section id='solution'>
```js
// Fake Comment
/* Another Comment */
```
</section>

View File

@ -0,0 +1,77 @@
---
id: 56533eb9ac21ba0edf2244d0
title: Comparison with the Equality Operator
challengeType: 1
---
## Description
<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>
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>
</section>
## Instructions
<section id='instructions'>
Add the <code>equality operator</code> to the indicated line so that the function will return "Equal" when <code>val</code> is equivalent to <code>12</code>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>testEqual(10)</code> should return "Not Equal"
testString: 'assert(testEqual(10) === "Not Equal", ''<code>testEqual(10)</code> should return "Not Equal"'');'
- text: <code>testEqual(12)</code> should return "Equal"
testString: 'assert(testEqual(12) === "Equal", ''<code>testEqual(12)</code> should return "Equal"'');'
- text: <code>testEqual("12")</code> should return "Equal"
testString: 'assert(testEqual("12") === "Equal", ''<code>testEqual("12")</code> should return "Equal"'');'
- text: You should use the <code>==</code> operator
testString: 'assert(code.match(/==/g) && !code.match(/===/g), ''You should use the <code>==</code> operator'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Setup
function testEqual(val) {
if (val) { // Change this line
return "Equal";
}
return "Not Equal";
}
// Change this value to test
testEqual(10);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function testEqual(val) {
if (val == 12) {
return "Equal";
}
return "Not Equal";
}
```
</section>

View File

@ -0,0 +1,90 @@
---
id: 56533eb9ac21ba0edf2244d4
title: Comparison with the Greater Than Operator
challengeType: 1
---
## Description
<section id='description'>
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>
</section>
## Instructions
<section id='instructions'>
Add the <code>greater than</code> operator to the indicated lines so that the return statements make sense.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>testGreaterThan(0)</code> should return "10 or Under"
testString: 'assert(testGreaterThan(0) === "10 or Under", ''<code>testGreaterThan(0)</code> should return "10 or Under"'');'
- text: <code>testGreaterThan(10)</code> should return "10 or Under"
testString: 'assert(testGreaterThan(10) === "10 or Under", ''<code>testGreaterThan(10)</code> should return "10 or Under"'');'
- text: <code>testGreaterThan(11)</code> should return "Over 10"
testString: 'assert(testGreaterThan(11) === "Over 10", ''<code>testGreaterThan(11)</code> should return "Over 10"'');'
- text: <code>testGreaterThan(99)</code> should return "Over 10"
testString: 'assert(testGreaterThan(99) === "Over 10", ''<code>testGreaterThan(99)</code> should return "Over 10"'');'
- text: <code>testGreaterThan(100)</code> should return "Over 10"
testString: 'assert(testGreaterThan(100) === "Over 10", ''<code>testGreaterThan(100)</code> should return "Over 10"'');'
- text: <code>testGreaterThan(101)</code> should return "Over 100"
testString: 'assert(testGreaterThan(101) === "Over 100", ''<code>testGreaterThan(101)</code> should return "Over 100"'');'
- text: <code>testGreaterThan(150)</code> should return "Over 100"
testString: 'assert(testGreaterThan(150) === "Over 100", ''<code>testGreaterThan(150)</code> should return "Over 100"'');'
- text: You should use the <code>&gt;</code> operator at least twice
testString: 'assert(code.match(/val\s*>\s*(''|")*\d+(''|")*/g).length > 1, ''You should use the <code>&gt;</code> operator at least twice'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function testGreaterThan(val) {
if (val) { // Change this line
return "Over 100";
}
if (val) { // Change this line
return "Over 10";
}
return "10 or Under";
}
// Change this value to test
testGreaterThan(10);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function testGreaterThan(val) {
if (val > 100) { // Change this line
return "Over 100";
}
if (val > 10) { // Change this line
return "Over 10";
}
return "10 or Under";
}
```
</section>

View File

@ -0,0 +1,92 @@
---
id: 56533eb9ac21ba0edf2244d5
title: Comparison with the Greater Than Or Equal To Operator
challengeType: 1
---
## Description
<section id='description'>
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>
</section>
## Instructions
<section id='instructions'>
Add the <code>greater than or equal to</code> operator to the indicated lines so that the return statements make sense.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>testGreaterOrEqual(0)</code> should return "Less than 10"
testString: 'assert(testGreaterOrEqual(0) === "Less than 10", ''<code>testGreaterOrEqual(0)</code> should return "Less than 10"'');'
- text: <code>testGreaterOrEqual(9)</code> should return "Less than 10"
testString: 'assert(testGreaterOrEqual(9) === "Less than 10", ''<code>testGreaterOrEqual(9)</code> should return "Less than 10"'');'
- text: <code>testGreaterOrEqual(10)</code> should return "10 or Over"
testString: 'assert(testGreaterOrEqual(10) === "10 or Over", ''<code>testGreaterOrEqual(10)</code> should return "10 or Over"'');'
- text: <code>testGreaterOrEqual(11)</code> should return "10 or Over"
testString: 'assert(testGreaterOrEqual(11) === "10 or Over", ''<code>testGreaterOrEqual(11)</code> should return "10 or Over"'');'
- text: <code>testGreaterOrEqual(19)</code> should return "10 or Over"
testString: 'assert(testGreaterOrEqual(19) === "10 or Over", ''<code>testGreaterOrEqual(19)</code> should return "10 or Over"'');'
- text: <code>testGreaterOrEqual(100)</code> should return "20 or Over"
testString: 'assert(testGreaterOrEqual(100) === "20 or Over", ''<code>testGreaterOrEqual(100)</code> should return "20 or Over"'');'
- text: <code>testGreaterOrEqual(21)</code> should return "20 or Over"
testString: 'assert(testGreaterOrEqual(21) === "20 or Over", ''<code>testGreaterOrEqual(21)</code> should return "20 or Over"'');'
- text: You should use the <code>&gt;=</code> operator at least twice
testString: 'assert(code.match(/val\s*>=\s*(''|")*\d+(''|")*/g).length > 1, ''You should use the <code>&gt;=</code> operator at least twice'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function testGreaterOrEqual(val) {
if (val) { // Change this line
return "20 or Over";
}
if (val) { // Change this line
return "10 or Over";
}
return "Less than 10";
}
// Change this value to test
testGreaterOrEqual(10);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function testGreaterOrEqual(val) {
if (val >= 20) { // Change this line
return "20 or Over";
}
if (val >= 10) { // Change this line
return "10 or Over";
}
return "Less than 10";
}
```
</section>

View File

@ -0,0 +1,78 @@
---
id: 56533eb9ac21ba0edf2244d2
title: Comparison with the Inequality Operator
challengeType: 1
---
## Description
<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>
</section>
## Instructions
<section id='instructions'>
Add the inequality operator <code>!=</code> in the <code>if</code> statement so that the function will return "Not Equal" when <code>val</code> is not equivalent to <code>99</code>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>testNotEqual(99)</code> should return "Equal"
testString: 'assert(testNotEqual(99) === "Equal", ''<code>testNotEqual(99)</code> should return "Equal"'');'
- text: <code>testNotEqual("99")</code> should return "Equal"
testString: 'assert(testNotEqual("99") === "Equal", ''<code>testNotEqual("99")</code> should return "Equal"'');'
- text: <code>testNotEqual(12)</code> should return "Not Equal"
testString: 'assert(testNotEqual(12) === "Not Equal", ''<code>testNotEqual(12)</code> should return "Not Equal"'');'
- text: <code>testNotEqual("12")</code> should return "Not Equal"
testString: 'assert(testNotEqual("12") === "Not Equal", ''<code>testNotEqual("12")</code> should return "Not Equal"'');'
- text: <code>testNotEqual("bob")</code> should return "Not Equal"
testString: 'assert(testNotEqual("bob") === "Not Equal", ''<code>testNotEqual("bob")</code> should return "Not Equal"'');'
- text: You should use the <code>!=</code> operator
testString: 'assert(code.match(/(?!!==)!=/), ''You should use the <code>!=</code> operator'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Setup
function testNotEqual(val) {
if (val) { // Change this line
return "Not Equal";
}
return "Equal";
}
// Change this value to test
testNotEqual(10);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function testNotEqual(val) {
if (val != 99) {
return "Not Equal";
}
return "Equal";
}
```
</section>

View File

@ -0,0 +1,89 @@
---
id: 56533eb9ac21ba0edf2244d6
title: Comparison with the Less Than Operator
challengeType: 1
---
## Description
<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>
</section>
## Instructions
<section id='instructions'>
Add the <code>less than</code> operator to the indicated lines so that the return statements make sense.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>testLessThan(0)</code> should return "Under 25"
testString: 'assert(testLessThan(0) === "Under 25", ''<code>testLessThan(0)</code> should return "Under 25"'');'
- text: <code>testLessThan(24)</code> should return "Under 25"
testString: 'assert(testLessThan(24) === "Under 25", ''<code>testLessThan(24)</code> should return "Under 25"'');'
- text: <code>testLessThan(25)</code> should return "Under 55"
testString: 'assert(testLessThan(25) === "Under 55", ''<code>testLessThan(25)</code> should return "Under 55"'');'
- text: <code>testLessThan(54)</code> should return "Under 55"
testString: 'assert(testLessThan(54) === "Under 55", ''<code>testLessThan(54)</code> should return "Under 55"'');'
- text: <code>testLessThan(55)</code> should return "55 or Over"
testString: 'assert(testLessThan(55) === "55 or Over", ''<code>testLessThan(55)</code> should return "55 or Over"'');'
- text: <code>testLessThan(99)</code> should return "55 or Over"
testString: 'assert(testLessThan(99) === "55 or Over", ''<code>testLessThan(99)</code> should return "55 or Over"'');'
- text: You should use the <code>&lt;</code> operator at least twice
testString: 'assert(code.match(/val\s*<\s*(''|")*\d+(''|")*/g).length > 1, ''You should use the <code>&lt;</code> operator at least twice'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function testLessThan(val) {
if (val) { // Change this line
return "Under 25";
}
if (val) { // Change this line
return "Under 55";
}
return "55 or Over";
}
// Change this value to test
testLessThan(10);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function testLessThan(val) {
if (val < 25) { // Change this line
return "Under 25";
}
if (val < 55) { // Change this line
return "Under 55";
}
return "55 or Over";
}
```
</section>

View File

@ -0,0 +1,92 @@
---
id: 56533eb9ac21ba0edf2244d7
title: Comparison with the Less Than Or Equal To Operator
challengeType: 1
---
## Description
<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>
</section>
## Instructions
<section id='instructions'>
Add the <code>less than or equal to</code> operator to the indicated lines so that the return statements make sense.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>testLessOrEqual(0)</code> should return "Smaller Than or Equal to 12"
testString: 'assert(testLessOrEqual(0) === "Smaller Than or Equal to 12", ''<code>testLessOrEqual(0)</code> should return "Smaller Than or Equal to 12"'');'
- text: <code>testLessOrEqual(11)</code> should return "Smaller Than or Equal to 12"
testString: 'assert(testLessOrEqual(11) === "Smaller Than or Equal to 12", ''<code>testLessOrEqual(11)</code> should return "Smaller Than or Equal to 12"'');'
- text: <code>testLessOrEqual(12)</code> should return "Smaller Than or Equal to 12"
testString: 'assert(testLessOrEqual(12) === "Smaller Than or Equal to 12", ''<code>testLessOrEqual(12)</code> should return "Smaller Than or Equal to 12"'');'
- text: <code>testLessOrEqual(23)</code> should return "Smaller Than or Equal to 24"
testString: 'assert(testLessOrEqual(23) === "Smaller Than or Equal to 24", ''<code>testLessOrEqual(23)</code> should return "Smaller Than or Equal to 24"'');'
- text: <code>testLessOrEqual(24)</code> should return "Smaller Than or Equal to 24"
testString: 'assert(testLessOrEqual(24) === "Smaller Than or Equal to 24", ''<code>testLessOrEqual(24)</code> should return "Smaller Than or Equal to 24"'');'
- text: <code>testLessOrEqual(25)</code> should return "More Than 24"
testString: 'assert(testLessOrEqual(25) === "More Than 24", ''<code>testLessOrEqual(25)</code> should return "More Than 24"'');'
- text: <code>testLessOrEqual(55)</code> should return "More Than 24"
testString: 'assert(testLessOrEqual(55) === "More Than 24", ''<code>testLessOrEqual(55)</code> should return "More Than 24"'');'
- text: You should use the <code>&lt;=</code> operator at least twice
testString: 'assert(code.match(/val\s*<=\s*(''|")*\d+(''|")*/g).length > 1, ''You should use the <code>&lt;=</code> operator at least twice'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function testLessOrEqual(val) {
if (val) { // Change this line
return "Smaller Than or Equal to 12";
}
if (val) { // Change this line
return "Smaller Than or Equal to 24";
}
return "More Than 24";
}
// Change this value to test
testLessOrEqual(10);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function testLessOrEqual(val) {
if (val <= 12) { // Change this line
return "Smaller Than or Equal to 12";
}
if (val <= 24) { // Change this line
return "Smaller Than or Equal to 24";
}
return "More Than 24";
}
```
</section>

View File

@ -0,0 +1,76 @@
---
id: 56533eb9ac21ba0edf2244d1
title: Comparison with the Strict Equality Operator
challengeType: 1
---
## Description
<section id='description'>
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>
In the second example, <code>3</code> is a <code>Number</code> type and <code>'3'</code> is a <code>String</code> type.
</section>
## Instructions
<section id='instructions'>
Use the strict equality operator in the <code>if</code> statement so the function will return "Equal" when <code>val</code> is strictly equal to <code>7</code>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>testStrict(10)</code> should return "Not Equal"
testString: 'assert(testStrict(10) === "Not Equal", ''<code>testStrict(10)</code> should return "Not Equal"'');'
- text: <code>testStrict(7)</code> should return "Equal"
testString: 'assert(testStrict(7) === "Equal", ''<code>testStrict(7)</code> should return "Equal"'');'
- text: <code>testStrict("7")</code> should return "Not Equal"
testString: 'assert(testStrict("7") === "Not Equal", ''<code>testStrict("7")</code> should return "Not Equal"'');'
- text: You should use the <code>===</code> operator
testString: 'assert(code.match(/(val\s*===\s*\d+)|(\d+\s*===\s*val)/g).length > 0, ''You should use the <code>===</code> operator'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Setup
function testStrict(val) {
if (val) { // Change this line
return "Equal";
}
return "Not Equal";
}
// Change this value to test
testStrict(10);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function testStrict(val) {
if (val === 7) {
return "Equal";
}
return "Not Equal";
}
```
</section>

View File

@ -0,0 +1,81 @@
---
id: 56533eb9ac21ba0edf2244d3
title: Comparison with the Strict Inequality Operator
challengeType: 1
---
## Description
<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>
</section>
## Instructions
<section id='instructions'>
Add the <code>strict inequality operator</code> to the <code>if</code> statement so the function will return "Not Equal" when <code>val</code> is not strictly equal to <code>17</code>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>testStrictNotEqual(17)</code> should return "Equal"
testString: 'assert(testStrictNotEqual(17) === "Equal", ''<code>testStrictNotEqual(17)</code> should return "Equal"'');'
- text: <code>testStrictNotEqual("17")</code> should return "Not Equal"
testString: 'assert(testStrictNotEqual("17") === "Not Equal", ''<code>testStrictNotEqual("17")</code> should return "Not Equal"'');'
- text: <code>testStrictNotEqual(12)</code> should return "Not Equal"
testString: 'assert(testStrictNotEqual(12) === "Not Equal", ''<code>testStrictNotEqual(12)</code> should return "Not Equal"'');'
- text: <code>testStrictNotEqual("bob")</code> should return "Not Equal"
testString: 'assert(testStrictNotEqual("bob") === "Not Equal", ''<code>testStrictNotEqual("bob")</code> should return "Not Equal"'');'
- text: You should use the <code>!==</code> operator
testString: 'assert(code.match(/(val\s*!==\s*\d+)|(\d+\s*!==\s*val)/g).length > 0, ''You should use the <code>!==</code> operator'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Setup
function testStrictNotEqual(val) {
// Only Change Code Below this Line
if (val) {
// Only Change Code Above this Line
return "Not Equal";
}
return "Equal";
}
// Change this value to test
testStrictNotEqual(10);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function testStrictNotEqual(val) {
if (val !== 17) {
return "Not Equal";
}
return "Equal";
}
```
</section>

View File

@ -0,0 +1,93 @@
---
id: 56533eb9ac21ba0edf2244d8
title: Comparisons with the Logical And Operator
challengeType: 1
---
## Description
<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>
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>
</section>
## Instructions
<section id='instructions'>
Combine the two if statements into one statement which will return <code>"Yes"</code> if <code>val</code> is less than or equal to <code>50</code> and greater than or equal to <code>25</code>. Otherwise, will return <code>"No"</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: You should use the <code>&&</code> operator once
testString: 'assert(code.match(/&&/g).length === 1, ''You should use the <code>&&</code> operator once'');'
- text: You should only have one <code>if</code> statement
testString: 'assert(code.match(/if/g).length === 1, ''You should only have one <code>if</code> statement'');'
- text: <code>testLogicalAnd(0)</code> should return "No"
testString: 'assert(testLogicalAnd(0) === "No", ''<code>testLogicalAnd(0)</code> should return "No"'');'
- text: <code>testLogicalAnd(24)</code> should return "No"
testString: 'assert(testLogicalAnd(24) === "No", ''<code>testLogicalAnd(24)</code> should return "No"'');'
- text: <code>testLogicalAnd(25)</code> should return "Yes"
testString: 'assert(testLogicalAnd(25) === "Yes", ''<code>testLogicalAnd(25)</code> should return "Yes"'');'
- text: <code>testLogicalAnd(30)</code> should return "Yes"
testString: 'assert(testLogicalAnd(30) === "Yes", ''<code>testLogicalAnd(30)</code> should return "Yes"'');'
- text: <code>testLogicalAnd(50)</code> should return "Yes"
testString: 'assert(testLogicalAnd(50) === "Yes", ''<code>testLogicalAnd(50)</code> should return "Yes"'');'
- text: <code>testLogicalAnd(51)</code> should return "No"
testString: 'assert(testLogicalAnd(51) === "No", ''<code>testLogicalAnd(51)</code> should return "No"'');'
- text: <code>testLogicalAnd(75)</code> should return "No"
testString: 'assert(testLogicalAnd(75) === "No", ''<code>testLogicalAnd(75)</code> should return "No"'');'
- text: <code>testLogicalAnd(80)</code> should return "No"
testString: 'assert(testLogicalAnd(80) === "No", ''<code>testLogicalAnd(80)</code> should return "No"'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function testLogicalAnd(val) {
// Only change code below this line
if (val) {
if (val) {
return "Yes";
}
}
// Only change code above this line
return "No";
}
// Change this value to test
testLogicalAnd(10);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function testLogicalAnd(val) {
if (val >= 25 && val <= 50) {
return "Yes";
}
return "No";
}
```
</section>

View File

@ -0,0 +1,96 @@
---
id: 56533eb9ac21ba0edf2244d9
title: Comparisons with the Logical Or Operator
challengeType: 1
---
## Description
<section id='description'>
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>
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>
</section>
## Instructions
<section id='instructions'>
Combine the two <code>if</code> statements into one statement which returns <code>"Outside"</code> if <code>val</code> is not between <code>10</code> and <code>20</code>, inclusive. Otherwise, return <code>"Inside"</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: You should use the <code>||</code> operator once
testString: 'assert(code.match(/\|\|/g).length === 1, ''You should use the <code>||</code> operator once'');'
- text: You should only have one <code>if</code> statement
testString: 'assert(code.match(/if/g).length === 1, ''You should only have one <code>if</code> statement'');'
- text: <code>testLogicalOr(0)</code> should return "Outside"
testString: 'assert(testLogicalOr(0) === "Outside", ''<code>testLogicalOr(0)</code> should return "Outside"'');'
- text: <code>testLogicalOr(9)</code> should return "Outside"
testString: 'assert(testLogicalOr(9) === "Outside", ''<code>testLogicalOr(9)</code> should return "Outside"'');'
- text: <code>testLogicalOr(10)</code> should return "Inside"
testString: 'assert(testLogicalOr(10) === "Inside", ''<code>testLogicalOr(10)</code> should return "Inside"'');'
- text: <code>testLogicalOr(15)</code> should return "Inside"
testString: 'assert(testLogicalOr(15) === "Inside", ''<code>testLogicalOr(15)</code> should return "Inside"'');'
- text: <code>testLogicalOr(19)</code> should return "Inside"
testString: 'assert(testLogicalOr(19) === "Inside", ''<code>testLogicalOr(19)</code> should return "Inside"'');'
- text: <code>testLogicalOr(20)</code> should return "Inside"
testString: 'assert(testLogicalOr(20) === "Inside", ''<code>testLogicalOr(20)</code> should return "Inside"'');'
- text: <code>testLogicalOr(21)</code> should return "Outside"
testString: 'assert(testLogicalOr(21) === "Outside", ''<code>testLogicalOr(21)</code> should return "Outside"'');'
- text: <code>testLogicalOr(25)</code> should return "Outside"
testString: 'assert(testLogicalOr(25) === "Outside", ''<code>testLogicalOr(25)</code> should return "Outside"'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function testLogicalOr(val) {
// Only change code below this line
if (val) {
return "Outside";
}
if (val) {
return "Outside";
}
// Only change code above this line
return "Inside";
}
// Change this value to test
testLogicalOr(15);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function testLogicalOr(val) {
if (val < 10 || val > 20) {
return "Outside";
}
return "Inside";
}
```
</section>

View File

@ -0,0 +1,87 @@
---
id: 56533eb9ac21ba0edf2244af
title: Compound Assignment With Augmented Addition
challengeType: 1
---
## Description
<section id='description'>
In programming, it is common to use assignments to modify the contents of a variable. Remember that everything to the right of the equals sign is evaluated first, so we can say:
<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>
</section>
## Instructions
<section id='instructions'>
Convert the assignments for <code>a</code>, <code>b</code>, and <code>c</code> to use the <code>+=</code> operator.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>a</code> should equal <code>15</code>
testString: 'assert(a === 15, ''<code>a</code> should equal <code>15</code>'');'
- text: <code>b</code> should equal <code>26</code>
testString: 'assert(b === 26, ''<code>b</code> should equal <code>26</code>'');'
- text: <code>c</code> should equal <code>19</code>
testString: 'assert(c === 19, ''<code>c</code> should equal <code>19</code>'');'
- text: You should use the <code>+=</code> operator for each variable
testString: 'assert(code.match(/\+=/g).length === 3, ''You should use the <code>+=</code> operator for each variable'');'
- text: Do not modify the code above the line
testString: 'assert(/var a = 3;/.test(code) && /var b = 17;/.test(code) && /var c = 12;/.test(code), ''Do not modify the code above the line'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var a = 3;
var b = 17;
var c = 12;
// Only modify code below this line
a = a + 12;
b = 9 + b;
c = c + 7;
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var a = 3;
var b = 17;
var c = 12;
a += 12;
b += 9;
c += 7;
```
</section>

View File

@ -0,0 +1,86 @@
---
id: 56533eb9ac21ba0edf2244b2
title: Compound Assignment With Augmented Division
challengeType: 1
---
## Description
<section id='description'>
The <code>/=</code> operator divides a variable by another number.
<code>myVar = myVar / 5;</code>
Will divide <code>myVar</code> by <code>5</code>. This can be rewritten as:
<code>myVar /= 5;</code>
</section>
## Instructions
<section id='instructions'>
Convert the assignments for <code>a</code>, <code>b</code>, and <code>c</code> to use the <code>/=</code> operator.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>a</code> should equal <code>4</code>
testString: 'assert(a === 4, ''<code>a</code> should equal <code>4</code>'');'
- text: <code>b</code> should equal <code>27</code>
testString: 'assert(b === 27, ''<code>b</code> should equal <code>27</code>'');'
- text: <code>c</code> should equal <code>3</code>
testString: 'assert(c === 3, ''<code>c</code> should equal <code>3</code>'');'
- text: You should use the <code>/=</code> operator for each variable
testString: 'assert(code.match(/\/=/g).length === 3, ''You should use the <code>/=</code> operator for each variable'');'
- text: Do not modify the code above the line
testString: 'assert(/var a = 48;/.test(code) && /var b = 108;/.test(code) && /var c = 33;/.test(code), ''Do not modify the code above the line'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var a = 48;
var b = 108;
var c = 33;
// Only modify code below this line
a = a / 12;
b = b / 4;
c = c / 11;
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var a = 48;
var b = 108;
var c = 33;
a /= 12;
b /= 4;
c /= 11;
```
</section>

View File

@ -0,0 +1,87 @@
---
id: 56533eb9ac21ba0edf2244b1
title: Compound Assignment With Augmented Multiplication
challengeType: 1
---
## Description
<section id='description'>
The <code>*=</code> operator multiplies a variable by a number.
<code>myVar = myVar * 5;</code>
will multiply <code>myVar</code> by <code>5</code>. This can be rewritten as:
<code>myVar *= 5;</code>
</section>
## Instructions
<section id='instructions'>
Convert the assignments for <code>a</code>, <code>b</code>, and <code>c</code> to use the <code>*=</code> operator.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>a</code> should equal <code>25</code>
testString: 'assert(a === 25, ''<code>a</code> should equal <code>25</code>'');'
- text: <code>b</code> should equal <code>36</code>
testString: 'assert(b === 36, ''<code>b</code> should equal <code>36</code>'');'
- text: <code>c</code> should equal <code>46</code>
testString: 'assert(c === 46, ''<code>c</code> should equal <code>46</code>'');'
- text: You should use the <code>*=</code> operator for each variable
testString: 'assert(code.match(/\*=/g).length === 3, ''You should use the <code>*=</code> operator for each variable'');'
- text: Do not modify the code above the line
testString: 'assert(/var a = 5;/.test(code) && /var b = 12;/.test(code) && /var c = 4\.6;/.test(code), ''Do not modify the code above the line'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var a = 5;
var b = 12;
var c = 4.6;
// Only modify code below this line
a = a * 5;
b = 3 * b;
c = c * 10;
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var a = 5;
var b = 12;
var c = 4.6;
a *= 5;
b *= 3;
c *= 10;
```
</section>

View File

@ -0,0 +1,89 @@
---
id: 56533eb9ac21ba0edf2244b0
title: Compound Assignment With Augmented Subtraction
challengeType: 1
---
## Description
<section id='description'>
Like the <code>+=</code> operator, <code>-=</code> subtracts a number from a variable.
<code>myVar = myVar - 5;</code>
will subtract <code>5</code> from <code>myVar</code>. This can be rewritten as:
<code>myVar -= 5;</code>
</section>
## Instructions
<section id='instructions'>
Convert the assignments for <code>a</code>, <code>b</code>, and <code>c</code> to use the <code>-=</code> operator.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>a</code> should equal <code>5</code>
testString: 'assert(a === 5, ''<code>a</code> should equal <code>5</code>'');'
- text: <code>b</code> should equal <code>-6</code>
testString: 'assert(b === -6, ''<code>b</code> should equal <code>-6</code>'');'
- text: <code>c</code> should equal <code>2</code>
testString: 'assert(c === 2, ''<code>c</code> should equal <code>2</code>'');'
- text: You should use the <code>-=</code> operator for each variable
testString: 'assert(code.match(/-=/g).length === 3, ''You should use the <code>-=</code> operator for each variable'');'
- text: Do not modify the code above the line
testString: 'assert(/var a = 11;/.test(code) && /var b = 9;/.test(code) && /var c = 3;/.test(code), ''Do not modify the code above the line'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var a = 11;
var b = 9;
var c = 3;
// Only modify code below this line
a = a - 6;
b = b - 15;
c = c - 1;
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var a = 11;
var b = 9;
var c = 3;
a -= 6;
b -= 15;
c -= 1;
```
</section>

View File

@ -0,0 +1,77 @@
---
id: 56533eb9ac21ba0edf2244b7
title: Concatenating Strings with Plus Operator
challengeType: 1
---
## Description
<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>
<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>
## Instructions
<section id='instructions'>
Build <code>myStr</code> from the strings <code>"This is the start. "</code> and <code>"This is the end."</code> using the <code>+</code> operator.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>myStr</code> should have a value of <code>This is the start. This is the end.</code>
testString: 'assert(myStr === "This is the start. This is the end.", ''<code>myStr</code> should have a value of <code>This is the start. This is the end.</code>'');'
- text: Use the <code>+</code> operator to build <code>myStr</code>
testString: 'assert(code.match(/(["'']).*(["''])\s*\+\s*(["'']).*(["''])/g).length > 1, ''Use the <code>+</code> operator to build <code>myStr</code>'');'
- text: <code>myStr</code> should be created using the <code>var</code> keyword.
testString: 'assert(/var\s+myStr/.test(code), ''<code>myStr</code> should be created using the <code>var</code> keyword.'');'
- text: Make sure to assign the result to the <code>myStr</code> variable.
testString: 'assert(/myStr\s*=/.test(code), ''Make sure to assign the result to the <code>myStr</code> variable.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Example
var ourStr = "I come first. " + "I come second.";
// Only change code below this line
var myStr;
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var ourStr = "I come first. " + "I come second.";
var myStr = "This is the start. " + "This is the end.";
```
</section>

View File

@ -0,0 +1,75 @@
---
id: 56533eb9ac21ba0edf2244b8
title: Concatenating Strings with the Plus Equals Operator
challengeType: 1
---
## Description
<section id='description'>
We can also use the <code>+=</code> operator to <dfn>concatenate</dfn> a string onto the end of an existing string variable. This can be very helpful to break a long string over several lines.
<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>
## Instructions
<section id='instructions'>
Build <code>myStr</code> over several lines by concatenating these two strings: <code>"This is the first sentence. "</code> and <code>"This is the second sentence."</code> using the <code>+=</code> operator. Use the <code>+=</code> operator similar to how it is shown in the editor. Start by assigning the first string to <code>myStr</code>, then add on the second string.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>myStr</code> should have a value of <code>This is the first sentence. This is the second sentence.</code>
testString: 'assert(myStr === "This is the first sentence. This is the second sentence.", ''<code>myStr</code> should have a value of <code>This is the first sentence. This is the second sentence.</code>'');'
- text: Use the <code>+=</code> operator to build <code>myStr</code>
testString: 'assert(code.match(/\w\s*\+=\s*["'']/g).length > 1 && code.match(/\w\s*\=\s*["'']/g).length > 1, ''Use the <code>+=</code> operator to build <code>myStr</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Example
var ourStr = "I come first. ";
ourStr += "I come second.";
// Only change code below this line
var myStr;
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var ourStr = "I come first. ";
ourStr += "I come second.";
var myStr = "This is the first sentence. ";
myStr += "This is the second sentence.";
```
</section>

View File

@ -0,0 +1,71 @@
---
id: 56533eb9ac21ba0edf2244b9
title: Constructing Strings with Variables
challengeType: 1
---
## Description
<section id='description'>
Sometimes you will need to build a string, <a href="https://en.wikipedia.org/wiki/Mad_Libs" target="_blank">Mad Libs</a> style. By using the concatenation operator (<code>+</code>), you can insert one or more variables into a string you're building.
</section>
## Instructions
<section id='instructions'>
Set <code>myName</code> to a string equal to your name and build <code>myStr</code> with <code>myName</code> between the strings <code>"My name is "</code> and <code>" and I am well!"</code>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>myName</code> should be set to a string at least 3 characters long
testString: 'assert(typeof myName !== ''undefined'' && myName.length > 2, ''<code>myName</code> should be set to a string at least 3 characters long'');'
- text: Use two <code>+</code> operators to build <code>myStr</code> with <code>myName</code> inside it
testString: 'assert(code.match(/["'']\s*\+\s*myName\s*\+\s*["'']/g).length > 0, ''Use two <code>+</code> operators to build <code>myStr</code> with <code>myName</code> inside it'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Example
var ourName = "freeCodeCamp";
var ourStr = "Hello, our name is " + ourName + ", how are you?";
// Only change code below this line
var myName;
var myStr;
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var myName = "Bob";
var myStr = "My name is " + myName + " and I am well!";
```
</section>

View File

@ -0,0 +1,88 @@
---
id: 56105e7b514f539506016a5e
title: Count Backwards With a For Loop
challengeType: 1
---
## Description
<section id='description'>
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>
<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>
## Instructions
<section id='instructions'>
Push the odd numbers from 9 through 1 to <code>myArray</code> using a <code>for</code> loop.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: You should be using a <code>for</code> loop for this.
testString: 'assert(code.match(/for\s*\(/g).length > 1, ''You should be using a <code>for</code> loop for this.'');'
- text: You should be using the array method <code>push</code>.
testString: 'assert(code.match(/myArray.push/), ''You should be using the array method <code>push</code>.'');'
- text: '<code>myArray</code> should equal <code>[9,7,5,3,1]</code>.'
testString: 'assert.deepEqual(myArray, [9,7,5,3,1], ''<code>myArray</code> should equal <code>[9,7,5,3,1]</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Example
var ourArray = [];
for (var i = 10; i > 0; i -= 2) {
ourArray.push(i);
}
// Setup
var myArray = [];
// Only change code below this line.
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var ourArray = [];
for (var i = 10; i > 0; i -= 2) {
ourArray.push(i);
}
var myArray = [];
for (var i = 9; i > 0; i -= 2) {
myArray.push(i);
}
```
</section>

View File

@ -0,0 +1,103 @@
---
id: 565bbe00e9cc8ac0725390f4
title: Counting Cards
challengeType: 1
---
## Description
<section id='description'>
In the casino game Blackjack, a player can gain an advantage over the house by keeping track of the relative number of high and low cards remaining in the deck. This is called <a href='https://en.wikipedia.org/wiki/Card_counting' target='_blank'>Card Counting</a>.
Having more high cards remaining in the deck favors the player. Each card is assigned a value according to the table below. When the count is positive, the player should bet high. When the count is zero or negative, the player should bet low.
<table class="table table-striped"><thead><tr><th>Count Change</th><th>Cards</th></tr></thead><tbody><tr><td>+1</td><td>2, 3, 4, 5, 6</td></tr><tr><td>0</td><td>7, 8, 9</td></tr><tr><td>-1</td><td>10, 'J', 'Q', 'K', 'A'</td></tr></tbody></table>
You will write a card counting function. It will receive a <code>card</code> parameter, which can be a number or a string, and increment or decrement the global <code>count</code> variable according to the card's value (see table). The function will then return a string with the current count and the string <code>Bet</code> if the count is positive, or <code>Hold</code> if the count is zero or negative. The current count and the player's decision (<code>Bet</code> or <code>Hold</code>) should be separated by a single space.
<strong>Example Output</strong><br><code>-3 Hold</code><br><code>5 Bet</code>
<strong>Hint</strong><br>Do NOT reset <code>count</code> to 0 when value is 7, 8, or 9.<br>Do NOT return an array.<br>Do NOT include quotes (single or double) in the output.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 'Cards Sequence 2, 3, 4, 5, 6 should return <code>5 Bet</code>'
testString: 'assert((function(){ count = 0; cc(2);cc(3);cc(4);cc(5);var out = cc(6); if(out === "5 Bet") {return true;} return false; })(), ''Cards Sequence 2, 3, 4, 5, 6 should return <code>5 Bet</code>'');'
- text: 'Cards Sequence 7, 8, 9 should return <code>0 Hold</code>'
testString: 'assert((function(){ count = 0; cc(7);cc(8);var out = cc(9); if(out === "0 Hold") {return true;} return false; })(), ''Cards Sequence 7, 8, 9 should return <code>0 Hold</code>'');'
- text: 'Cards Sequence 10, J, Q, K, A should return <code>-5 Hold</code>'
testString: 'assert((function(){ count = 0; cc(10);cc(''J'');cc(''Q'');cc(''K'');var out = cc(''A''); if(out === "-5 Hold") {return true;} return false; })(), ''Cards Sequence 10, J, Q, K, A should return <code>-5 Hold</code>'');'
- text: 'Cards Sequence 3, 7, Q, 8, A should return <code>-1 Hold</code>'
testString: 'assert((function(){ count = 0; cc(3);cc(7);cc(''Q'');cc(8);var out = cc(''A''); if(out === "-1 Hold") {return true;} return false; })(), ''Cards Sequence 3, 7, Q, 8, A should return <code>-1 Hold</code>'');'
- text: 'Cards Sequence 2, J, 9, 2, 7 should return <code>1 Bet</code>'
testString: 'assert((function(){ count = 0; cc(2);cc(''J'');cc(9);cc(2);var out = cc(7); if(out === "1 Bet") {return true;} return false; })(), ''Cards Sequence 2, J, 9, 2, 7 should return <code>1 Bet</code>'');'
- text: 'Cards Sequence 2, 2, 10 should return <code>1 Bet</code>'
testString: 'assert((function(){ count = 0; cc(2);cc(2);var out = cc(10); if(out === "1 Bet") {return true;} return false; })(), ''Cards Sequence 2, 2, 10 should return <code>1 Bet</code>'');'
- text: 'Cards Sequence 3, 2, A, 10, K should return <code>-1 Hold</code>'
testString: 'assert((function(){ count = 0; cc(3);cc(2);cc(''A'');cc(10);var out = cc(''K''); if(out === "-1 Hold") {return true;} return false; })(), ''Cards Sequence 3, 2, A, 10, K should return <code>-1 Hold</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var count = 0;
function cc(card) {
// Only change code below this line
return "Change Me";
// Only change code above this line
}
// Add/remove calls to test your function.
// Note: Only the last will display
cc(2); cc(3); cc(7); cc('K'); cc('A');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var count = 0;
function cc(card) {
switch(card) {
case 2:
case 3:
case 4:
case 5:
case 6:
count++;
break;
case 10:
case 'J':
case 'Q':
case 'K':
case 'A':
count--;
}
if(count > 0) {
return count + " Bet";
} else {
return count + " Hold";
}
}
```
</section>

View File

@ -0,0 +1,67 @@
---
id: cf1391c1c11feddfaeb4bdef
title: Create Decimal Numbers with JavaScript
challengeType: 1
---
## Description
<section id='description'>
We can store decimal numbers in variables too. Decimal numbers are sometimes referred to as <dfn>floating point</dfn> numbers or <dfn>floats</dfn>.
<strong>Note</strong><br>Not all real numbers can accurately be represented in <dfn>floating point</dfn>. This can lead to rounding errors. <a href="https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems" target="_blank">Details Here</a>.
</section>
## Instructions
<section id='instructions'>
Create a variable <code>myDecimal</code> and give it a decimal value with a fractional part (e.g. <code>5.7</code>).
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>myDecimal</code> should be a number.
testString: 'assert(typeof myDecimal === "number", ''<code>myDecimal</code> should be a number.'');'
- text: <code>myDecimal</code> should have a decimal point
testString: 'assert(myDecimal % 1 != 0, ''<code>myDecimal</code> should have a decimal point''); '
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var ourDecimal = 5.7;
// Only change code below this line
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var myDecimal = 9.9;
```
</section>

View File

@ -0,0 +1,72 @@
---
id: bd7123c9c443eddfaeb5bdef
title: Declare JavaScript Variables
challengeType: 1
---
## Description
<section id='description'>
In computer science, <dfn>data</dfn> is anything that is meaningful to the computer. JavaScript provides seven different <dfn>data types</dfn> which are <code>undefined</code>, <code>null</code>, <code>boolean</code>, <code>string</code>, <code>symbol</code>, <code>number</code>, and <code>object</code>.
For example, computers distinguish between numbers, such as the number <code>12</code>, and <code>strings</code>, such as <code>"12"</code>, <code>"dog"</code>, or <code>"123 cats"</code>, which are collections of characters. Computers can perform mathematical operations on a number, but not on a string.
<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>
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>
## Instructions
<section id='instructions'>
Use the <code>var</code> keyword to create a variable called <code>myName</code>.
<strong>Hint</strong><br>Look at the <code>ourName</code> example if you get stuck.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 'You should declare <code>myName</code> with the <code>var</code> keyword, ending with a semicolon'
testString: 'assert(/var\s+myName\s*;/.test(code), ''You should declare <code>myName</code> with the <code>var</code> keyword, ending with a semicolon'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Example
var ourName;
// Declare myName below this line
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var myName;
```
</section>

View File

@ -0,0 +1,71 @@
---
id: bd7123c9c444eddfaeb5bdef
title: Declare String Variables
challengeType: 1
---
## Description
<section id='description'>
Previously we have used the code
<code>var myName = "your name";</code>
<code>"your name"</code> is called a <dfn>string</dfn> <dfn>literal</dfn>. It is a string because it is a series of zero or more characters enclosed in single or double quotes.
</section>
## Instructions
<section id='instructions'>
Create two new <code>string</code> variables: <code>myFirstName</code> and <code>myLastName</code> and assign them the values of your first and last name, respectively.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>myFirstName</code> should be a string with at least one character in it.
testString: 'assert((function(){if(typeof myFirstName !== "undefined" && typeof myFirstName === "string" && myFirstName.length > 0){return true;}else{return false;}})(), ''<code>myFirstName</code> should be a string with at least one character in it.'');'
- text: <code>myLastName</code> should be a string with at least one character in it.
testString: 'assert((function(){if(typeof myLastName !== "undefined" && typeof myLastName === "string" && myLastName.length > 0){return true;}else{return false;}})(), ''<code>myLastName</code> should be a string with at least one character in it.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Example
var firstName = "Alan";
var lastName = "Turing";
// Only change code below this line
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var myFirstName = "Alan";
var myLastName = "Turing";
```
</section>

View File

@ -0,0 +1,75 @@
---
id: 56533eb9ac21ba0edf2244ad
title: Decrement a Number with JavaScript
challengeType: 1
---
## Description
<section id='description'>
You can easily <dfn>decrement</dfn> or decrease a variable by one with the <code>--</code> operator.
<code>i--;</code>
is the equivalent of
<code>i = i - 1;</code>
<strong>Note</strong><br>The entire line becomes <code>i--;</code>, eliminating the need for the equal sign.
</section>
## Instructions
<section id='instructions'>
Change the code to use the <code>--</code> operator on <code>myVar</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>myVar</code> should equal <code>10</code>
testString: 'assert(myVar === 10, ''<code>myVar</code> should equal <code>10</code>'');'
- text: <code>myVar = myVar - 1;</code> should be changed
testString: 'assert(/var\s*myVar\s*=\s*11;\s*\/*.*\s*([-]{2}\s*myVar|myVar\s*[-]{2});/.test(code), ''<code>myVar = myVar - 1;</code> should be changed'');'
- text: Use the <code>--</code> operator on <code>myVar</code>
testString: 'assert(/[-]{2}\s*myVar|myVar\s*[-]{2}/.test(code), ''Use the <code>--</code> operator on <code>myVar</code>'');'
- text: Do not change code above the line
testString: 'assert(/var myVar = 11;/.test(code), ''Do not change code above the line'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var myVar = 11;
// Only change code below this line
myVar = myVar - 1;
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var myVar = 11;
myVar--;
```
</section>

View File

@ -0,0 +1,99 @@
---
id: 56bbb991ad1ed5201cd392d3
title: Delete Properties from a JavaScript Object
challengeType: 1
---
## Description
<section id='description'>
We can also delete properties from objects like this:
<code>delete ourDog.bark;</code>
</section>
## Instructions
<section id='instructions'>
Delete the <code>"tails"</code> property from <code>myDog</code>. You may use either dot or bracket notation.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Delete the property <code>"tails"</code> from <code>myDog</code>.
testString: 'assert(typeof myDog === "object" && myDog.tails === undefined, ''Delete the property <code>"tails"</code> from <code>myDog</code>.'');'
- text: Do not modify the <code>myDog</code> setup
testString: 'assert(code.match(/"tails": 1/g).length > 1, ''Do not modify the <code>myDog</code> setup'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Example
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"],
"bark": "bow-wow"
};
delete ourDog.bark;
// Setup
var myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"],
"bark": "woof"
};
// Only change code below this line.
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"],
"bark": "bow-wow"
};
var myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"],
"bark": "woof"
};
delete myDog.tails;
```
</section>

View File

@ -0,0 +1,64 @@
---
id: bd7993c9ca9feddfaeb7bdef
title: Divide One Decimal by Another with JavaScript
challengeType: 1
---
## Description
<section id='description'>
Now let's divide one decimal by another.
</section>
## Instructions
<section id='instructions'>
Change the <code>0.0</code> so that <code>quotient</code> will equal to <code>2.2</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The variable <code>quotient</code> should equal <code>2.2</code>
testString: 'assert(quotient === 2.2, ''The variable <code>quotient</code> should equal <code>2.2</code>'');'
- text: You should use the <code>/</code> operator to divide 4.4 by 2
testString: 'assert(/4\.40*\s*\/\s*2\.*0*/.test(code), ''You should use the <code>/</code> operator to divide 4.4 by 2'');'
- text: The quotient variable should only be assigned once
testString: 'assert(code.match(/quotient/g).length === 1, ''The quotient variable should only be assigned once'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var quotient = 0.0 / 2.0; // Fix this line
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,69 @@
---
id: cf1111c1c11feddfaeb6bdef
title: Divide One Number by Another with JavaScript
challengeType: 1
---
## Description
<section id='description'>
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>
</section>
## Instructions
<section id='instructions'>
Change the <code>0</code> so that the <code>quotient</code> is equal to <code>2</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Make the variable <code>quotient</code> equal to 2.
testString: 'assert(quotient === 2, ''Make the variable <code>quotient</code> equal to 2.'');'
- text: Use the <code>/</code> operator
testString: 'assert(/\d+\s*\/\s*\d+/.test(code), ''Use the <code>/</code> operator'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var quotient = 66 / 0;
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var quotient = 66 / 33;
```
</section>

View File

@ -0,0 +1,78 @@
---
id: 56533eb9ac21ba0edf2244b6
title: Escape Sequences in Strings
challengeType: 1
---
## Description
<section id='description'>
Quotes are not the only characters that can be <dfn>escaped</dfn> inside a string. There are two reasons to use escaping characters: First is to allow you to use characters you might not otherwise be able to type out, such as a backspace. Second is to allow you to represent multiple quotes in a string without JavaScript misinterpreting what you mean. We learned this in the previous challenge.
<table class="table table-striped"><thead><tr><th>Code</th><th>Output</th></tr></thead><tbody><tr><td><code>\'</code></td><td>single quote</td></tr><tr><td><code>\"</code></td><td>double quote</td></tr><tr><td><code>\\</code></td><td>backslash</td></tr><tr><td><code>\n</code></td><td>newline</td></tr><tr><td><code>\r</code></td><td>carriage return</td></tr><tr><td><code>\t</code></td><td>tab</td></tr><tr><td><code>\b</code></td><td>backspace</td></tr><tr><td><code>\f</code></td><td>form feed</td></tr></tbody></table>
<em>Note that the backslash itself must be escaped in order to display as a backslash.</em>
</section>
## Instructions
<section id='instructions'>
Assign the following three lines of text into the single variable <code>myStr</code> using escape sequences.
<blockquote>FirstLine<br/>&nbsp;&nbsp;&nbsp;&nbsp;\SecondLine<br/>ThirdLine</blockquote>
You will need to use escape sequences to insert special characters correctly. You will also need to follow the spacing as it looks above, with no spaces between escape sequences or words.
Here is the text with the escape sequences written out.
<q>FirstLine<code>newline</code><code>tab</code><code>backslash</code>SecondLine<code>newline</code>ThirdLine</q>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>myStr</code> should not contain any spaces
testString: 'assert(!/ /.test(myStr), ''<code>myStr</code> should not contain any spaces'');'
- text: '<code>myStr</code> should contain the strings <code>FirstLine</code>, <code>SecondLine</code> and <code>ThirdLine</code> (remember case sensitivity)'
testString: 'assert(/FirstLine/.test(myStr) && /SecondLine/.test(myStr) && /ThirdLine/.test(myStr), ''<code>myStr</code> should contain the strings <code>FirstLine</code>, <code>SecondLine</code> and <code>ThirdLine</code> (remember case sensitivity)'');'
- text: <code>FirstLine</code> should be followed by the newline character <code>\n</code>
testString: 'assert(/FirstLine\n/.test(myStr), ''<code>FirstLine</code> should be followed by the newline character <code>\n</code>'');'
- text: <code>myStr</code> should contain a tab character <code>\t</code> which follows a newline character
testString: 'assert(/\n\t/.test(myStr), ''<code>myStr</code> should contain a tab character <code>\t</code> which follows a newline character'');'
- text: <code>SecondLine</code> should be preceded by the backslash character <code>\\</code>
testString: 'assert(/\SecondLine/.test(myStr), ''<code>SecondLine</code> should be preceded by the backslash character <code>\\</code>'');'
- text: There should be a newline character between <code>SecondLine</code> and <code>ThirdLine</code>
testString: 'assert(/SecondLine\nThirdLine/.test(myStr), ''There should be a newline character between <code>SecondLine</code> and <code>ThirdLine</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var myStr; // Change this line
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var myStr = "FirstLine\n\t\\SecondLine\nThirdLine";
```
</section>

View File

@ -0,0 +1,69 @@
---
id: 56533eb9ac21ba0edf2244b5
title: Escaping Literal Quotes in Strings
challengeType: 1
---
## Description
<section id='description'>
When you are defining a string you must start and end with a single or double quote. What happens when you need a literal quote: <code>"</code> or <code>'</code> inside of your string?
In JavaScript, you can <dfn>escape</dfn> a quote from considering it as an end of string quote by placing a <dfn>backslash</dfn> (<code>\</code>) in front of the quote.
<code>var sampleStr = "Alan said, \"Peter is learning JavaScript\".";</code>
This signals to JavaScript that the following quote is not the end of the string, but should instead appear inside the string. So if you were to print this to the console, you would get:
<code>Alan said, "Peter is learning JavaScript".</code>
</section>
## Instructions
<section id='instructions'>
Use <dfn>backslashes</dfn> to assign a string to the <code>myStr</code> variable so that if you were to print it to the console, you would see:
<code>I am a "double quoted" string inside "double quotes".</code>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 'You should use two double quotes (<code>&quot;</code>) and four escaped double quotes (<code>&#92;&quot;</code>).'
testString: 'assert(code.match(/\\"/g).length === 4 && code.match(/[^\\]"/g).length === 2, ''You should use two double quotes (<code>&quot;</code>) and four escaped double quotes (<code>&#92;&quot;</code>).'');'
- text: 'Variable myStr should contain the string: <code>I am a "double quoted" string inside "double quotes".</code>'
testString: 'assert(myStr === "I am a \"double quoted\" string inside \"double quotes\".", ''Variable myStr should contain the string: <code>I am a "double quoted" string inside "double quotes".</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var myStr = ""; // Change this line
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var myStr = "I am a \"double quoted\" string inside \"double quotes\".";
```
</section>

View File

@ -0,0 +1,84 @@
---
id: bd7123c9c448eddfaeb5bdef
title: Find the Length of a String
challengeType: 1
---
## Description
<section id='description'>
You can find the length of a <code>String</code> value by writing <code>.length</code> after the string variable or string literal.
<code>"Alan Peter".length; // 10</code>
For example, if we created a variable <code>var firstName = "Charles"</code>, we could find out how long the string <code>"Charles"</code> is by using the <code>firstName.length</code> property.
</section>
## Instructions
<section id='instructions'>
Use the <code>.length</code> property to count the number of characters in the <code>lastName</code> variable and assign it to <code>lastNameLength</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>lastNameLength</code> should be equal to eight.
testString: 'assert((function(){if(typeof lastNameLength !== "undefined" && typeof lastNameLength === "number" && lastNameLength === 8){return true;}else{return false;}})(), ''<code>lastNameLength</code> should be equal to eight.'');'
- text: 'You should be getting the length of <code>lastName</code> by using <code>.length</code> like this: <code>lastName.length</code>.'
testString: 'assert((function(){if(code.match(/\.length/gi) && code.match(/\.length/gi).length >= 2 && code.match(/var lastNameLength \= 0;/gi) && code.match(/var lastNameLength \= 0;/gi).length >= 1){return true;}else{return false;}})(), ''You should be getting the length of <code>lastName</code> by using <code>.length</code> like this: <code>lastName.length</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Example
var firstNameLength = 0;
var firstName = "Ada";
firstNameLength = firstName.length;
// Setup
var lastNameLength = 0;
var lastName = "Lovelace";
// Only change code below this line.
lastNameLength = lastName;
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var firstNameLength = 0;
var firstName = "Ada";
firstNameLength = firstName.length;
var lastNameLength = 0;
var lastName = "Lovelace";
lastNameLength = lastName.length;
```
</section>

View File

@ -0,0 +1,72 @@
---
id: 56533eb9ac21ba0edf2244ae
title: Finding a Remainder in JavaScript
challengeType: 1
---
## Description
<section id='description'>
The <dfn>remainder</dfn> operator <code>%</code> gives the remainder of the division of two numbers.
<strong>Example</strong>
<blockquote>5 % 2 = 1 because<br>Math.floor(5 / 2) = 2 (Quotient)<br>2 * 2 = 4<br>5 - 4 = 1 (Remainder)</blockquote>
<strong>Usage</strong><br>In mathematics, a number can be checked to be even or odd by checking the remainder of the division of the number by <code>2</code>.
<blockquote>17 % 2 = 1 (17 is Odd)<br>48 % 2 = 0 (48 is Even)</blockquote>
<strong>Note</strong><br>The <dfn>remainder</dfn> operator is sometimes incorrectly referred to as the "modulus" operator. It is very similar to modulus, but does not work properly with negative numbers.
</section>
## Instructions
<section id='instructions'>
Set <code>remainder</code> equal to the remainder of <code>11</code> divided by <code>3</code> using the <dfn>remainder</dfn> (<code>%</code>) operator.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The variable <code>remainder</code> should be initialized
testString: 'assert(/var\s+?remainder/.test(code), ''The variable <code>remainder</code> should be initialized'');'
- text: The value of <code>remainder</code> should be <code>2</code>
testString: 'assert(remainder === 2, ''The value of <code>remainder</code> should be <code>2</code>'');'
- text: You should use the <code>%</code> operator
testString: 'assert(/\s+?remainder\s*?=\s*?.*%.*;/.test(code), ''You should use the <code>%</code> operator'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Only change code below this line
var remainder;
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var remainder = 11 % 3;
```
</section>

View File

@ -0,0 +1,75 @@
---
id: cf1111c1c11feddfaeb9bdef
title: Generate Random Fractions with JavaScript
challengeType: 1
---
## Description
<section id='description'>
Random numbers are useful for creating random behavior.
JavaScript has a <code>Math.random()</code> function that generates a random decimal number between <code>0</code> (inclusive) and not quite up to <code>1</code> (exclusive). Thus <code>Math.random()</code> can return a <code>0</code> but never quite return a <code>1</code>
<strong>Note</strong><br>Like <a href='storing-values-with-the-assignment-operator' target='_blank'>Storing Values with the Equal Operator</a>, all function calls will be resolved before the <code>return</code> executes, so we can <code>return</code> the value of the <code>Math.random()</code> function.
</section>
## Instructions
<section id='instructions'>
Change <code>randomFraction</code> to return a random number instead of returning <code>0</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>randomFraction</code> should return a random number.
testString: 'assert(typeof randomFraction() === "number", ''<code>randomFraction</code> should return a random number.'');'
- text: The number returned by <code>randomFraction</code> should be a decimal.
testString: 'assert((randomFraction()+''''). match(/\./g), ''The number returned by <code>randomFraction</code> should be a decimal.'');'
- text: You should be using <code>Math.random</code> to generate the random decimal number.
testString: 'assert(code.match(/Math\.random/g).length >= 0, ''You should be using <code>Math.random</code> to generate the random decimal number.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function randomFraction() {
// Only change code below this line.
return 0;
// Only change code above this line.
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
function randomFraction() {
return Math.random();
}
```
</section>

View File

@ -0,0 +1,81 @@
---
id: cf1111c1c12feddfaeb1bdef
title: Generate Random Whole Numbers with JavaScript
challengeType: 1
---
## Description
<section id='description'>
It's great that we can generate random decimal numbers, but it's even more useful if we use it to generate random whole numbers.
<ol><li>Use <code>Math.random()</code> to generate a random decimal.</li><li>Multiply that random decimal by <code>20</code>.</li><li>Use another function, <code>Math.floor()</code> to round the number down to its nearest whole number.</li></ol>
Remember that <code>Math.random()</code> can never quite return a <code>1</code> and, because we're rounding down, it's impossible to actually get <code>20</code>. This technique will give us a whole number between <code>0</code> and <code>19</code>.
Putting everything together, this is what our code looks like:
<code>Math.floor(Math.random() * 20);</code>
We are calling <code>Math.random()</code>, multiplying the result by 20, then passing the value to <code>Math.floor()</code> function to round the value down to the nearest whole number.
</section>
## Instructions
<section id='instructions'>
Use this technique to generate and return a random whole number between <code>0</code> and <code>9</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The result of <code>randomWholeNum</code> should be a whole number.
testString: 'assert(typeof randomWholeNum() === "number" && (function(){var r = randomWholeNum();return Math.floor(r) === r;})(), ''The result of <code>randomWholeNum</code> should be a whole number.'');'
- text: You should be using <code>Math.random</code> to generate a random number.
testString: 'assert(code.match(/Math.random/g).length > 1, ''You should be using <code>Math.random</code> to generate a random number.'');'
- text: You should have multiplied the result of <code>Math.random</code> by 10 to make it a number that is between zero and nine.
testString: 'assert(code.match(/\s*?Math.random\s*?\(\s*?\)\s*?\*\s*?10[\D]\s*?/g) || code.match(/\s*?10\s*?\*\s*?Math.random\s*?\(\s*?\)\s*?/g), ''You should have multiplied the result of <code>Math.random</code> by 10 to make it a number that is between zero and nine.'');'
- text: You should use <code>Math.floor</code> to remove the decimal part of the number.
testString: 'assert(code.match(/Math.floor/g).length > 1, ''You should use <code>Math.floor</code> to remove the decimal part of the number.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var randomNumberBetween0and19 = Math.floor(Math.random() * 20);
function randomWholeNum() {
// Only change code below this line.
return Math.random();
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var randomNumberBetween0and19 = Math.floor(Math.random() * 20);
function randomWholeNum() {
return Math.floor(Math.random() * 10);
}
```
</section>

View File

@ -0,0 +1,88 @@
---
id: cf1111c1c12feddfaeb2bdef
title: Generate Random Whole Numbers within a Range
challengeType: 1
---
## Description
<section id='description'>
Instead of generating a random number between zero and a given number like we did before, we can generate a random number that falls within a range of two specific numbers.
To do this, we'll define a minimum number <code>min</code> and a maximum number <code>max</code>.
Here's the formula we'll use. Take a moment to read it and try to understand what this code is doing:
<code>Math.floor(Math.random() * (max - min + 1)) + min</code>
</section>
## Instructions
<section id='instructions'>
Create a function called <code>randomRange</code> that takes a range <code>myMin</code> and <code>myMax</code> and returns a random number that's greater than or equal to <code>myMin</code>, and is less than or equal to <code>myMax</code>, inclusive.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 'The lowest random number that can be generated by <code>randomRange</code> should be equal to your minimum number, <code>myMin</code>.'
testString: 'assert(calcMin === 5, ''The lowest random number that can be generated by <code>randomRange</code> should be equal to your minimum number, <code>myMin</code>.'');'
- text: 'The highest random number that can be generated by <code>randomRange</code> should be equal to your maximum number, <code>myMax</code>.'
testString: 'assert(calcMax === 15, ''The highest random number that can be generated by <code>randomRange</code> should be equal to your maximum number, <code>myMax</code>.'');'
- text: 'The random number generated by <code>randomRange</code> should be an integer, not a decimal.'
testString: 'assert(randomRange(0,1) % 1 === 0 , ''The random number generated by <code>randomRange</code> should be an integer, not a decimal.'');'
- text: '<code>randomRange</code> should use both <code>myMax</code> and <code>myMin</code>, and return a random number in your range.'
testString: 'assert((function(){if(code.match(/myMax/g).length > 1 && code.match(/myMin/g).length > 2 && code.match(/Math.floor/g) && code.match(/Math.random/g)){return true;}else{return false;}})(), ''<code>randomRange</code> should use both <code>myMax</code> and <code>myMin</code>, and return a random number in your range.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Example
function ourRandomRange(ourMin, ourMax) {
return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin;
}
ourRandomRange(1, 9);
// Only change code below this line.
function randomRange(myMin, myMax) {
return 0; // Change this line
}
// Change these values to test your function
var myRandom = randomRange(5, 15);
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
function randomRange(myMin, myMax) {
return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
}
```
</section>

View File

@ -0,0 +1,131 @@
---
id: 56533eb9ac21ba0edf2244be
title: Global Scope and Functions
challengeType: 1
---
## Description
<section id='description'>
In JavaScript, <dfn>scope</dfn> refers to the visibility of variables. Variables which are defined outside of a function block have <dfn>Global</dfn> scope. This means, they can be seen everywhere in your JavaScript code.
Variables which are used without the <code>var</code> keyword are automatically created in the <code>global</code> scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with <code>var</code>.
</section>
## Instructions
<section id='instructions'>
Using <code>var</code>, declare a <code>global</code> variable <code>myGlobal</code> outside of any function. Initialize it with a value of <code>10</code>.
Inside function <code>fun1</code>, assign <code>5</code> to <code>oopsGlobal</code> <strong><em>without</em></strong> using the <code>var</code> keyword.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>myGlobal</code> should be defined
testString: 'assert(typeof myGlobal != "undefined", ''<code>myGlobal</code> should be defined'');'
- text: <code>myGlobal</code> should have a value of <code>10</code>
testString: 'assert(myGlobal === 10, ''<code>myGlobal</code> should have a value of <code>10</code>'');'
- text: <code>myGlobal</code> should be declared using the <code>var</code> keyword
testString: 'assert(/var\s+myGlobal/.test(code), ''<code>myGlobal</code> should be declared using the <code>var</code> keyword'');'
- text: <code>oopsGlobal</code> should be a global variable and have a value of <code>5</code>
testString: 'assert(typeof oopsGlobal != "undefined" && oopsGlobal === 5, ''<code>oopsGlobal</code> should be a global variable and have a value of <code>5</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Declare your variable here
function fun1() {
// Assign 5 to oopsGlobal Here
}
// Only change code above this line
function fun2() {
var output = "";
if (typeof myGlobal != "undefined") {
output += "myGlobal: " + myGlobal;
}
if (typeof oopsGlobal != "undefined") {
output += " oopsGlobal: " + oopsGlobal;
}
console.log(output);
}
```
</div>
### Before Test
<div id='js-setup'>
```js
var logOutput = "";
var originalConsole = console
function capture() {
var nativeLog = console.log;
console.log = function (message) {
logOutput = message;
if(nativeLog.apply) {
nativeLog.apply(originalConsole, arguments);
} else {
var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');
nativeLog(nativeMsg);
}
};
}
function uncapture() {
console.log = originalConsole.log;
}
var oopsGlobal;
capture();
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// Declare your variable here
var myGlobal = 10;
function fun1() {
// Assign 5 to oopsGlobal Here
oopsGlobal = 5;
}
// Only change code above this line
function fun2() {
var output = "";
if(typeof myGlobal != "undefined") {
output += "myGlobal: " + myGlobal;
}
if(typeof oopsGlobal != "undefined") {
output += " oopsGlobal: " + oopsGlobal;
}
console.log(output);
}
```
</section>

View File

@ -0,0 +1,75 @@
---
id: 56533eb9ac21ba0edf2244c0
title: Global vs. Local Scope in Functions
challengeType: 1
---
## Description
<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>
The function <code>myFun</code> will return <code>"Head"</code> because the <code>local</code> version of the variable is present.
</section>
## Instructions
<section id='instructions'>
Add a local variable to <code>myOutfit</code> function to override the value of <code>outerWear</code> with <code>"sweater"</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Do not change the value of the global <code>outerWear</code>
testString: 'assert(outerWear === "T-Shirt", ''Do not change the value of the global <code>outerWear</code>'');'
- text: <code>myOutfit</code> should return <code>"sweater"</code>
testString: 'assert(myOutfit() === "sweater", ''<code>myOutfit</code> should return <code>"sweater"</code>'');'
- text: Do not change the return statement
testString: 'assert(/return outerWear/.test(code), ''Do not change the return statement'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Setup
var outerWear = "T-Shirt";
function myOutfit() {
// Only change code below this line
// Only change code above this line
return outerWear;
}
myOutfit();
```
</div>
</section>
## Solution
<section id='solution'>
```js
var outerWear = "T-Shirt";
function myOutfit() {
var outerWear = "sweater";
return outerWear;
}
```
</section>

View File

@ -0,0 +1,111 @@
---
id: 5664820f61c48e80c9fa476c
title: Golf Code
challengeType: 1
---
## Description
<section id='description'>
In the game of <a href="https://en.wikipedia.org/wiki/Golf" target="_blank">golf</a> each hole has a <code>par</code> meaning the average number of <code>strokes</code> a golfer is expected to make in order to sink the ball in a hole to complete the play. Depending on how far above or below <code>par</code> your <code>strokes</code> are, there is a different nickname.
Your function will be passed <code>par</code> and <code>strokes</code> arguments. Return the correct string according to this table which lists the strokes in order of priority; top (highest) to bottom (lowest):
<table class="table table-striped"><thead><tr><th>Strokes</th><th>Return</th></tr></thead><tbody><tr><td>1</td><td>"Hole-in-one!"</td></tr><tr><td>&lt;= par - 2</td><td>"Eagle"</td></tr><tr><td>par - 1</td><td>"Birdie"</td></tr><tr><td>par</td><td>"Par"</td></tr><tr><td>par + 1</td><td>"Bogey"</td></tr><tr><td>par + 2</td><td>"Double Bogey"</td></tr><tr><td>&gt;= par + 3</td><td>"Go Home!"</td></tr></tbody></table>
<code>par</code> and <code>strokes</code> will always be numeric and positive. We have added an array of all the names for your convenience.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>golfScore(4, 1)</code> should return "Hole-in-one!"'
testString: 'assert(golfScore(4, 1) === "Hole-in-one!", ''<code>golfScore(4, 1)</code> should return "Hole-in-one!"'');'
- text: '<code>golfScore(4, 2)</code> should return "Eagle"'
testString: 'assert(golfScore(4, 2) === "Eagle", ''<code>golfScore(4, 2)</code> should return "Eagle"'');'
- text: '<code>golfScore(5, 2)</code> should return "Eagle"'
testString: 'assert(golfScore(5, 2) === "Eagle", ''<code>golfScore(5, 2)</code> should return "Eagle"'');'
- text: '<code>golfScore(4, 3)</code> should return "Birdie"'
testString: 'assert(golfScore(4, 3) === "Birdie", ''<code>golfScore(4, 3)</code> should return "Birdie"'');'
- text: '<code>golfScore(4, 4)</code> should return "Par"'
testString: 'assert(golfScore(4, 4) === "Par", ''<code>golfScore(4, 4)</code> should return "Par"'');'
- text: '<code>golfScore(1, 1)</code> should return "Hole-in-one!"'
testString: 'assert(golfScore(1, 1) === "Hole-in-one!", ''<code>golfScore(1, 1)</code> should return "Hole-in-one!"'');'
- text: '<code>golfScore(5, 5)</code> should return "Par"'
testString: 'assert(golfScore(5, 5) === "Par", ''<code>golfScore(5, 5)</code> should return "Par"'');'
- text: '<code>golfScore(4, 5)</code> should return "Bogey"'
testString: 'assert(golfScore(4, 5) === "Bogey", ''<code>golfScore(4, 5)</code> should return "Bogey"'');'
- text: '<code>golfScore(4, 6)</code> should return "Double Bogey"'
testString: 'assert(golfScore(4, 6) === "Double Bogey", ''<code>golfScore(4, 6)</code> should return "Double Bogey"'');'
- text: '<code>golfScore(4, 7)</code> should return "Go Home!"'
testString: 'assert(golfScore(4, 7) === "Go Home!", ''<code>golfScore(4, 7)</code> should return "Go Home!"'');'
- text: '<code>golfScore(5, 9)</code> should return "Go Home!"'
testString: 'assert(golfScore(5, 9) === "Go Home!", ''<code>golfScore(5, 9)</code> should return "Go Home!"'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"];
function golfScore(par, strokes) {
// Only change code below this line
return "Change Me";
// Only change code above this line
}
// Change these values to test
golfScore(5, 4);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function golfScore(par, strokes) {
if (strokes === 1) {
return "Hole-in-one!";
}
if (strokes <= par - 2) {
return "Eagle";
}
if (strokes === par - 1) {
return "Birdie";
}
if (strokes === par) {
return "Par";
}
if (strokes === par + 1) {
return "Bogey";
}
if(strokes === par + 2) {
return "Double Bogey";
}
return "Go Home!";
}
```
</section>

View File

@ -0,0 +1,76 @@
---
id: 56533eb9ac21ba0edf2244ac
title: Increment a Number with JavaScript
challengeType: 1
---
## Description
<section id='description'>
You can easily <dfn>increment</dfn> or add one to a variable with the <code>++</code> operator.
<code>i++;</code>
is the equivalent of
<code>i = i + 1;</code>
<strong>Note</strong><br>The entire line becomes <code>i++;</code>, eliminating the need for the equal sign.
</section>
## Instructions
<section id='instructions'>
Change the code to use the <code>++</code> operator on <code>myVar</code>.
<strong>Hint</strong><br>Learn more about <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment_()" target="_blank">Arithmetic operators - Increment (++)</a>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>myVar</code> should equal <code>88</code>
testString: 'assert(myVar === 88, ''<code>myVar</code> should equal <code>88</code>'');'
- text: <code>myVar = myVar + 1;</code> should be changed
testString: 'assert(/var\s*myVar\s*=\s*87;\s*\/*.*\s*([+]{2}\s*myVar|myVar\s*[+]{2});/.test(code), ''<code>myVar = myVar + 1;</code> should be changed'');'
- text: Use the <code>++</code> operator
testString: 'assert(/[+]{2}\s*myVar|myVar\s*[+]{2}/.test(code), ''Use the <code>++</code> operator'');'
- text: Do not change code above the line
testString: 'assert(/var myVar = 87;/.test(code), ''Do not change code above the line'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var myVar = 87;
// Only change code below this line
myVar = myVar + 1;
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var myVar = 87;
myVar++;
```
</section>

View File

@ -0,0 +1,66 @@
---
id: 56533eb9ac21ba0edf2244a9
title: Initializing Variables with the Assignment Operator
challengeType: 1
---
## Description
<section id='description'>
It is common to <dfn>initialize</dfn> a variable to an initial value in the same line as it is declared.
<code>var myVar = 0;</code>
Creates a new variable called <code>myVar</code> and assigns it an initial value of <code>0</code>.
</section>
## Instructions
<section id='instructions'>
Define a variable <code>a</code> with <code>var</code> and initialize it to a value of <code>9</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Initialize <code>a</code> to a value of <code>9</code>
testString: 'assert(/var\s+a\s*=\s*9\s*/.test(code), ''Initialize <code>a</code> to a value of <code>9</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Example
var ourVar = 19;
// Only change code below this line
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var a = 9;
```
</section>

View File

@ -0,0 +1,89 @@
---
id: 56533eb9ac21ba0edf2244db
title: Introducing Else If Statements
challengeType: 1
---
## 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>
</section>
## Instructions
<section id='instructions'>
Convert the logic to use <code>else if</code> statements.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: You should have at least two <code>else</code> statements
testString: 'assert(code.match(/else/g).length > 1, ''You should have at least two <code>else</code> statements'');'
- text: You should have at least two <code>if</code> statements
testString: 'assert(code.match(/if/g).length > 1, ''You should have at least two <code>if</code> statements'');'
- text: You should have closing and opening curly braces for each condition
testString: 'assert(code.match(/if\s*\((.+)\)\s*\{[\s\S]+\}\s*else if\s*\((.+)\)\s*\{[\s\S]+\}\s*else\s*\{[\s\S]+\s*\}/), ''You should have closing and opening curly braces for each condition in your if else statement'');'
- text: <code>testElseIf(0)</code> should return "Smaller than 5"
testString: 'assert(testElseIf(0) === "Smaller than 5", ''<code>testElseIf(0)</code> should return "Smaller than 5"'');'
- text: <code>testElseIf(5)</code> should return "Between 5 and 10"
testString: 'assert(testElseIf(5) === "Between 5 and 10", ''<code>testElseIf(5)</code> should return "Between 5 and 10"'');'
- text: <code>testElseIf(7)</code> should return "Between 5 and 10"
testString: 'assert(testElseIf(7) === "Between 5 and 10", ''<code>testElseIf(7)</code> should return "Between 5 and 10"'');'
- text: <code>testElseIf(10)</code> should return "Between 5 and 10"
testString: 'assert(testElseIf(10) === "Between 5 and 10", ''<code>testElseIf(10)</code> should return "Between 5 and 10"'');'
- text: <code>testElseIf(12)</code> should return "Greater than 10"
testString: 'assert(testElseIf(12) === "Greater than 10", ''<code>testElseIf(12)</code> should return "Greater than 10"'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function testElseIf(val) {
if (val > 10) {
return "Greater than 10";
}
if (val < 5) {
return "Smaller than 5";
}
return "Between 5 and 10";
}
// Change this value to test
testElseIf(7);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function testElseIf(val) {
if(val > 10) {
return "Greater than 10";
} else if(val < 5) {
return "Smaller than 5";
} else {
return "Between 5 and 10";
}
}
```
</section>

View File

@ -0,0 +1,91 @@
---
id: 56533eb9ac21ba0edf2244da
title: Introducing Else Statements
challengeType: 1
---
## 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>
</section>
## Instructions
<section id='instructions'>
Combine the <code>if</code> statements into a single <code>if/else</code> statement.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: You should only have one <code>if</code> statement in the editor
testString: 'assert(code.match(/if/g).length === 1, ''You should only have one <code>if</code> statement in the editor'');'
- text: You should use an <code>else</code> statement
testString: 'assert(/else/g.test(code), ''You should use an <code>else</code> statement'');'
- text: <code>testElse(4)</code> should return "5 or Smaller"
testString: 'assert(testElse(4) === "5 or Smaller", ''<code>testElse(4)</code> should return "5 or Smaller"'');'
- text: <code>testElse(5)</code> should return "5 or Smaller"
testString: 'assert(testElse(5) === "5 or Smaller", ''<code>testElse(5)</code> should return "5 or Smaller"'');'
- text: <code>testElse(6)</code> should return "Bigger than 5"
testString: 'assert(testElse(6) === "Bigger than 5", ''<code>testElse(6)</code> should return "Bigger than 5"'');'
- text: <code>testElse(10)</code> should return "Bigger than 5"
testString: 'assert(testElse(10) === "Bigger than 5", ''<code>testElse(10)</code> should return "Bigger than 5"'');'
- text: Do not change the code above or below the lines.
testString: 'assert(/var result = "";/.test(code) && /return result;/.test(code), ''Do not change the code above or below the lines.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function testElse(val) {
var result = "";
// Only change code below this line
if (val > 5) {
result = "Bigger than 5";
}
if (val <= 5) {
result = "5 or Smaller";
}
// Only change code above this line
return result;
}
// Change this value to test
testElse(4);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function testElse(val) {
var result = "";
if(val > 5) {
result = "Bigger than 5";
} else {
result = "5 or Smaller";
}
return result;
}
```
</section>

View File

@ -0,0 +1,85 @@
---
id: 56104e9e514f539506016a5c
title: Iterate Odd Numbers With a For Loop
challengeType: 1
---
## Description
<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>
<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>
## Instructions
<section id='instructions'>
Push the odd numbers from 1 through 9 to <code>myArray</code> using a <code>for</code> loop.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: You should be using a <code>for</code> loop for this.
testString: 'assert(code.match(/for\s*\(/g).length > 1, ''You should be using a <code>for</code> loop for this.'');'
- text: '<code>myArray</code> should equal <code>[1,3,5,7,9]</code>.'
testString: 'assert.deepEqual(myArray, [1,3,5,7,9], ''<code>myArray</code> should equal <code>[1,3,5,7,9]</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Example
var ourArray = [];
for (var i = 0; i < 10; i += 2) {
ourArray.push(i);
}
// Setup
var myArray = [];
// Only change code below this line.
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var ourArray = [];
for (var i = 0; i < 10; i += 2) {
ourArray.push(i);
}
var myArray = [];
for (var i = 1; i < 10; i += 2) {
myArray.push(i);
}
```
</section>

View File

@ -0,0 +1,93 @@
---
id: 5675e877dbd60be8ad28edc6
title: Iterate Through an Array with a For Loop
challengeType: 1
---
## 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>
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>
## Instructions
<section id='instructions'>
Declare and initialize a variable <code>total</code> to <code>0</code>. Use a <code>for</code> loop to add the value of each element of the <code>myArr</code> array to <code>total</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>total</code> should be declared and initialized to 0
testString: 'assert(code.match(/var.*?total\s*=\s*0.*?;/), ''<code>total</code> should be declared and initialized to 0'');'
- text: <code>total</code> should equal 20
testString: 'assert(total === 20, ''<code>total</code> should equal 20'');'
- text: You should use a <code>for</code> loop to iterate through <code>myArr</code>
testString: 'assert(code.match(/for\s*\(/g).length > 1 && code.match(/myArr\s*\[/), ''You should use a <code>for</code> loop to iterate through <code>myArr</code>'');'
- text: Do not set <code>total</code> to 20 directly
testString: 'assert(!code.match(/total[\s\+\-]*=\s*(\d(?!\s*[;,])|[1-9])/g), ''Do not set <code>total</code> to 20 directly'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Example
var ourArr = [ 9, 10, 11, 12];
var ourTotal = 0;
for (var i = 0; i < ourArr.length; i++) {
ourTotal += ourArr[i];
}
// Setup
var myArr = [ 2, 3, 4, 5, 6];
// Only change code below this line
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var ourArr = [ 9, 10, 11, 12];
var ourTotal = 0;
for (var i = 0; i < ourArr.length; i++) {
ourTotal += ourArr[i];
}
var myArr = [ 2, 3, 4, 5, 6];
var total = 0;
for (var i = 0; i < myArr.length; i++) {
total += myArr[i];
}
```
</section>

View File

@ -0,0 +1,90 @@
---
id: 5a2efd662fb457916e1fe604
title: Iterate with JavaScript Do...While Loops
challengeType: 1
---
## Description
<section id='description'>
You can run the same code multiple times by using a loop.
The next type of loop you will learn is called a "<code>do...while</code>" loop because it first will "<code>do</code>" one pass of the code inside the loop no matter what, and then it runs "<code>while</code>" a specified condition is true and stops once that condition is no longer true. Let's look at an example.
<blockquote>var ourArray = [];<br>var i = 0;<br>do {<br>&nbsp;&nbsp;ourArray.push(i);<br>&nbsp;&nbsp;i++;<br>} while (i < 5);</blockquote>
This behaves just as you would expect with any other type of loop, 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 while 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>
Notice that we initialize the value of <code>i</code> to be 5. When we execute the next line, we notice that <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 nothing added to it, so it will still look like this <code>[]</code> when all the code in the example above finishes 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>
In this case, we initialize the value of <code>i</code> as 5, just like we did with the while loop. When we get to the next line, there is no check for the value of <code>i</code>, so we go to the code inside the curly braces and execute it. We will add one element to the array and increment <code>i</code> before we get to the condition check. Then, when we get to checking if <code>i < 5</code> 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.
</section>
## Instructions
<section id='instructions'>
Change the <code>while</code> loop in the code to a <code>do...while</code> loop so that the loop will push the number 10 to <code>myArray</code>, and <code>i</code> will be equal to <code>11</code> when your code finishes running.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: You should be using a <code>do...while</code> loop for this.
testString: 'assert(code.match(/do/g), ''You should be using a <code>do...while</code> loop for this.'');'
- text: '<code>myArray</code> should equal <code>[10]</code>.'
testString: 'assert.deepEqual(myArray, [10], ''<code>myArray</code> should equal <code>[10]</code>.'');'
- text: <code>i</code> should equal <code>11</code>
testString: 'assert.deepEqual(i, 11, ''<code>i</code> should equal <code>11</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Setup
var myArray = [];
var i = 10;
// Only change code below this line.
while (i < 5) {
myArray.push(i);
i++;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var myArray = [];
var i = 10;
do {
myArray.push(i);
i++;
} while (i < 5)
```
</section>

View File

@ -0,0 +1,90 @@
---
id: cf1111c1c11feddfaeb5bdef
title: Iterate with JavaScript For Loops
challengeType: 1
---
## Description
<section id='description'>
You can run the same code multiple times by using a loop.
The most common type of JavaScript loop is called a "<code>for loop</code>" because it runs "for" a specific number of times.
For loops are declared with three optional expressions separated by semicolons:
<code>for ([initialization]; [condition]; [final-expression])</code>
The <code>initialization</code> statement is executed one time only before the loop starts. It is typically used to define and setup your loop variable.
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>
<code>ourArray</code> will now contain <code>[0,1,2,3,4]</code>.
</section>
## Instructions
<section id='instructions'>
Use a <code>for</code> loop to work to push the values 1 through 5 onto <code>myArray</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: You should be using a <code>for</code> loop for this.
testString: 'assert(code.match(/for\s*\(/g).length > 1, ''You should be using a <code>for</code> loop for this.'');'
- text: '<code>myArray</code> should equal <code>[1,2,3,4,5]</code>.'
testString: 'assert.deepEqual(myArray, [1,2,3,4,5], ''<code>myArray</code> should equal <code>[1,2,3,4,5]</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Example
var ourArray = [];
for (var i = 0; i < 5; i++) {
ourArray.push(i);
}
// Setup
var myArray = [];
// Only change code below this line.
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var ourArray = [];
for (var i = 0; i < 5; i++) {
ourArray.push(i);
}
var myArray = [];
for (var i = 1; i < 6; i++) {
myArray.push(i);
}
```
</section>

View File

@ -0,0 +1,75 @@
---
id: cf1111c1c11feddfaeb1bdef
title: Iterate with JavaScript While Loops
challengeType: 1
---
## Description
<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>
Let's try getting a while loop to work by pushing values to an array.
</section>
## Instructions
<section id='instructions'>
Push the numbers 0 through 4 to <code>myArray</code> using a <code>while</code> loop.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: You should be using a <code>while</code> loop for this.
testString: 'assert(code.match(/while/g), ''You should be using a <code>while</code> loop for this.'');'
- text: '<code>myArray</code> should equal <code>[0,1,2,3,4]</code>.'
testString: 'assert.deepEqual(myArray, [0,1,2,3,4], ''<code>myArray</code> should equal <code>[0,1,2,3,4]</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// Setup
var myArray = [];
// Only change code below this line.
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
var myArray = [];
var i = 0;
while(i < 5) {
myArray.push(i);
i++;
}
```
</section>

View File

@ -0,0 +1,110 @@
---
id: 56533eb9ac21ba0edf2244bf
title: Local Scope and Functions
challengeType: 1
---
## Description
<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>
<code>loc</code> is not defined outside of the function.
</section>
## Instructions
<section id='instructions'>
Declare a local variable <code>myVar</code> inside <code>myLocalScope</code>. Run the tests and then follow the instructions commented out in the editor.
<strong>Hint</strong><br>Refreshing the page may help if you get stuck.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: No global <code>myVar</code> variable
testString: 'assert(typeof myVar === ''undefined'', ''No global <code>myVar</code> variable'');'
- text: Add a local <code>myVar</code> variable
testString: 'assert(/var\s+myVar/.test(code), ''Add a local <code>myVar</code> variable'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function myLocalScope() {
'use strict'; // you shouldn't need to edit this line
console.log(myVar);
}
myLocalScope();
// Run and check the console
// myVar is not defined outside of myLocalScope
console.log(myVar);
// Now remove the console log line to pass the test
```
</div>
### Before Test
<div id='js-setup'>
```js
var logOutput = "";
var originalConsole = console
function capture() {
var nativeLog = console.log;
console.log = function (message) {
logOutput = message;
if(nativeLog.apply) {
nativeLog.apply(originalConsole, arguments);
} else {
var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');
nativeLog(nativeMsg);
}
};
}
function uncapture() {
console.log = originalConsole.log;
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
function myLocalScope() {
'use strict';
var myVar;
console.log(myVar);
}
myLocalScope();
```
</section>

View File

@ -0,0 +1,83 @@
---
id: 5690307fddb111c6084545d7
title: Logical Order in If Else Statements
challengeType: 1
---
## Description
<section id='description'>
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>
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>
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>
</section>
## Instructions
<section id='instructions'>
Change the order of logic in the function so that it will return the correct statements in all cases.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>orderMyLogic(4)</code> should return "Less than 5"
testString: 'assert(orderMyLogic(4) === "Less than 5", ''<code>orderMyLogic(4)</code> should return "Less than 5"'');'
- text: <code>orderMyLogic(6)</code> should return "Less than 10"
testString: 'assert(orderMyLogic(6) === "Less than 10", ''<code>orderMyLogic(6)</code> should return "Less than 10"'');'
- text: <code>orderMyLogic(11)</code> should return "Greater than or equal to 10"
testString: 'assert(orderMyLogic(11) === "Greater than or equal to 10", ''<code>orderMyLogic(11)</code> should return "Greater than or equal to 10"'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function orderMyLogic(val) {
if (val < 10) {
return "Less than 10";
} else if (val < 5) {
return "Less than 5";
} else {
return "Greater than or equal to 10";
}
}
// Change this value to test
orderMyLogic(7);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function orderMyLogic(val) {
if(val < 5) {
return "Less than 5";
} else if (val < 10) {
return "Less than 10";
} else {
return "Greater than or equal to 10";
}
}
```
</section>

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