chore(i8n,learn): processed translations

This commit is contained in:
Crowdin Bot
2021-02-06 04:42:36 +00:00
committed by Mrugesh Mohapatra
parent 15047f2d90
commit e5c44a3ae5
3274 changed files with 172122 additions and 14164 deletions

View File

@ -0,0 +1,97 @@
---
id: a77dbc43c33f39daa4429b4f
title: Boo who
challengeType: 5
forumTopicId: 16000
dashedName: boo-who
---
# --description--
Check if a value is classified as a boolean primitive. Return true or false.
Boolean primitives are true and false.
# --hints--
`booWho(true)` should return true.
```js
assert.strictEqual(booWho(true), true);
```
`booWho(false)` should return true.
```js
assert.strictEqual(booWho(false), true);
```
`booWho([1, 2, 3])` should return false.
```js
assert.strictEqual(booWho([1, 2, 3]), false);
```
`booWho([].slice)` should return false.
```js
assert.strictEqual(booWho([].slice), false);
```
`booWho({ "a": 1 })` should return false.
```js
assert.strictEqual(booWho({ a: 1 }), false);
```
`booWho(1)` should return false.
```js
assert.strictEqual(booWho(1), false);
```
`booWho(NaN)` should return false.
```js
assert.strictEqual(booWho(NaN), false);
```
`booWho("a")` should return false.
```js
assert.strictEqual(booWho('a'), false);
```
`booWho("true")` should return false.
```js
assert.strictEqual(booWho('true'), false);
```
`booWho("false")` should return false.
```js
assert.strictEqual(booWho('false'), false);
```
# --seed--
## --seed-contents--
```js
function booWho(bool) {
return bool;
}
booWho(null);
```
# --solutions--
```js
function booWho(bool) {
return typeof bool === "boolean";
}
booWho(null);
```

View File

@ -0,0 +1,110 @@
---
id: a9bd25c716030ec90084d8a1
title: Chunky Monkey
challengeType: 5
forumTopicId: 16005
dashedName: chunky-monkey
---
# --description--
Write a function that splits an array (first argument) into groups the length of `size` (second argument) and returns them as a two-dimensional array.
# --hints--
`chunkArrayInGroups(["a", "b", "c", "d"], 2)` should return `[["a", "b"], ["c", "d"]]`.
```js
assert.deepEqual(chunkArrayInGroups(['a', 'b', 'c', 'd'], 2), [
['a', 'b'],
['c', 'd']
]);
```
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3)` should return `[[0, 1, 2], [3, 4, 5]]`.
```js
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3), [
[0, 1, 2],
[3, 4, 5]
]);
```
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2)` should return `[[0, 1], [2, 3], [4, 5]]`.
```js
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2), [
[0, 1],
[2, 3],
[4, 5]
]);
```
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4)` should return `[[0, 1, 2, 3], [4, 5]]`.
```js
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4), [
[0, 1, 2, 3],
[4, 5]
]);
```
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3)` should return `[[0, 1, 2], [3, 4, 5], [6]]`.
```js
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3), [
[0, 1, 2],
[3, 4, 5],
[6]
]);
```
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4)` should return `[[0, 1, 2, 3], [4, 5, 6, 7], [8]]`.
```js
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4), [
[0, 1, 2, 3],
[4, 5, 6, 7],
[8]
]);
```
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2)` should return `[[0, 1], [2, 3], [4, 5], [6, 7], [8]]`.
```js
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2), [
[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8]
]);
```
# --seed--
## --seed-contents--
```js
function chunkArrayInGroups(arr, size) {
return arr;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
```
# --solutions--
```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);
```

View File

@ -0,0 +1,113 @@
---
id: acda2fb1324d9b0fa741e6b5
title: Confirm the Ending
challengeType: 5
forumTopicId: 16006
dashedName: confirm-the-ending
---
# --description--
Check if a string (first argument, `str`) ends with the given target string (second argument, `target`).
This challenge *can* be solved with the `.endsWith()` 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.
# --hints--
`confirmEnding("Bastian", "n")` should return true.
```js
assert(confirmEnding('Bastian', 'n') === true);
```
`confirmEnding("Congratulation", "on")` should return true.
```js
assert(confirmEnding('Congratulation', 'on') === true);
```
`confirmEnding("Connor", "n")` should return false.
```js
assert(confirmEnding('Connor', 'n') === false);
```
`confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification")` should return false.
```js
assert(
confirmEnding(
'Walking on water and developing software from a specification are easy if both are frozen',
'specification'
) === false
);
```
`confirmEnding("He has to give me a new name", "name")` should return true.
```js
assert(confirmEnding('He has to give me a new name', 'name') === true);
```
`confirmEnding("Open sesame", "same")` should return true.
```js
assert(confirmEnding('Open sesame', 'same') === true);
```
`confirmEnding("Open sesame", "sage")` should return false.
```js
assert(confirmEnding('Open sesame', 'sage') === false);
```
`confirmEnding("Open sesame", "game")` should return false.
```js
assert(confirmEnding('Open sesame', 'game') === false);
```
`confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain")` should return false.
```js
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
);
```
`confirmEnding("Abstraction", "action")` should return true.
```js
assert(confirmEnding('Abstraction', 'action') === true);
```
Your code should not use the built-in method `.endsWith()` to solve the challenge.
```js
assert(!/\.endsWith\(.*?\)\s*?;?/.test(code) && !/\['endsWith'\]/.test(code));
```
# --seed--
## --seed-contents--
```js
function confirmEnding(str, target) {
return str;
}
confirmEnding("Bastian", "n");
```
# --solutions--
```js
function confirmEnding(str, target) {
return str.substring(str.length - target.length) === target;
}
confirmEnding("Bastian", "n");
```

View File

@ -0,0 +1,76 @@
---
id: 56533eb9ac21ba0edf2244b3
title: Convert Celsius to Fahrenheit
challengeType: 1
forumTopicId: 16806
dashedName: convert-celsius-to-fahrenheit
---
# --description--
The algorithm to convert from Celsius to Fahrenheit is the temperature in Celsius times `9/5`, plus `32`.
You are given a variable `celsius` representing a temperature in Celsius. Use the variable `fahrenheit` 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.
# --hints--
`convertToF(0)` should return a number
```js
assert(typeof convertToF(0) === 'number');
```
`convertToF(-30)` should return a value of `-22`
```js
assert(convertToF(-30) === -22);
```
`convertToF(-10)` should return a value of `14`
```js
assert(convertToF(-10) === 14);
```
`convertToF(0)` should return a value of `32`
```js
assert(convertToF(0) === 32);
```
`convertToF(20)` should return a value of `68`
```js
assert(convertToF(20) === 68);
```
`convertToF(30)` should return a value of `86`
```js
assert(convertToF(30) === 86);
```
# --seed--
## --seed-contents--
```js
function convertToF(celsius) {
let fahrenheit;
return fahrenheit;
}
convertToF(30);
```
# --solutions--
```js
function convertToF(celsius) {
let fahrenheit = celsius * 9/5 + 32;
return fahrenheit;
}
convertToF(30);
```

View File

@ -0,0 +1,73 @@
---
id: a302f7aae1aa3152a5b413bc
title: Factorialize a Number
challengeType: 5
forumTopicId: 16013
dashedName: factorialize-a-number
---
# --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 `n!`
For example: `5! = 1 * 2 * 3 * 4 * 5 = 120`
Only integers greater than or equal to zero will be supplied to the function.
# --hints--
`factorialize(5)` should return a number.
```js
assert(typeof factorialize(5) === 'number');
```
`factorialize(5)` should return 120.
```js
assert(factorialize(5) === 120);
```
`factorialize(10)` should return 3628800.
```js
assert(factorialize(10) === 3628800);
```
`factorialize(20)` should return 2432902008176640000.
```js
assert(factorialize(20) === 2432902008176640000);
```
`factorialize(0)` should return 1.
```js
assert(factorialize(0) === 1);
```
# --seed--
## --seed-contents--
```js
function factorialize(num) {
return num;
}
factorialize(5);
```
# --solutions--
```js
function factorialize(num) {
return num < 1 ? 1 : num * factorialize(num - 1);
}
factorialize(5);
```

View File

@ -0,0 +1,63 @@
---
id: adf08ec01beb4f99fc7a68f2
title: Falsy Bouncer
challengeType: 5
forumTopicId: 16014
dashedName: falsy-bouncer
---
# --description--
Remove all falsy values from an array.
Falsy values in JavaScript are `false`, `null`, `0`, `""`, `undefined`, and `NaN`.
Hint: Try converting each value to a Boolean.
# --hints--
`bouncer([7, "ate", "", false, 9])` should return `[7, "ate", 9]`.
```js
assert.deepEqual(bouncer([7, 'ate', '', false, 9]), [7, 'ate', 9]);
```
`bouncer(["a", "b", "c"])` should return `["a", "b", "c"]`.
```js
assert.deepEqual(bouncer(['a', 'b', 'c']), ['a', 'b', 'c']);
```
`bouncer([false, null, 0, NaN, undefined, ""])` should return `[]`.
```js
assert.deepEqual(bouncer([false, null, 0, NaN, undefined, '']), []);
```
`bouncer([null, NaN, 1, 2, undefined])` should return `[1, 2]`.
```js
assert.deepEqual(bouncer([null, NaN, 1, 2, undefined]), [1, 2]);
```
# --seed--
## --seed-contents--
```js
function bouncer(arr) {
return arr;
}
bouncer([7, "ate", "", false, 9]);
```
# --solutions--
```js
function bouncer(arr) {
return arr.filter(e => e);
}
bouncer([7, "ate", "", false, 9]);
```

View File

@ -0,0 +1,87 @@
---
id: a26cbbe9ad8655a977e1ceb5
title: Find the Longest Word in a String
challengeType: 5
forumTopicId: 16015
dashedName: find-the-longest-word-in-a-string
---
# --description--
Return the length of the longest word in the provided sentence.
Your response should be a number.
# --hints--
`findLongestWordLength("The quick brown fox jumped over the lazy dog")` should return a number.
```js
assert(
typeof findLongestWordLength(
'The quick brown fox jumped over the lazy dog'
) === 'number'
);
```
`findLongestWordLength("The quick brown fox jumped over the lazy dog")` should return 6.
```js
assert(
findLongestWordLength('The quick brown fox jumped over the lazy dog') === 6
);
```
`findLongestWordLength("May the force be with you")` should return 5.
```js
assert(findLongestWordLength('May the force be with you') === 5);
```
`findLongestWordLength("Google do a barrel roll")` should return 6.
```js
assert(findLongestWordLength('Google do a barrel roll') === 6);
```
`findLongestWordLength("What is the average airspeed velocity of an unladen swallow")` should return 8.
```js
assert(
findLongestWordLength(
'What is the average airspeed velocity of an unladen swallow'
) === 8
);
```
`findLongestWordLength("What if we try a super-long word such as otorhinolaryngology")` should return 19.
```js
assert(
findLongestWordLength(
'What if we try a super-long word such as otorhinolaryngology'
) === 19
);
```
# --seed--
## --seed-contents--
```js
function findLongestWordLength(str) {
return str.length;
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");
```
# --solutions--
```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");
```

View File

@ -0,0 +1,58 @@
---
id: a6e40f1041b06c996f7b2406
title: Finders Keepers
challengeType: 5
forumTopicId: 16016
dashedName: finders-keepers
---
# --description--
Create a function that looks through an array `arr` and returns the first element in it that passes a 'truth test'. This means that given an element `x`, the 'truth test' is passed if `func(x)` is `true`. If no element passes the test, return `undefined`.
# --hints--
`findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; })` should return 8.
```js
assert.strictEqual(
findElement([1, 3, 5, 8, 9, 10], function (num) {
return num % 2 === 0;
}),
8
);
```
`findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; })` should return undefined.
```js
assert.strictEqual(
findElement([1, 3, 5, 9], function (num) {
return num % 2 === 0;
}),
undefined
);
```
# --seed--
## --seed-contents--
```js
function findElement(arr, func) {
let num = 0;
return num;
}
findElement([1, 2, 3, 4], num => num % 2 === 0);
```
# --solutions--
```js
function findElement(arr, func) {
return arr.filter(func)[0];
}
findElement([1, 2, 3, 4], num => num % 2 === 0);
```

View File

@ -0,0 +1,117 @@
---
id: af2170cad53daa0770fabdea
title: Mutations
challengeType: 5
forumTopicId: 16025
dashedName: mutations
---
# --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, `["hello", "Hello"]`, should return true because all of the letters in the second string are present in the first, ignoring case.
The arguments `["hello", "hey"]` should return false because the string "hello" does not contain a "y".
Lastly, `["Alien", "line"]`, should return true because all of the letters in "line" are present in "Alien".
# --hints--
`mutation(["hello", "hey"])` should return false.
```js
assert(mutation(['hello', 'hey']) === false);
```
`mutation(["hello", "Hello"])` should return true.
```js
assert(mutation(['hello', 'Hello']) === true);
```
`mutation(["zyxwvutsrqponmlkjihgfedcba", "qrstu"])` should return true.
```js
assert(mutation(['zyxwvutsrqponmlkjihgfedcba', 'qrstu']) === true);
```
`mutation(["Mary", "Army"])` should return true.
```js
assert(mutation(['Mary', 'Army']) === true);
```
`mutation(["Mary", "Aarmy"])` should return true.
```js
assert(mutation(['Mary', 'Aarmy']) === true);
```
`mutation(["Alien", "line"])` should return true.
```js
assert(mutation(['Alien', 'line']) === true);
```
`mutation(["floor", "for"])` should return true.
```js
assert(mutation(['floor', 'for']) === true);
```
`mutation(["hello", "neo"])` should return false.
```js
assert(mutation(['hello', 'neo']) === false);
```
`mutation(["voodoo", "no"])` should return false.
```js
assert(mutation(['voodoo', 'no']) === false);
```
`mutation(["ate", "date"]` should return false.
```js
assert(mutation(['ate', 'date']) === false);
```
`mutation(["Tiger", "Zebra"])` should return false.
```js
assert(mutation(['Tiger', 'Zebra']) === false);
```
`mutation(["Noel", "Ole"])` should return true.
```js
assert(mutation(['Noel', 'Ole']) === true);
```
# --seed--
## --seed-contents--
```js
function mutation(arr) {
return arr;
}
mutation(["hello", "hey"]);
```
# --solutions--
```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"]);
```

View File

@ -0,0 +1,84 @@
---
id: afcc8d540bea9ea2669306b6
title: Repeat a String Repeat a String
challengeType: 5
forumTopicId: 16041
dashedName: repeat-a-string-repeat-a-string
---
# --description--
Repeat a given string `str` (first argument) for `num` times (second argument). Return an empty string if `num` is not a positive number. For the purpose of this challenge, do *not* use the built-in `.repeat()` method.
# --hints--
`repeatStringNumTimes("*", 3)` should return `"***"`.
```js
assert(repeatStringNumTimes('*', 3) === '***');
```
`repeatStringNumTimes("abc", 3)` should return `"abcabcabc"`.
```js
assert(repeatStringNumTimes('abc', 3) === 'abcabcabc');
```
`repeatStringNumTimes("abc", 4)` should return `"abcabcabcabc"`.
```js
assert(repeatStringNumTimes('abc', 4) === 'abcabcabcabc');
```
`repeatStringNumTimes("abc", 1)` should return `"abc"`.
```js
assert(repeatStringNumTimes('abc', 1) === 'abc');
```
`repeatStringNumTimes("*", 8)` should return `"********"`.
```js
assert(repeatStringNumTimes('*', 8) === '********');
```
`repeatStringNumTimes("abc", -2)` should return `""`.
```js
assert(repeatStringNumTimes('abc', -2) === '');
```
The built-in `repeat()` method should not be used.
```js
assert(!/\.repeat/g.test(code));
```
`repeatStringNumTimes("abc", 0)` should return `""`.
```js
assert(repeatStringNumTimes('abc', 0) === '');
```
# --seed--
## --seed-contents--
```js
function repeatStringNumTimes(str, num) {
return str;
}
repeatStringNumTimes("abc", 3);
```
# --solutions--
```js
function repeatStringNumTimes(str, num) {
if (num < 1) return '';
return num === 1 ? str : str + repeatStringNumTimes(str, num-1);
}
repeatStringNumTimes("abc", 3);
```

View File

@ -0,0 +1,92 @@
---
id: a789b3483989747d63b0e427
title: Return Largest Numbers in Arrays
challengeType: 5
forumTopicId: 16042
dashedName: return-largest-numbers-in-arrays
---
# --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 `arr[i]`.
# --hints--
`largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])` should return an array.
```js
assert(
largestOfFour([
[4, 5, 1, 3],
[13, 27, 18, 26],
[32, 35, 37, 39],
[1000, 1001, 857, 1]
]).constructor === Array
);
```
`largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]])` should return `[27, 5, 39, 1001]`.
```js
assert.deepEqual(
largestOfFour([
[13, 27, 18, 26],
[4, 5, 1, 3],
[32, 35, 37, 39],
[1000, 1001, 857, 1]
]),
[27, 5, 39, 1001]
);
```
`largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]])` should return `[9, 35, 97, 1000000]`.
```js
assert.deepEqual(
largestOfFour([
[4, 9, 1, 3],
[13, 35, 18, 26],
[32, 35, 97, 39],
[1000000, 1001, 857, 1]
]),
[9, 35, 97, 1000000]
);
```
`largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]])` should return `[25, 48, 21, -3]`.
```js
assert.deepEqual(
largestOfFour([
[17, 23, 25, 12],
[25, 7, 34, 48],
[4, -10, 18, 21],
[-72, -3, -17, -10]
]),
[25, 48, 21, -3]
);
```
# --seed--
## --seed-contents--
```js
function largestOfFour(arr) {
return arr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
```
# --solutions--
```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]]);
```

View File

@ -0,0 +1,63 @@
---
id: a202eed8fc186c8434cb6d61
title: Reverse a String
challengeType: 5
forumTopicId: 16043
dashedName: reverse-a-string
---
# --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.
# --hints--
`reverseString("hello")` should return a string.
```js
assert(typeof reverseString('hello') === 'string');
```
`reverseString("hello")` should become `"olleh"`.
```js
assert(reverseString('hello') === 'olleh');
```
`reverseString("Howdy")` should become `"ydwoH"`.
```js
assert(reverseString('Howdy') === 'ydwoH');
```
`reverseString("Greetings from Earth")` should return `"htraE morf sgniteerG"`.
```js
assert(reverseString('Greetings from Earth') === 'htraE morf sgniteerG');
```
# --seed--
## --seed-contents--
```js
function reverseString(str) {
return str;
}
reverseString("hello");
```
# --solutions--
```js
function reverseString(str) {
return str.split('').reverse().join('');
}
reverseString("hello");
```

View File

@ -0,0 +1,98 @@
---
id: 579e2a2c335b9d72dd32e05c
title: Slice and Splice
challengeType: 5
forumTopicId: 301148
dashedName: slice-and-splice
---
# --description--
You are given two arrays and an index.
Copy each element of the first array into the second array, in order.
Begin inserting elements at index `n` of the second array.
Return the resulting array. The input arrays should remain the same after the function runs.
# --hints--
`frankenSplice([1, 2, 3], [4, 5], 1)` should return `[4, 1, 2, 3, 5]`.
```js
assert.deepEqual(frankenSplice([1, 2, 3], [4, 5], 1), [4, 1, 2, 3, 5]);
```
`frankenSplice([1, 2], ["a", "b"], 1)` should return `["a", 1, 2, "b"]`.
```js
assert.deepEqual(frankenSplice(testArr1, testArr2, 1), ['a', 1, 2, 'b']);
```
`frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2)` should return `["head", "shoulders", "claw", "tentacle", "knees", "toes"]`.
```js
assert.deepEqual(
frankenSplice(
['claw', 'tentacle'],
['head', 'shoulders', 'knees', 'toes'],
2
),
['head', 'shoulders', 'claw', 'tentacle', 'knees', 'toes']
);
```
All elements from the first array should be added to the second array in their original order.
```js
assert.deepEqual(frankenSplice([1, 2, 3, 4], [], 0), [1, 2, 3, 4]);
```
The first array should remain the same after the function runs.
```js
frankenSplice(testArr1, testArr2, 1);
assert.deepEqual(testArr1, [1, 2]);
```
The second array should remain the same after the function runs.
```js
frankenSplice(testArr1, testArr2, 1);
assert.deepEqual(testArr2, ['a', 'b']);
```
# --seed--
## --after-user-code--
```js
let testArr1 = [1, 2];
let testArr2 = ["a", "b"];
```
## --seed-contents--
```js
function frankenSplice(arr1, arr2, n) {
return arr2;
}
frankenSplice([1, 2, 3], [4, 5, 6], 1);
```
# --solutions--
```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);
```

View File

@ -0,0 +1,64 @@
---
id: ab6137d4e35944e21037b769
title: Title Case a Sentence
challengeType: 5
forumTopicId: 16088
dashedName: title-case-a-sentence
---
# --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".
# --hints--
`titleCase("I'm a little tea pot")` should return a string.
```js
assert(typeof titleCase("I'm a little tea pot") === 'string');
```
`titleCase("I'm a little tea pot")` should return `I'm A Little Tea Pot`.
```js
assert(titleCase("I'm a little tea pot") === "I'm A Little Tea Pot");
```
`titleCase("sHoRt AnD sToUt")` should return `Short And Stout`.
```js
assert(titleCase('sHoRt AnD sToUt') === 'Short And Stout');
```
`titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")` should return `Here Is My Handle Here Is My Spout`.
```js
assert(
titleCase('HERE IS MY HANDLE HERE IS MY SPOUT') ===
'Here Is My Handle Here Is My Spout'
);
```
# --seed--
## --seed-contents--
```js
function titleCase(str) {
return str;
}
titleCase("I'm a little tea pot");
```
# --solutions--
```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");
```

View File

@ -0,0 +1,91 @@
---
id: ac6993d51946422351508a41
title: Truncate a String
challengeType: 5
forumTopicId: 16089
dashedName: truncate-a-string
---
# --description--
Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a `...` ending.
# --hints--
`truncateString("A-tisket a-tasket A green and yellow basket", 8)` should return "A-tisket...".
```js
assert(
truncateString('A-tisket a-tasket A green and yellow basket', 8) ===
'A-tisket...'
);
```
`truncateString("Peter Piper picked a peck of pickled peppers", 11)` should return "Peter Piper...".
```js
assert(
truncateString('Peter Piper picked a peck of pickled peppers', 11) ===
'Peter Piper...'
);
```
`truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length)` should return "A-tisket a-tasket A green and yellow basket".
```js
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'
);
```
`truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2)` should return "A-tisket a-tasket A green and yellow basket".
```js
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'
);
```
`truncateString("A-", 1)` should return "A...".
```js
assert(truncateString('A-', 1) === 'A...');
```
`truncateString("Absolutely Longer", 2)` should return "Ab...".
```js
assert(truncateString('Absolutely Longer', 2) === 'Ab...');
```
# --seed--
## --seed-contents--
```js
function truncateString(str, num) {
return str;
}
truncateString("A-tisket a-tasket A green and yellow basket", 8);
```
# --solutions--
```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);
```

View File

@ -0,0 +1,143 @@
---
id: a24c1a4622e3c05097f71d67
title: Where do I Belong
challengeType: 5
forumTopicId: 16094
dashedName: where-do-i-belong
---
# --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, `getIndexToIns([1,2,3,4], 1.5)` should return `1` because it is greater than `1` (index 0), but less than `2` (index 1).
Likewise, `getIndexToIns([20,3,5], 19)` should return `2` because once the array has been sorted it will look like `[3,5,20]` and `19` is less than `20` (index 2) and greater than `5` (index 1).
# --hints--
`getIndexToIns([10, 20, 30, 40, 50], 35)` should return `3`.
```js
assert(getIndexToIns([10, 20, 30, 40, 50], 35) === 3);
```
`getIndexToIns([10, 20, 30, 40, 50], 35)` should return a number.
```js
assert(typeof getIndexToIns([10, 20, 30, 40, 50], 35) === 'number');
```
`getIndexToIns([10, 20, 30, 40, 50], 30)` should return `2`.
```js
assert(getIndexToIns([10, 20, 30, 40, 50], 30) === 2);
```
`getIndexToIns([10, 20, 30, 40, 50], 30)` should return a number.
```js
assert(typeof getIndexToIns([10, 20, 30, 40, 50], 30) === 'number');
```
`getIndexToIns([40, 60], 50)` should return `1`.
```js
assert(getIndexToIns([40, 60], 50) === 1);
```
`getIndexToIns([40, 60], 50)` should return a number.
```js
assert(typeof getIndexToIns([40, 60], 50) === 'number');
```
`getIndexToIns([3, 10, 5], 3)` should return `0`.
```js
assert(getIndexToIns([3, 10, 5], 3) === 0);
```
`getIndexToIns([3, 10, 5], 3)` should return a number.
```js
assert(typeof getIndexToIns([3, 10, 5], 3) === 'number');
```
`getIndexToIns([5, 3, 20, 3], 5)` should return `2`.
```js
assert(getIndexToIns([5, 3, 20, 3], 5) === 2);
```
`getIndexToIns([5, 3, 20, 3], 5)` should return a number.
```js
assert(typeof getIndexToIns([5, 3, 20, 3], 5) === 'number');
```
`getIndexToIns([2, 20, 10], 19)` should return `2`.
```js
assert(getIndexToIns([2, 20, 10], 19) === 2);
```
`getIndexToIns([2, 20, 10], 19)` should return a number.
```js
assert(typeof getIndexToIns([2, 20, 10], 19) === 'number');
```
`getIndexToIns([2, 5, 10], 15)` should return `3`.
```js
assert(getIndexToIns([2, 5, 10], 15) === 3);
```
`getIndexToIns([2, 5, 10], 15)` should return a number.
```js
assert(typeof getIndexToIns([2, 5, 10], 15) === 'number');
```
`getIndexToIns([], 1)` should return `0`.
```js
assert(getIndexToIns([], 1) === 0);
```
`getIndexToIns([], 1)` should return a number.
```js
assert(typeof getIndexToIns([], 1) === 'number');
```
# --seed--
## --seed-contents--
```js
function getIndexToIns(arr, num) {
return num;
}
getIndexToIns([40, 60], 50);
```
# --solutions--
```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);
```

View File

@ -0,0 +1,82 @@
---
id: 5a661e0f1068aca922b3ef17
title: Access an Array's Contents Using Bracket Notation
challengeType: 1
forumTopicId: 301149
dashedName: access-an-arrays-contents-using-bracket-notation
---
# --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:
```js
let ourArray = ["a", "b", "c"];
```
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 ***zeroth*** 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 `"a"` from `ourArray` and assign it to a variable, we can do so with the following code:
```js
let ourVariable = ourArray[0];
// ourVariable equals "a"
```
In addition to accessing the value associated with an index, you can also *set* an index to a value using the same notation:
```js
ourArray[1] = "not b anymore";
// ourArray now equals ["a", "not b anymore", "c"];
```
Using bracket notation, we have now reset the item at index 1 from `"b"`, to `"not b anymore"`.
# --instructions--
In order to complete this challenge, set the 2nd position (index `1`) of `myArray` to anything you want, besides `"b"`.
# --hints--
`myArray[0]` should be equal to `"a"`
```js
assert.strictEqual(myArray[0], 'a');
```
`myArray[1]` should not be equal to `"b"`
```js
assert.notStrictEqual(myArray[1], 'b');
```
`myArray[2]` should be equal to `"c"`
```js
assert.strictEqual(myArray[2], 'c');
```
`myArray[3]` should be equal to `"d"`
```js
assert.strictEqual(myArray[3], 'd');
```
# --seed--
## --seed-contents--
```js
let myArray = ["a", "b", "c", "d"];
// Only change code below this line
// Only change code above this line
console.log(myArray);
```
# --solutions--
```js
let myArray = ["a", "b", "c", "d"];
myArray[1] = "e";
```

View File

@ -0,0 +1,101 @@
---
id: 587d7b7c367417b2b2512b1a
title: Access Property Names with Bracket Notation
challengeType: 1
forumTopicId: 301150
dashedName: access-property-names-with-bracket-notation
---
# --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 `foods` object is being used in a program for a supermarket cash register. We have some function that sets the `selectedFood` and we want to check our `foods` object for the presence of that food. This might look like:
```js
let selectedFood = getCurrentFood(scannedItem);
let inventory = foods[selectedFood];
```
This code will evaluate the value stored in the `selectedFood` variable and return the value of that key in the `foods` object, or `undefined` 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.
# --instructions--
We've defined a function, `checkInventory`, which receives a scanned item as an argument. Return the current value of the `scannedItem` key in the `foods` object. You can assume that only valid keys will be provided as an argument to `checkInventory`.
# --hints--
`checkInventory` should be a function.
```js
assert.strictEqual(typeof checkInventory, 'function');
```
The `foods` object should have only the following key-value pairs: `apples: 25`, `oranges: 32`, `plums: 28`, `bananas: 13`, `grapes: 35`, `strawberries: 27`.
```js
assert.deepEqual(foods, {
apples: 25,
oranges: 32,
plums: 28,
bananas: 13,
grapes: 35,
strawberries: 27
});
```
`checkInventory("apples")` should return `25`.
```js
assert.strictEqual(checkInventory('apples'), 25);
```
`checkInventory("bananas")` should return `13`.
```js
assert.strictEqual(checkInventory('bananas'), 13);
```
`checkInventory("strawberries")` should return `27`.
```js
assert.strictEqual(checkInventory('strawberries'), 27);
```
# --seed--
## --seed-contents--
```js
let foods = {
apples: 25,
oranges: 32,
plums: 28,
bananas: 13,
grapes: 35,
strawberries: 27
};
function checkInventory(scannedItem) {
// Only change code below this line
// Only change code above this line
}
console.log(checkInventory("apples"));
```
# --solutions--
```js
let foods = {
apples: 25,
oranges: 32,
plums: 28,
bananas: 13,
grapes: 35,
strawberries: 27
};
function checkInventory(scannedItem) {
return foods[scannedItem];
}
```

View File

@ -0,0 +1,83 @@
---
id: 587d78b2367417b2b2512b0e
title: Add Items to an Array with push() and unshift()
challengeType: 1
forumTopicId: 301151
dashedName: add-items-to-an-array-with-push-and-unshift
---
# --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: `Array.push()` and `Array.unshift()`.
Both methods take one or more elements as parameters and add those elements to the array the method is being called on; the `push()` method adds elements to the end of an array, and `unshift()` adds elements to the beginning. Consider the following:
```js
let twentyThree = 'XXIII';
let romanNumerals = ['XXI', 'XXII'];
romanNumerals.unshift('XIX', 'XX');
// now equals ['XIX', 'XX', 'XXI', 'XXII']
romanNumerals.push(twentyThree);
// 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.
```
# --instructions--
We have defined a function, `mixedNumbers`, which we are passing an array as an argument. Modify the function by using `push()` and `unshift()` to add `'I', 2, 'three'` to the beginning of the array and `7, 'VIII', 9` to the end so that the returned array contains representations of the numbers 1-9 in order.
# --hints--
`mixedNumbers(["IV", 5, "six"])` should now return `["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]`
```js
assert.deepEqual(mixedNumbers(['IV', 5, 'six']), [
'I',
2,
'three',
'IV',
5,
'six',
7,
'VIII',
9
]);
```
The `mixedNumbers` function should utilize the `push()` method
```js
assert(mixedNumbers.toString().match(/\.push/));
```
The `mixedNumbers` function should utilize the `unshift()` method
```js
assert(mixedNumbers.toString().match(/\.unshift/));
```
# --seed--
## --seed-contents--
```js
function mixedNumbers(arr) {
// Only change code below this line
// Only change code above this line
return arr;
}
console.log(mixedNumbers(['IV', 5, 'six']));
```
# --solutions--
```js
function mixedNumbers(arr) {
arr.push(7,'VIII',9);
arr.unshift('I',2,'three');
return arr;
}
```

View File

@ -0,0 +1,93 @@
---
id: 587d78b3367417b2b2512b11
title: Add Items Using splice()
challengeType: 1
forumTopicId: 301152
dashedName: add-items-using-splice
---
# --description--
Remember in the last challenge we mentioned that `splice()` can take up to three parameters? Well, you can use the third parameter, comprised of one or more element(s), to add to the array. This can be incredibly useful for quickly switching out an element, or a set of elements, for another.
```js
const numbers = [10, 11, 12, 12, 15];
const startIndex = 3;
const amountToDelete = 1;
numbers.splice(startIndex, amountToDelete, 13, 14);
// the second entry of 12 is removed, and we add 13 and 14 at the same index
console.log(numbers);
// returns [ 10, 11, 12, 13, 14, 15 ]
```
Here, we begin with an array of numbers. Then, we pass the following to `splice()`: The index at which to begin deleting elements (3), the number of elements to be deleted (1), and the remaining arguments (13, 14) will be inserted starting at that same index. Note that there can be any number of elements (separated by commas) following `amountToDelete`, each of which gets inserted.
# --instructions--
We have defined a function, `htmlColorNames`, which takes an array of HTML colors as an argument. Modify the function using `splice()` to remove the first two elements of the array and add `'DarkSalmon'` and `'BlanchedAlmond'` in their respective places.
# --hints--
`htmlColorNames` should return `["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurquoise", "FireBrick"]`
```js
assert.deepEqual(
htmlColorNames([
'DarkGoldenRod',
'WhiteSmoke',
'LavenderBlush',
'PaleTurquoise',
'FireBrick'
]),
[
'DarkSalmon',
'BlanchedAlmond',
'LavenderBlush',
'PaleTurquoise',
'FireBrick'
]
);
```
The `htmlColorNames` function should utilize the `splice()` method
```js
assert(/.splice/.test(code));
```
You should not use `shift()` or `unshift()`.
```js
assert(!/shift|unshift/.test(code));
```
You should not use array bracket notation.
```js
assert(!/\[\d\]\s*=/.test(code));
```
# --seed--
## --seed-contents--
```js
function htmlColorNames(arr) {
// Only change code below this line
// Only change code above this line
return arr;
}
console.log(htmlColorNames(['DarkGoldenRod', 'WhiteSmoke', 'LavenderBlush', 'PaleTurquoise', 'FireBrick']));
```
# --solutions--
```js
function htmlColorNames(arr) {
arr.splice(0,2,'DarkSalmon', 'BlanchedAlmond');
return arr;
}
```

View File

@ -0,0 +1,124 @@
---
id: 587d7b7c367417b2b2512b18
title: Add Key-Value Pairs to JavaScript Objects
challengeType: 1
forumTopicId: 301153
dashedName: add-key-value-pairs-to-javascript-objects
---
# --description--
At their most basic, objects are just collections of <dfn>key-value</dfn> pairs. In other words, they are pieces of data (<dfn>values</dfn>) mapped to unique identifiers called <dfn>properties</dfn> (<dfn>keys</dfn>). Take a look at an example:
```js
const tekkenCharacter = {
player: 'Hwoarang',
fightingStyle: 'Tae Kwon Doe',
human: true
};
```
The above code defines a Tekken video game character object called `tekkenCharacter`. It has three properties, each of which map to a specific value. If you want to add an additional property, such as "origin", it can be done by assigning `origin` to the object:
```js
tekkenCharacter.origin = 'South Korea';
```
This uses dot notation. If you were to observe the `tekkenCharacter` object, it will now include the `origin` property. Hwoarang also had distinct orange hair. You can add this property with bracket notation by doing:
```js
tekkenCharacter['hair color'] = 'dyed orange';
```
Bracket notation is required if your property has a space in it or if you want to use a variable to name the property. In the above case, the property is enclosed in quotes to denote it as a string and will be added exactly as shown. Without quotes, it will be evaluated as a variable and the name of the property will be whatever value the variable is. Here's an example with a variable:
```js
const eyes = 'eye color';
tekkenCharacter[eyes] = 'brown';
```
After adding all the examples, the object will look like this:
```js
{
player: 'Hwoarang',
fightingStyle: 'Tae Kwon Doe',
human: true,
origin: 'South Korea',
'hair color': 'dyed orange',
'eye color': 'brown'
};
```
# --instructions--
A `foods` object has been created with three entries. Using the syntax of your choice, add three more entries to it: `bananas` with a value of `13`, `grapes` with a value of `35`, and `strawberries` with a value of `27`.
# --hints--
`foods` should be an object.
```js
assert(typeof foods === 'object');
```
The `foods` object should have a key `"bananas"` with a value of `13`.
```js
assert(foods.bananas === 13);
```
The `foods` object should have a key `"grapes"` with a value of `35`.
```js
assert(foods.grapes === 35);
```
The `foods` object should have a key `"strawberries"` with a value of `27`.
```js
assert(foods.strawberries === 27);
```
The key-value pairs should be set using dot or bracket notation.
```js
assert(
code.search(/bananas:/) === -1 &&
code.search(/grapes:/) === -1 &&
code.search(/strawberries:/) === -1
);
```
# --seed--
## --seed-contents--
```js
let foods = {
apples: 25,
oranges: 32,
plums: 28
};
// Only change code below this line
// Only change code above this line
console.log(foods);
```
# --solutions--
```js
let foods = {
apples: 25,
oranges: 32,
plums: 28
};
foods['bananas'] = 13;
foods['grapes'] = 35;
foods['strawberries'] = 27;
```

View File

@ -0,0 +1,91 @@
---
id: 587d7b7b367417b2b2512b14
title: Check For The Presence of an Element With indexOf()
challengeType: 1
forumTopicId: 301154
dashedName: check-for-the-presence-of-an-element-with-indexof
---
# --description--
Since arrays can be changed, or *mutated*, 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, `indexOf()`, that allows us to quickly and easily check for the presence of an element on an array. `indexOf()` takes an element as a parameter, and when called, it returns the position, or index, of that element, or `-1` if the element does not exist on the array.
For example:
```js
let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears'];
fruits.indexOf('dates'); // returns -1
fruits.indexOf('oranges'); // returns 2
fruits.indexOf('pears'); // returns 1, the first index at which the element exists
```
# --instructions--
`indexOf()` can be incredibly useful for quickly checking for the presence of an element on an array. We have defined a function, `quickCheck`, that takes an array and an element as arguments. Modify the function using `indexOf()` so that it returns `true` if the passed element exists on the array, and `false` if it does not.
# --hints--
The `quickCheck` function should return a boolean (`true` or `false`), not a string (`"true"` or `"false"`)
```js
assert.isBoolean(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
```
`quickCheck(["squash", "onions", "shallots"], "mushrooms")` should return `false`
```js
assert.strictEqual(
quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'),
false
);
```
`quickCheck(["onions", "squash", "shallots"], "onions")` should return `true`
```js
assert.strictEqual(
quickCheck(['onions', 'squash', 'shallots'], 'onions'),
true
);
```
`quickCheck([3, 5, 9, 125, 45, 2], 125)` should return `true`
```js
assert.strictEqual(quickCheck([3, 5, 9, 125, 45, 2], 125), true);
```
`quickCheck([true, false, false], undefined)` should return `false`
```js
assert.strictEqual(quickCheck([true, false, false], undefined), false);
```
The `quickCheck` function should utilize the `indexOf()` method
```js
assert.notStrictEqual(quickCheck.toString().search(/\.indexOf\(/), -1);
```
# --seed--
## --seed-contents--
```js
function quickCheck(arr, elem) {
// Only change code below this line
// Only change code above this line
}
console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
```
# --solutions--
```js
function quickCheck(arr, elem) {
return arr.indexOf(elem) >= 0;
}
```

View File

@ -0,0 +1,152 @@
---
id: 587d7b7d367417b2b2512b1c
title: Check if an Object has a Property
challengeType: 1
forumTopicId: 301155
dashedName: check-if-an-object-has-a-property
---
# --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 `hasOwnProperty()` method and the other uses the `in` keyword. If we have an object `users` with a property of `Alan`, we could check for its presence in either of the following ways:
```js
users.hasOwnProperty('Alan');
'Alan' in users;
// both return true
```
# --instructions--
We've created an object, `users`, with some users in it and a function `isEveryoneHere`, which we pass the `users` object to as an argument. Finish writing this function so that it returns `true` only if the `users` object contains all four names, `Alan`, `Jeff`, `Sarah`, and `Ryan`, as keys, and `false` otherwise.
# --hints--
The `users` object should only contain the keys `Alan`, `Jeff`, `Sarah`, and `Ryan`
```js
assert(
'Alan' in users &&
'Jeff' in users &&
'Sarah' in users &&
'Ryan' in users &&
Object.keys(users).length === 4
);
```
The function `isEveryoneHere` should return `true` if `Alan`, `Jeff`, `Sarah`, and `Ryan` are properties on the `users` object
```js
assert(isEveryoneHere(users) === true);
```
The function `isEveryoneHere` should return `false` if `Alan` is not a property on the `users` object
```js
assert(
(function () {
delete users.Alan;
return isEveryoneHere(users);
})() === false
);
```
The function `isEveryoneHere` should return `false` if `Jeff` is not a property on the `users` object
```js
assert(
(function () {
delete users.Jeff;
return isEveryoneHere(users);
})() === false
);
```
The function `isEveryoneHere` should return `false` if `Sarah` is not a property on the `users` object
```js
assert(
(function () {
delete users.Sarah;
return isEveryoneHere(users);
})() === false
);
```
The function `isEveryoneHere` should return `false` if `Ryan` is not a property on the `users` object
```js
assert(
(function () {
delete users.Ryan;
return isEveryoneHere(users);
})() === false
);
```
# --seed--
## --seed-contents--
```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) {
// Only change code below this line
// Only change code above this line
}
console.log(isEveryoneHere(users));
```
# --solutions--
```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) {
return [
'Alan',
'Jeff',
'Sarah',
'Ryan'
].every(i => obj.hasOwnProperty(i));
}
console.log(isEveryoneHere(users));
```

View File

@ -0,0 +1,62 @@
---
id: 587d7b7b367417b2b2512b17
title: Combine Arrays with the Spread Operator
challengeType: 1
forumTopicId: 301156
dashedName: combine-arrays-with-the-spread-operator
---
# --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:
```js
let thisArray = ['sage', 'rosemary', 'parsley', 'thyme'];
let thatArray = ['basil', 'cilantro', ...thisArray, 'coriander'];
// thatArray now equals ['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']
```
Using spread syntax, we have just achieved an operation that would have been more complex and more verbose had we used traditional methods.
# --instructions--
We have defined a function `spreadOut` that returns the variable `sentence`. Modify the function using the <dfn>spread</dfn> operator so that it returns the array `['learning', 'to', 'code', 'is', 'fun']`.
# --hints--
`spreadOut` should return `["learning", "to", "code", "is", "fun"]`
```js
assert.deepEqual(spreadOut(), ['learning', 'to', 'code', 'is', 'fun']);
```
The `spreadOut` function should utilize spread syntax
```js
assert.notStrictEqual(spreadOut.toString().search(/[...]/), -1);
```
# --seed--
## --seed-contents--
```js
function spreadOut() {
let fragment = ['to', 'code'];
let sentence; // Change this line
return sentence;
}
console.log(spreadOut());
```
# --solutions--
```js
function spreadOut() {
let fragment = ['to', 'code'];
let sentence = ['learning', ...fragment, 'is', 'fun'];
return sentence;
}
```

View File

@ -0,0 +1,102 @@
---
id: 587d7b7b367417b2b2512b13
title: Copy an Array with the Spread Operator
challengeType: 1
forumTopicId: 301157
dashedName: copy-an-array-with-the-spread-operator
---
# --description--
While `slice()` 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 *all* of an array's elements, in order, with a simple and highly readable syntax. The spread syntax simply looks like this: `...`
In practice, we can use the spread operator to copy an array like so:
```js
let thisArray = [true, true, undefined, false, null];
let thatArray = [...thisArray];
// thatArray equals [true, true, undefined, false, null]
// thisArray remains unchanged and thatArray contains the same elements as thisArray
```
# --instructions--
We have defined a function, `copyMachine` which takes `arr` (an array) and `num` (a number) as arguments. The function is supposed to return a new array made up of `num` copies of `arr`. 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!).
# --hints--
`copyMachine([true, false, true], 2)` should return `[[true, false, true], [true, false, true]]`
```js
assert.deepEqual(copyMachine([true, false, true], 2), [
[true, false, true],
[true, false, true]
]);
```
`copyMachine([1, 2, 3], 5)` should return `[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]`
```js
assert.deepEqual(copyMachine([1, 2, 3], 5), [
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]
]);
```
`copyMachine([true, true, null], 1)` should return `[[true, true, null]]`
```js
assert.deepEqual(copyMachine([true, true, null], 1), [[true, true, null]]);
```
`copyMachine(["it works"], 3)` should return `[["it works"], ["it works"], ["it works"]]`
```js
assert.deepEqual(copyMachine(['it works'], 3), [
['it works'],
['it works'],
['it works']
]);
```
The `copyMachine` function should utilize the `spread operator` with array `arr`
```js
assert(__helpers.removeJSComments(code).match(/\.\.\.arr/));
```
# --seed--
## --seed-contents--
```js
function copyMachine(arr, num) {
let newArr = [];
while (num >= 1) {
// Only change code below this line
// Only change code above this line
num--;
}
return newArr;
}
console.log(copyMachine([true, false, true], 2));
```
# --solutions--
```js
function copyMachine(arr,num){
let newArr=[];
while(num >=1){
newArr.push([...arr]);
num--;
}
return newArr;
}
console.log(copyMachine([true, false, true], 2));
```

View File

@ -0,0 +1,65 @@
---
id: 587d7b7a367417b2b2512b12
title: Copy Array Items Using slice()
challengeType: 1
forumTopicId: 301158
dashedName: copy-array-items-using-slice
---
# --description--
The next method we will cover is `slice()`. Rather than modifying an array, `slice()` copies or *extracts* a given number of elements to a new array, leaving the array it is called upon untouched. `slice()` takes only 2 parameters — 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:
```js
let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];
let todaysWeather = weatherConditions.slice(1, 3);
// todaysWeather equals ['snow', 'sleet'];
// weatherConditions still equals ['rain', 'snow', 'sleet', 'hail', 'clear']
```
In effect, we have created a new array by extracting elements from an existing array.
# --instructions--
We have defined a function, `forecast`, that takes an array as an argument. Modify the function using `slice()` to extract information from the argument array and return a new array that contains the elements `'warm'` and `'sunny'`.
# --hints--
`forecast` should return `["warm", "sunny"]`
```js
assert.deepEqual(
forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']),
['warm', 'sunny']
);
```
The `forecast` function should utilize the `slice()` method
```js
assert(/\.slice\(/.test(code));
```
# --seed--
## --seed-contents--
```js
function forecast(arr) {
// Only change code below this line
return arr;
}
// Only change code above this line
console.log(forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']));
```
# --solutions--
```js
function forecast(arr) {
return arr.slice(2,4);
}
```

View File

@ -0,0 +1,216 @@
---
id: 587d7b7b367417b2b2512b16
title: Create complex multi-dimensional arrays
challengeType: 1
forumTopicId: 301159
dashedName: create-complex-multi-dimensional-arrays
---
# --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:
```js
let nestedArray = [ // top, or first level - the outer most array
['deep'], // an array within an array, 2 levels of depth
[
['deeper'], ['deeper'] // 2 arrays nested 3 levels deep
],
[
[
['deepest'], ['deepest'] // 2 arrays nested 4 levels deep
],
[
[
['deepest-est?'] // an array nested 5 levels deep
]
]
]
];
```
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:
```js
console.log(nestedArray[2][1][0][0][0]);
// logs: deepest-est?
```
And now that we know where that piece of data is, we can reset it if we need to:
```js
nestedArray[2][1][0][0][0] = 'deeper still';
console.log(nestedArray[2][1][0][0][0]);
// now logs: deeper still
```
# --instructions--
We have defined a variable, `myNestedArray`, set equal to an array. Modify `myNestedArray`, 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 `'deep'`, on the fourth level, include the string `'deeper'`, and on the fifth level, include the string `'deepest'`.
# --hints--
`myNestedArray` should contain only numbers, booleans, and strings as data elements
```js
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
);
```
`myNestedArray` should have exactly 5 levels of depth
```js
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
);
```
`myNestedArray` should contain exactly one occurrence of the string `"deep"` on an array nested 3 levels deep
```js
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
);
```
`myNestedArray` should contain exactly one occurrence of the string `"deeper"` on an array nested 4 levels deep
```js
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
);
```
`myNestedArray` should contain exactly one occurrence of the string `"deepest"` on an array nested 5 levels deep
```js
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
);
```
# --seed--
## --seed-contents--
```js
let myNestedArray = [
// Only 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']
// Only change code above this line
];
```
# --solutions--
```js
let myNestedArray = [
['unshift', ['deep', ['deeper', ['deepest']]],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']
];
```

View File

@ -0,0 +1,111 @@
---
id: 587d7b7d367417b2b2512b1e
title: Generate an Array of All Object Keys with Object.keys()
challengeType: 1
forumTopicId: 301160
dashedName: generate-an-array-of-all-object-keys-with-object-keys
---
# --description--
We can also generate an array which contains all the keys stored in an object using the `Object.keys()` 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.
# --instructions--
Finish writing the `getArrayOfUsers` function so that it returns an array containing all the properties in the object it receives as an argument.
# --hints--
The `users` object should only contain the keys `Alan`, `Jeff`, `Sarah`, and `Ryan`
```js
assert(
'Alan' in users &&
'Jeff' in users &&
'Sarah' in users &&
'Ryan' in users &&
Object.keys(users).length === 4
);
```
The `getArrayOfUsers` function should return an array which contains all the keys in the `users` object
```js
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
);
```
# --seed--
## --seed-contents--
```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) {
// Only change code below this line
// Only change code above this line
}
console.log(getArrayOfUsers(users));
```
# --solutions--
```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) {
return Object.keys(obj);
}
console.log(getArrayOfUsers(users));
```

View File

@ -0,0 +1,139 @@
---
id: 587d7b7b367417b2b2512b15
title: Iterate Through All an Array's Items Using For Loops
challengeType: 1
forumTopicId: 301161
dashedName: iterate-through-all-an-arrays-items-using-for-loops
---
# --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 `every()`, `forEach()`, `map()`, etc.), however the technique which is most flexible and offers us the greatest amount of control is a simple `for` loop.
Consider the following:
```js
function greaterThanTen(arr) {
let newArr = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] > 10) {
newArr.push(arr[i]);
}
}
return newArr;
}
greaterThanTen([2, 12, 8, 14, 80, 0, 1]);
// returns [12, 14, 80]
```
Using a `for` 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 `10`, and returned a new array containing those items.
# --instructions--
We have defined a function, `filteredArray`, which takes `arr`, a nested array, and `elem` as arguments, and returns a new array. `elem` represents an element that may or may not be present on one or more of the arrays nested within `arr`. Modify the function, using a `for` loop, to return a filtered version of the passed array such that any array nested within `arr` containing `elem` has been removed.
# --hints--
`filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)` should return `[ [10, 8, 3], [14, 6, 23] ]`
```js
assert.deepEqual(
filteredArray(
[
[10, 8, 3],
[14, 6, 23],
[3, 18, 6]
],
18
),
[
[10, 8, 3],
[14, 6, 23]
]
);
```
`filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2)` should return `[ ["flutes", 4] ]`
```js
assert.deepEqual(
filteredArray(
[
['trumpets', 2],
['flutes', 4],
['saxophones', 2]
],
2
),
[['flutes', 4]]
);
```
`filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter")` should return `[ ["amy", "beth", "sam"] ]`
```js
assert.deepEqual(
filteredArray(
[
['amy', 'beth', 'sam'],
['dave', 'sean', 'peter']
],
'peter'
),
[['amy', 'beth', 'sam']]
);
```
`filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)` should return `[ ]`
```js
assert.deepEqual(
filteredArray(
[
[3, 2, 3],
[1, 6, 3],
[3, 13, 26],
[19, 3, 9]
],
3
),
[]
);
```
The `filteredArray` function should utilize a `for` loop
```js
assert.notStrictEqual(filteredArray.toString().search(/for/), -1);
```
# --seed--
## --seed-contents--
```js
function filteredArray(arr, elem) {
let newArr = [];
// Only change code below this line
// Only change code above this line
return newArr;
}
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));
```
# --solutions--
```js
function filteredArray(arr, elem) {
let newArr = [];
for (let i = 0; i<arr.length; i++) {
if (arr[i].indexOf(elem) < 0) {
newArr.push(arr[i]);
}
}
return newArr;
}
```

View File

@ -0,0 +1,140 @@
---
id: 587d7b7d367417b2b2512b1d
title: Iterate Through the Keys of an Object with a for...in Statement
challengeType: 1
forumTopicId: 301162
dashedName: iterate-through-the-keys-of-an-object-with-a-for---in-statement
---
# --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 `users` object, this could look like:
```js
for (let user in users) {
console.log(user);
}
// logs:
Alan
Jeff
Sarah
Ryan
```
In this statement, we defined a variable `user`, 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. **NOTE:** Objects do not maintain an ordering to stored keys like arrays do; thus a key's position on an object, or the relative order in which it appears, is irrelevant when referencing or accessing that key.
# --instructions--
We've defined a function `countOnline` which accepts one argument (a users object). Use a <dfn>for...in</dfn> statement within this function to loop through the users object passed into the function and return the number of users whose `online` property is set to `true`. An example of a users object which could be passed to `countOnline` is shown below. Each user will have an `online` property with either a `true` or `false` value.
```js
{
Alan: {
online: false
},
Jeff: {
online: true
},
Sarah: {
online: false
}
}
```
# --hints--
The function `countOnline` should use a `for in` statement to iterate through the object keys of the object passed to it.
```js
assert(
code.match(
/for\s*\(\s*(var|let|const)\s+[a-zA-Z_$]\w*\s+in\s+[a-zA-Z_$]\w*\s*\)/
)
);
```
The function `countOnline` should return `1` when the object `{ Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } }` is passed to it
```js
assert(countOnline(usersObj1) === 1);
```
The function `countOnline` should return `2` when the object `{ Alan: { online: true }, Jeff: { online: false }, Sarah: { online: true } }` is passed to it
```js
assert(countOnline(usersObj2) === 2);
```
The function `countOnline` should return `0` when the object `{ Alan: { online: false }, Jeff: { online: false }, Sarah: { online: false } }` is passed to it
```js
assert(countOnline(usersObj3) === 0);
```
# --seed--
## --after-user-code--
```js
const usersObj1 = {
Alan: {
online: false
},
Jeff: {
online: true
},
Sarah: {
online: false
}
}
const usersObj2 = {
Alan: {
online: true
},
Jeff: {
online: false
},
Sarah: {
online: true
}
}
const usersObj3 = {
Alan: {
online: false
},
Jeff: {
online: false
},
Sarah: {
online: false
}
}
```
## --seed-contents--
```js
function countOnline(usersObj) {
// Only change code below this line
// Only change code above this line
}
```
# --solutions--
```js
function countOnline(usersObj) {
let online = 0;
for(let user in usersObj){
if(usersObj[user].online) {
online++;
}
}
return online;
}
```

View File

@ -0,0 +1,112 @@
---
id: 587d7b7d367417b2b2512b1f
title: Modify an Array Stored in an Object
challengeType: 1
forumTopicId: 301163
dashedName: modify-an-array-stored-in-an-object
---
# --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 Data Structures lessons located in the Coding Interview Prep section of 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!
# --instructions--
Take a look at the object we've provided in the code editor. The `user` object contains three keys. The `data` key contains five keys, one of which contains an array of `friends`. From this, you can see how flexible objects are as data structures. We've started writing a function `addFriend`. Finish writing it so that it takes a `user` object and adds the name of the `friend` argument to the array stored in `user.data.friends` and returns that array.
# --hints--
The `user` object should have `name`, `age`, and `data` keys.
```js
assert('name' in user && 'age' in user && 'data' in user);
```
The `addFriend` function should accept a `user` object and a `friend` string as arguments and add the friend to the array of `friends` in the `user` object.
```js
assert(
(function () {
let L1 = user.data.friends.length;
addFriend(user, 'Sean');
let L2 = user.data.friends.length;
return L2 === L1 + 1;
})()
);
```
`addFriend(user, "Pete")` should return `["Sam", "Kira", "Tomo", "Pete"]`.
```js
assert.deepEqual(
(function () {
delete user.data.friends;
user.data.friends = ['Sam', 'Kira', 'Tomo'];
return addFriend(user, 'Pete');
})(),
['Sam', 'Kira', 'Tomo', 'Pete']
);
```
# --seed--
## --seed-contents--
```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) {
// Only change code below this line
// Only change code above this line
}
console.log(addFriend(user, 'Pete'));
```
# --solutions--
```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) {
userObj.data.friends.push(friend);
return userObj.data.friends;
}
```

View File

@ -0,0 +1,101 @@
---
id: 587d7b7c367417b2b2512b19
title: Modify an Object Nested Within an Object
challengeType: 1
forumTopicId: 301164
dashedName: modify-an-object-nested-within-an-object
---
# --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:
```js
let nestedObject = {
id: 28802695164,
date: 'December 31, 2016',
data: {
totalUsers: 99,
online: 80,
onlineStatus: {
active: 67,
away: 13,
busy: 8
}
}
};
```
`nestedObject` has three properties: `id` (value is a number), `date` (value is a string), and `data` (value is an object with its nested structure). While structures can quickly become complex, we can still use the same notations to access the information we need. To assign the value `10` to the `busy` property of the nested `onlineStatus` object, we use dot notation to reference the property:
```js
nestedObject.data.onlineStatus.busy = 10;
```
# --instructions--
Here we've defined an object `userActivity`, which includes another object nested within it. Set the value of the `online` key to `45`.
# --hints--
`userActivity` should have `id`, `date` and `data` properties.
```js
assert(
'id' in userActivity && 'date' in userActivity && 'data' in userActivity
);
```
`userActivity` should have a `data` key set to an object with keys `totalUsers` and `online`.
```js
assert('totalUsers' in userActivity.data && 'online' in userActivity.data);
```
The `online` property nested in the `data` key of `userActivity` should be set to `45`
```js
assert(userActivity.data.online === 45);
```
The `online` property should be set using dot or bracket notation.
```js
assert.strictEqual(code.search(/online: 45/), -1);
```
# --seed--
## --seed-contents--
```js
let userActivity = {
id: 23894201352,
date: 'January 1, 2017',
data: {
totalUsers: 51,
online: 42
}
};
// Only change code below this line
// Only change code above this line
console.log(userActivity);
```
# --solutions--
```js
let userActivity = {
id: 23894201352,
date: 'January 1, 2017',
data: {
totalUsers: 51,
online: 42
}
};
userActivity.data.online = 45;
```

View File

@ -0,0 +1,82 @@
---
id: 587d78b2367417b2b2512b0f
title: Remove Items from an Array with pop() and shift()
challengeType: 1
forumTopicId: 301165
dashedName: remove-items-from-an-array-with-pop-and-shift
---
# --description--
Both `push()` and `unshift()` have corresponding methods that are nearly functional opposites: `pop()` and `shift()`. As you may have guessed by now, instead of adding, `pop()` *removes* an element from the end of an array, while `shift()` removes an element from the beginning. The key difference between `pop()` and `shift()` and their cousins `push()` and `unshift()`, 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:
```js
let greetings = ['whats up?', 'hello', 'see ya!'];
greetings.pop();
// now equals ['whats up?', 'hello']
greetings.shift();
// now equals ['hello']
```
We can also return the value of the removed element with either method like this:
```js
let popped = greetings.pop();
// returns 'hello'
// greetings now equals []
```
# --instructions--
We have defined a function, `popShift`, which takes an array as an argument and returns a new array. Modify the function, using `pop()` and `shift()`, 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.
# --hints--
`popShift(["challenge", "is", "not", "complete"])` should return `["challenge", "complete"]`
```js
assert.deepEqual(popShift(['challenge', 'is', 'not', 'complete']), [
'challenge',
'complete'
]);
```
The `popShift` function should utilize the `pop()` method
```js
assert.notStrictEqual(popShift.toString().search(/\.pop\(/), -1);
```
The `popShift` function should utilize the `shift()` method
```js
assert.notStrictEqual(popShift.toString().search(/\.shift\(/), -1);
```
# --seed--
## --seed-contents--
```js
function popShift(arr) {
let popped; // Change this line
let shifted; // Change this line
return [shifted, popped];
}
console.log(popShift(['challenge', 'is', 'not', 'complete']));
```
# --solutions--
```js
function popShift(arr) {
let popped = arr.pop(); // Change this line
let shifted = arr.shift(); // Change this line
return [shifted, popped];
}
```

View File

@ -0,0 +1,86 @@
---
id: 587d78b2367417b2b2512b10
title: Remove Items Using splice()
challengeType: 1
forumTopicId: 301166
dashedName: remove-items-using-splice
---
# --description--
Ok, so we've learned how to remove elements from the beginning and end of arrays using `shift()` and `pop()`, 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 `splice()` comes in. `splice()` allows us to do just that: **remove any number of consecutive elements** from anywhere in an array.
`splice()` can take up to 3 parameters, but for now, we'll focus on just the first 2. The first two parameters of `splice()` are integers which represent indexes, or positions, of the array that `splice()` is being called upon. And remember, arrays are *zero-indexed*, so to indicate the first element of an array, we would use `0`. `splice()`'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:
```js
let array = ['today', 'was', 'not', 'so', 'great'];
array.splice(2, 2);
// remove 2 elements beginning with the 3rd element
// array now equals ['today', 'was', 'great']
```
`splice()` not only modifies the array it's being called on, but it also returns a new array containing the value of the removed elements:
```js
let array = ['I', 'am', 'feeling', 'really', 'happy'];
let newArray = array.splice(3, 2);
// newArray equals ['really', 'happy']
```
# --instructions--
We've initialized an array `arr`. Use `splice()` to remove elements from `arr`, so that it only contains elements that sum to the value of `10`.
# --hints--
You should not change the original line of `const arr = [2, 4, 5, 1, 7, 5, 2, 1];`.
```js
assert(
__helpers.removeWhiteSpace(code).match(/constarr=\[2,4,5,1,7,5,2,1\];?/)
);
```
`arr` should only contain elements that sum to `10`.
```js
assert.strictEqual(
arr.reduce((a, b) => a + b),
10
);
```
Your code should utilize the `splice()` method on `arr`.
```js
assert(__helpers.removeWhiteSpace(code).match(/arr\.splice\(/));
```
The splice should only remove elements from `arr` and not add any additional elements to `arr`.
```js
assert(
!__helpers.removeWhiteSpace(code).match(/arr\.splice\(\d+,\d+,\d+.*\)/g)
);
```
# --seed--
## --seed-contents--
```js
const arr = [2, 4, 5, 1, 7, 5, 2, 1];
// Only change code below this line
// Only change code above this line
console.log(arr);
```
# --solutions--
```js
const arr = [2, 4, 5, 1, 7, 5, 2, 1];
arr.splice(1, 4);
```

View File

@ -0,0 +1,94 @@
---
id: 587d7b7e367417b2b2512b20
title: Use an Array to Store a Collection of Data
challengeType: 1
forumTopicId: 301167
dashedName: use-an-array-to-store-a-collection-of-data
---
# --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:
```js
let simpleArray = ['one', 2, 'three', true, false, undefined, null];
console.log(simpleArray.length);
// logs 7
```
All arrays have a length property, which as shown above, can be very easily accessed with the syntax `Array.length`. 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.
```js
let complexArray = [
[
{
one: 1,
two: 2
},
{
three: 3,
four: 4
}
],
[
{
a: "a",
b: "b"
},
{
c: "c",
d: "d"
}
]
];
```
# --instructions--
We have defined a variable called `yourArray`. Complete the statement by assigning an array of at least 5 elements in length to the `yourArray` variable. Your array should contain at least one <dfn>string</dfn>, one <dfn>number</dfn>, and one <dfn>boolean</dfn>.
# --hints--
`yourArray` should be an array.
```js
assert.strictEqual(Array.isArray(yourArray), true);
```
`yourArray` should be at least 5 elements long.
```js
assert.isAtLeast(yourArray.length, 5);
```
`yourArray` should contain at least one `boolean`.
```js
assert(yourArray.filter((el) => typeof el === 'boolean').length >= 1);
```
`yourArray` should contain at least one `number`.
```js
assert(yourArray.filter((el) => typeof el === 'number').length >= 1);
```
`yourArray` should contain at least one `string`.
```js
assert(yourArray.filter((el) => typeof el === 'string').length >= 1);
```
# --seed--
## --seed-contents--
```js
let yourArray; // Change this line
```
# --solutions--
```js
let yourArray = ['a string', 100, true, ['one', 2], 'another string'];
```

View File

@ -0,0 +1,86 @@
---
id: 587d7b7c367417b2b2512b1b
title: Use the delete Keyword to Remove Object Properties
challengeType: 1
forumTopicId: 301168
dashedName: use-the-delete-keyword-to-remove-object-properties
---
# --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, ***and***, 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 *remove* a key-value pair from an object.
Let's revisit our `foods` object example one last time. If we wanted to remove the `apples` key, we can remove it by using the `delete` keyword like this:
```js
delete foods.apples;
```
# --instructions--
Use the delete keyword to remove the `oranges`, `plums`, and `strawberries` keys from the `foods` object.
# --hints--
The `foods` object should only have three keys: `apples`, `grapes`, and `bananas`.
```js
assert(
!foods.hasOwnProperty('oranges') &&
!foods.hasOwnProperty('plums') &&
!foods.hasOwnProperty('strawberries') &&
Object.keys(foods).length === 3
);
```
The `oranges`, `plums`, and `strawberries` keys should be removed using `delete`.
```js
assert(
code.search(/oranges:/) !== -1 &&
code.search(/plums:/) !== -1 &&
code.search(/strawberries:/) !== -1
);
```
# --seed--
## --seed-contents--
```js
let foods = {
apples: 25,
oranges: 32,
plums: 28,
bananas: 13,
grapes: 35,
strawberries: 27
};
// Only change code below this line
// Only change code above this line
console.log(foods);
```
# --solutions--
```js
let foods = {
apples: 25,
oranges: 32,
plums: 28,
bananas: 13,
grapes: 35,
strawberries: 27
};
delete foods.oranges;
delete foods.plums;
delete foods.strawberries;
console.log(foods);
```

View File

@ -0,0 +1,89 @@
---
id: 56bbb991ad1ed5201cd392ca
title: Access Array Data with Indexes
challengeType: 1
videoUrl: 'https://scrimba.com/c/cBZQbTz'
forumTopicId: 16158
dashedName: access-array-data-with-indexes
---
# --description--
We can access the data inside arrays using <dfn>indexes</dfn>.
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 has an index of `0`.
<br>
**Example**
```js
var array = [50,60,70];
array[0]; // equals 50
var data = array[1]; // equals 60
```
**Note**
There shouldn't be any spaces between the array name and the square brackets, like `array [0]`. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.
# --instructions--
Create a variable called `myData` and set it to equal the first value of `myArray` using bracket notation.
# --hints--
The variable `myData` should equal the first value of `myArray`.
```js
assert(
(function () {
if (
typeof myArray !== 'undefined' &&
typeof myData !== 'undefined' &&
myArray[0] === myData
) {
return true;
} else {
return false;
}
})()
);
```
The data in variable `myArray` should be accessed using bracket notation.
```js
assert(
(function () {
if (code.match(/\s*=\s*myArray\[0\]/g)) {
return true;
} else {
return false;
}
})()
);
```
# --seed--
## --after-user-code--
```js
if(typeof myArray !== "undefined" && typeof myData !== "undefined"){(function(y,z){return 'myArray = ' + JSON.stringify(y) + ', myData = ' + JSON.stringify(z);})(myArray, myData);}
```
## --seed-contents--
```js
// Setup
var myArray = [50,60,70];
// Only change code below this line
```
# --solutions--
```js
var myArray = [50,60,70];
var myData = myArray[0];
```

View File

@ -0,0 +1,72 @@
---
id: 56592a60ddddeae28f7aa8e1
title: Access Multi-Dimensional Arrays With Indexes
challengeType: 1
videoUrl: 'https://scrimba.com/c/ckND4Cq'
forumTopicId: 16159
dashedName: access-multi-dimensional-arrays-with-indexes
---
# --description--
One way to think of a <dfn>multi-dimensional</dfn> array, is as an *array of arrays*. 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.
**Example**
```js
var arr = [
[1,2,3],
[4,5,6],
[7,8,9],
[[10,11,12], 13, 14]
];
arr[3]; // equals [[10,11,12], 13, 14]
arr[3][0]; // equals [10,11,12]
arr[3][0][1]; // equals 11
```
**Note**
There shouldn't be any spaces between the array name and the square brackets, like `array [0][0]` and even this `array [0] [0]` is not allowed. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.
# --instructions--
Using bracket notation select an element from `myArray` such that `myData` is equal to `8`.
# --hints--
`myData` should be equal to `8`.
```js
assert(myData === 8);
```
You should be using bracket notation to read the correct value from `myArray`.
```js
assert(/myData=myArray\[2\]\[1\]/.test(__helpers.removeWhiteSpace(code)));
```
# --seed--
## --after-user-code--
```js
if(typeof myArray !== "undefined"){(function(){return "myData: " + myData + " myArray: " + JSON.stringify(myArray);})();}
```
## --seed-contents--
```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];
```
# --solutions--
```js
var myArray = [[1,2,3],[4,5,6], [7,8,9], [[10,11,12], 13, 14]];
var myData = myArray[2][1];
```

View File

@ -0,0 +1,123 @@
---
id: 56533eb9ac21ba0edf2244cd
title: Accessing Nested Arrays
challengeType: 1
videoUrl: 'https://scrimba.com/c/cLeGDtZ'
forumTopicId: 16160
dashedName: accessing-nested-arrays
---
# --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:
```js
var ourPets = [
{
animalType: "cat",
names: [
"Meowzer",
"Fluffy",
"Kit-Cat"
]
},
{
animalType: "dog",
names: [
"Spot",
"Bowser",
"Frankie"
]
}
];
ourPets[0].names[1]; // "Fluffy"
ourPets[1].names[0]; // "Spot"
```
# --instructions--
Retrieve the second tree from the variable `myPlants` using object dot and array bracket notation.
# --hints--
`secondTree` should equal "pine".
```js
assert(secondTree === 'pine');
```
Your code should use dot and bracket notation to access `myPlants`.
```js
assert(/=\s*myPlants\[1\].list\[1\]/.test(code));
```
# --seed--
## --after-user-code--
```js
(function(x) {
if(typeof x != 'undefined') {
return "secondTree = " + x;
}
return "secondTree is undefined";
})(secondTree);
```
## --seed-contents--
```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
```
# --solutions--
```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];
```

View File

@ -0,0 +1,98 @@
---
id: 56533eb9ac21ba0edf2244cc
title: Accessing Nested Objects
challengeType: 1
videoUrl: 'https://scrimba.com/c/cRnRnfa'
forumTopicId: 16161
dashedName: accessing-nested-objects
---
# --description--
The sub-properties of objects can be accessed by chaining together the dot or bracket notation.
Here is a nested object:
```js
var ourStorage = {
"desk": {
"drawer": "stapler"
},
"cabinet": {
"top drawer": {
"folder1": "a file",
"folder2": "secrets"
},
"bottom drawer": "soda"
}
};
ourStorage.cabinet["top drawer"].folder2; // "secrets"
ourStorage.desk.drawer; // "stapler"
```
# --instructions--
Access the `myStorage` object and assign the contents of the `glove box` property to the `gloveBoxContents` variable. Use dot notation for all properties where possible, otherwise use bracket notation.
# --hints--
`gloveBoxContents` should equal "maps".
```js
assert(gloveBoxContents === 'maps');
```
Your code should use dot and bracket notation to access `myStorage`.
```js
assert(/=\s*myStorage\.car\.inside\[\s*("|')glove box\1\s*\]/g.test(code));
```
# --seed--
## --after-user-code--
```js
(function(x) {
if(typeof x != 'undefined') {
return "gloveBoxContents = " + x;
}
return "gloveBoxContents is undefined";
})(gloveBoxContents);
```
## --seed-contents--
```js
// Setup
var myStorage = {
"car": {
"inside": {
"glove box": "maps",
"passenger seat": "crumbs"
},
"outside": {
"trunk": "jack"
}
}
};
var gloveBoxContents = undefined; // Change this line
```
# --solutions--
```js
var myStorage = {
"car":{
"inside":{
"glove box":"maps",
"passenger seat":"crumbs"
},
"outside":{
"trunk":"jack"
}
}
};
var gloveBoxContents = myStorage.car.inside["glove box"];
```

View File

@ -0,0 +1,101 @@
---
id: 56533eb9ac21ba0edf2244c8
title: Accessing Object Properties with Bracket Notation
challengeType: 1
videoUrl: 'https://scrimba.com/c/cBvmEHP'
forumTopicId: 16163
dashedName: accessing-object-properties-with-bracket-notation
---
# --description--
The second way to access the properties of an object is bracket notation (`[]`). 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:
```js
var myObj = {
"Space Name": "Kirk",
"More Space": "Spock",
"NoSpace": "USS Enterprise"
};
myObj["Space Name"]; // Kirk
myObj['More Space']; // Spock
myObj["NoSpace"]; // USS Enterprise
```
Note that property names with spaces in them must be in quotes (single or double).
# --instructions--
Read the values of the properties `"an entree"` and `"the drink"` of `testObj` using bracket notation and assign them to `entreeValue` and `drinkValue` respectively.
# --hints--
`entreeValue` should be a string
```js
assert(typeof entreeValue === 'string');
```
The value of `entreeValue` should be `"hamburger"`
```js
assert(entreeValue === 'hamburger');
```
`drinkValue` should be a string
```js
assert(typeof drinkValue === 'string');
```
The value of `drinkValue` should be `"water"`
```js
assert(drinkValue === 'water');
```
You should use bracket notation twice
```js
assert(code.match(/testObj\s*?\[('|")[^'"]+\1\]/g).length > 1);
```
# --seed--
## --after-user-code--
```js
(function(a,b) { return "entreeValue = '" + a + "', drinkValue = '" + b + "'"; })(entreeValue,drinkValue);
```
## --seed-contents--
```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
```
# --solutions--
```js
var testObj = {
"an entree": "hamburger",
"my side": "veggies",
"the drink": "water"
};
var entreeValue = testObj["an entree"];
var drinkValue = testObj['the drink'];
```

View File

@ -0,0 +1,98 @@
---
id: 56533eb9ac21ba0edf2244c7
title: Accessing Object Properties with Dot Notation
challengeType: 1
videoUrl: 'https://scrimba.com/c/cGryJs8'
forumTopicId: 16164
dashedName: accessing-object-properties-with-dot-notation
---
# --description--
There are two ways to access the properties of an object: dot notation (`.`) and bracket notation (`[]`), 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 (`.`) to read an object's property:
```js
var myObj = {
prop1: "val1",
prop2: "val2"
};
var prop1val = myObj.prop1; // val1
var prop2val = myObj.prop2; // val2
```
# --instructions--
Read in the property values of `testObj` using dot notation. Set the variable `hatValue` equal to the object's property `hat` and set the variable `shirtValue` equal to the object's property `shirt`.
# --hints--
`hatValue` should be a string
```js
assert(typeof hatValue === 'string');
```
The value of `hatValue` should be `"ballcap"`
```js
assert(hatValue === 'ballcap');
```
`shirtValue` should be a string
```js
assert(typeof shirtValue === 'string');
```
The value of `shirtValue` should be `"jersey"`
```js
assert(shirtValue === 'jersey');
```
You should use dot notation twice
```js
assert(code.match(/testObj\.\w+/g).length > 1);
```
# --seed--
## --after-user-code--
```js
(function(a,b) { return "hatValue = '" + a + "', shirtValue = '" + b + "'"; })(hatValue,shirtValue);
```
## --seed-contents--
```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
```
# --solutions--
```js
var testObj = {
"hat": "ballcap",
"shirt": "jersey",
"shoes": "cleats"
};
var hatValue = testObj.hat;
var shirtValue = testObj.shirt;
```

View File

@ -0,0 +1,117 @@
---
id: 56533eb9ac21ba0edf2244c9
title: Accessing Object Properties with Variables
challengeType: 1
videoUrl: 'https://scrimba.com/c/cnQyKur'
forumTopicId: 16165
dashedName: accessing-object-properties-with-variables
---
# --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:
```js
var dogs = {
Fido: "Mutt", Hunter: "Doberman", Snoopie: "Beagle"
};
var myDog = "Hunter";
var myBreed = dogs[myDog];
console.log(myBreed); // "Doberman"
```
Another way you can use this concept is when the property's name is collected dynamically during the program execution, as follows:
```js
var someObj = {
propName: "John"
};
function propPrefix(str) {
var s = "prop";
return s + str;
}
var someProp = propPrefix("Name"); // someProp now holds the value 'propName'
console.log(someObj[someProp]); // "John"
```
Note that we do *not* use quotes around the variable name when using it to access the property because we are using the *value* of the variable, not the *name*.
# --instructions--
Set the `playerNumber` variable to `16`. Then, use the variable to look up the player's name and assign it to `player`.
# --hints--
`playerNumber` should be a number
```js
assert(typeof playerNumber === 'number');
```
The variable `player` should be a string
```js
assert(typeof player === 'string');
```
The value of `player` should be "Montana"
```js
assert(player === 'Montana');
```
You should use bracket notation to access `testObj`
```js
assert(/testObj\s*?\[.*?\]/.test(code));
```
You should not assign the value `Montana` to the variable `player` directly.
```js
assert(!code.match(/player\s*=\s*"|\'\s*Montana\s*"|\'\s*;/gi));
```
You should be using the variable `playerNumber` in your bracket notation
```js
assert(/testObj\s*?\[\s*playerNumber\s*\]/.test(code));
```
# --seed--
## --after-user-code--
```js
if(typeof player !== "undefined"){(function(v){return v;})(player);}
```
## --seed-contents--
```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
```
# --solutions--
```js
var testObj = {
12: "Namath",
16: "Montana",
19: "Unitas"
};
var playerNumber = 16;
var player = testObj[playerNumber];
```

View File

@ -0,0 +1,87 @@
---
id: 56bbb991ad1ed5201cd392d2
title: Add New Properties to a JavaScript Object
challengeType: 1
videoUrl: 'https://scrimba.com/c/cQe38UD'
forumTopicId: 301169
dashedName: add-new-properties-to-a-javascript-object
---
# --description--
You can add new properties to existing JavaScript objects the same way you would modify them.
Here's how we would add a `"bark"` property to `ourDog`:
`ourDog.bark = "bow-wow";`
or
`ourDog["bark"] = "bow-wow";`
Now when we evaluate `ourDog.bark`, we'll get his bark, "bow-wow".
Example:
```js
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"]
};
ourDog.bark = "bow-wow";
```
# --instructions--
Add a `"bark"` property to `myDog` and set it to a dog sound, such as "woof". You may use either dot or bracket notation.
# --hints--
You should add the property `"bark"` to `myDog`.
```js
assert(myDog.bark !== undefined);
```
You should not add `"bark"` to the setup section.
```js
assert(!/bark[^\n]:/.test(code));
```
# --seed--
## --after-user-code--
```js
(function(z){return z;})(myDog);
```
## --seed-contents--
```js
// Setup
var myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"]
};
// Only change code below this line
```
# --solutions--
```js
var myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"]
};
myDog.bark = "Woof Woof";
```

View File

@ -0,0 +1,60 @@
---
id: cf1111c1c11feddfaeb3bdef
title: Add Two Numbers with JavaScript
challengeType: 1
videoUrl: 'https://scrimba.com/c/cM2KBAG'
forumTopicId: 16650
dashedName: add-two-numbers-with-javascript
---
# --description--
`Number` is a data type in JavaScript which represents numeric data.
Now let's try to add two numbers using JavaScript.
JavaScript uses the `+` symbol as an addition operator when placed between two numbers.
**Example:**
```js
myVar = 5 + 10; // assigned 15
```
# --instructions--
Change the `0` so that sum will equal `20`.
# --hints--
`sum` should equal `20`.
```js
assert(sum === 20);
```
You should use the `+` operator.
```js
assert(/\+/.test(code));
```
# --seed--
## --after-user-code--
```js
(function(z){return 'sum = '+z;})(sum);
```
## --seed-contents--
```js
var sum = 10 + 0;
```
# --solutions--
```js
var sum = 10 + 10;
```

View File

@ -0,0 +1,128 @@
---
id: 56533eb9ac21ba0edf2244de
title: Adding a Default Option in Switch Statements
challengeType: 1
videoUrl: 'https://scrimba.com/c/c3JvVfg'
forumTopicId: 16653
dashedName: adding-a-default-option-in-switch-statements
---
# --description--
In a `switch` statement you may not be able to specify all possible values as `case` statements. Instead, you can add the `default` statement which will be executed if no matching `case` statements are found. Think of it like the final `else` statement in an `if/else` chain.
A `default` statement should be the last case.
```js
switch (num) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
default:
defaultStatement;
break;
}
```
# --instructions--
Write a switch statement to set `answer` for the following conditions:
`"a"` - "apple"
`"b"` - "bird"
`"c"` - "cat"
`default` - "stuff"
# --hints--
`switchOfStuff("a")` should have a value of "apple"
```js
assert(switchOfStuff('a') === 'apple');
```
`switchOfStuff("b")` should have a value of "bird"
```js
assert(switchOfStuff('b') === 'bird');
```
`switchOfStuff("c")` should have a value of "cat"
```js
assert(switchOfStuff('c') === 'cat');
```
`switchOfStuff("d")` should have a value of "stuff"
```js
assert(switchOfStuff('d') === 'stuff');
```
`switchOfStuff(4)` should have a value of "stuff"
```js
assert(switchOfStuff(4) === 'stuff');
```
You should not use any `if` or `else` statements
```js
assert(!/else/g.test(code) || !/if/g.test(code));
```
You should use a `default` statement
```js
assert(switchOfStuff('string-to-trigger-default-case') === 'stuff');
```
You should have at least 3 `break` statements
```js
assert(code.match(/break/g).length > 2);
```
# --seed--
## --seed-contents--
```js
function switchOfStuff(val) {
var answer = "";
// Only change code below this line
// Only change code above this line
return answer;
}
switchOfStuff(1);
```
# --solutions--
```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;
}
```

View File

@ -0,0 +1,77 @@
---
id: 56533eb9ac21ba0edf2244ed
title: Appending Variables to Strings
challengeType: 1
videoUrl: 'https://scrimba.com/c/cbQmZfa'
forumTopicId: 16656
dashedName: appending-variables-to-strings
---
# --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 (`+=`) operator.
Example:
```js
var anAdjective = "awesome!";
var ourStr = "freeCodeCamp is ";
ourStr += anAdjective;
// ourStr is now "freeCodeCamp is awesome!"
```
# --instructions--
Set `someAdjective` to a string of at least 3 characters and append it to `myStr` using the `+=` operator.
# --hints--
`someAdjective` should be set to a string at least 3 characters long.
```js
assert(typeof someAdjective !== 'undefined' && someAdjective.length > 2);
```
You should append `someAdjective` to `myStr` using the `+=` operator.
```js
assert(code.match(/myStr\s*\+=\s*someAdjective\s*/).length > 0);
```
# --seed--
## --after-user-code--
```js
(function(){
var output = [];
if(typeof someAdjective === 'string') {
output.push('someAdjective = "' + someAdjective + '"');
} else {
output.push('someAdjective is not a string');
}
if(typeof myStr === 'string') {
output.push('myStr = "' + myStr + '"');
} else {
output.push('myStr is not a string');
}
return output.join('\n');
})();
```
## --seed-contents--
```js
// Change code below this line
var someAdjective;
var myStr = "Learning to code is ";
```
# --solutions--
```js
var someAdjective = "neat";
var myStr = "Learning to code is ";
myStr += someAdjective;
```

View File

@ -0,0 +1,86 @@
---
id: 5ee127a03c3b35dd45426493
title: Assigning the Value of One Variable to Another
challengeType: 1
videoUrl: ''
forumTopicId: 418265
dashedName: assigning-the-value-of-one-variable-to-another
---
# --description--
After a value is assigned to a variable using the <dfn>assignment</dfn> operator, you can assign the value of that variable to another variable using the <dfn>assignment</dfn> operator.
```js
var myVar;
myVar = 5;
var myNum;
myNum = myVar;
```
The above declares a `myVar` variable with no value, then assigns it the value `5`. Next, a variable named `myNum` is declared with no value. Then, the contents of `myVar` (which is `5`) is assigned to the variable `myNum`. Now, `myNum` also has the value of `5`.
# --instructions--
Assign the contents of `a` to variable `b`.
# --hints--
You should not change code above the specified comment.
```js
assert(/var a;/.test(code) && /a = 7;/.test(code) && /var b;/.test(code));
```
`b` should have a value of 7.
```js
assert(typeof b === 'number' && b === 7);
```
`a` should be assigned to `b` with `=`.
```js
assert(/b\s*=\s*a\s*/g.test(code));
```
# --seed--
## --before-user-code--
```js
if (typeof a != 'undefined') {
a = undefined;
}
if (typeof b != 'undefined') {
b = undefined;
}
```
## --after-user-code--
```js
(function(a, b) {
return 'a = ' + a + ', b = ' + b;
})(a, b);
```
## --seed-contents--
```js
// Setup
var a;
a = 7;
var b;
// Only change code below this line
```
# --solutions--
```js
var a;
a = 7;
var b;
b = a;
```

View File

@ -0,0 +1,69 @@
---
id: 56533eb9ac21ba0edf2244c3
title: Assignment with a Returned Value
challengeType: 1
videoUrl: 'https://scrimba.com/c/ce2pEtB'
forumTopicId: 16658
dashedName: assignment-with-a-returned-value
---
# --description--
If you'll recall from our discussion of [Storing Values with the Assignment Operator](/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator), 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 `sum` which adds two numbers together, then:
`ourSum = sum(5, 12);`
will call `sum` function, which returns a value of `17` and assigns it to `ourSum` variable.
# --instructions--
Call the `processArg` function with an argument of `7` and assign its return value to the variable `processed`.
# --hints--
`processed` should have a value of `2`
```js
assert(processed === 2);
```
You should assign `processArg` to `processed`
```js
assert(/processed\s*=\s*processArg\(\s*7\s*\)/.test(code));
```
# --seed--
## --after-user-code--
```js
(function(){return "processed = " + processed})();
```
## --seed-contents--
```js
// Setup
var processed = 0;
function processArg(num) {
return (num + 3) / 5;
}
// Only change code below this line
```
# --solutions--
```js
var processed = 0;
function processArg(num) {
return (num + 3) / 5;
}
processed = processArg(7);
```

View File

@ -0,0 +1,159 @@
---
id: 56bbb991ad1ed5201cd392d0
title: Build JavaScript Objects
challengeType: 1
videoUrl: 'https://scrimba.com/c/cWGkbtd'
forumTopicId: 16769
dashedName: build-javascript-objects
---
# --description--
You may have heard the term `object` before.
Objects are similar to `arrays`, except that instead of using indexes to access and modify their data, you access the data in objects through what are called `properties`.
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:
```js
var cat = {
"name": "Whiskers",
"legs": 4,
"tails": 1,
"enemies": ["Water", "Dogs"]
};
```
In this example, all the properties are stored as strings, such as - `"name"`, `"legs"`, and `"tails"`. However, you can also use numbers as properties. You can even omit the quotes for single-word string properties, as follows:
```js
var anotherObject = {
make: "Ford",
5: "five",
"model": "focus"
};
```
However, if your object has any non-string properties, JavaScript will automatically typecast them as strings.
# --instructions--
Make an object that represents a dog called `myDog` which contains the properties `"name"` (a string), `"legs"`, `"tails"` and `"friends"`.
You can set these object properties to whatever values you want, as long as `"name"` is a string, `"legs"` and `"tails"` are numbers, and `"friends"` is an array.
# --hints--
`myDog` should contain the property `name` and it should be a `string`.
```js
assert(
(function (z) {
if (
z.hasOwnProperty('name') &&
z.name !== undefined &&
typeof z.name === 'string'
) {
return true;
} else {
return false;
}
})(myDog)
);
```
`myDog` should contain the property `legs` and it should be a `number`.
```js
assert(
(function (z) {
if (
z.hasOwnProperty('legs') &&
z.legs !== undefined &&
typeof z.legs === 'number'
) {
return true;
} else {
return false;
}
})(myDog)
);
```
`myDog` should contain the property `tails` and it should be a `number`.
```js
assert(
(function (z) {
if (
z.hasOwnProperty('tails') &&
z.tails !== undefined &&
typeof z.tails === 'number'
) {
return true;
} else {
return false;
}
})(myDog)
);
```
`myDog` should contain the property `friends` and it should be an `array`.
```js
assert(
(function (z) {
if (
z.hasOwnProperty('friends') &&
z.friends !== undefined &&
Array.isArray(z.friends)
) {
return true;
} else {
return false;
}
})(myDog)
);
```
`myDog` should only contain all the given properties.
```js
assert(
(function (z) {
return Object.keys(z).length === 4;
})(myDog)
);
```
# --seed--
## --after-user-code--
```js
(function(z){return z;})(myDog);
```
## --seed-contents--
```js
var myDog = {
// Only change code below this line
// Only change code above this line
};
```
# --solutions--
```js
var myDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"]
};
```

View File

@ -0,0 +1,149 @@
---
id: 56533eb9ac21ba0edf2244dc
title: Chaining If Else Statements
challengeType: 1
videoUrl: 'https://scrimba.com/c/caeJgsw'
forumTopicId: 16772
dashedName: chaining-if-else-statements
---
# --description--
`if/else` statements can be chained together for complex logic. Here is <dfn>pseudocode</dfn> of multiple chained `if` / `else if` statements:
```js
if (condition1) {
statement1
} else if (condition2) {
statement2
} else if (condition3) {
statement3
. . .
} else {
statementN
}
```
# --instructions--
Write chained `if`/`else if` statements to fulfill the following conditions:
`num < 5` - return "Tiny"
`num < 10` - return "Small"
`num < 15` - return "Medium"
`num < 20` - return "Large"
`num >= 20` - return "Huge"
# --hints--
You should have at least four `else` statements
```js
assert(code.match(/else/g).length > 3);
```
You should have at least four `if` statements
```js
assert(code.match(/if/g).length > 3);
```
You should have at least one `return` statement
```js
assert(code.match(/return/g).length >= 1);
```
`testSize(0)` should return "Tiny"
```js
assert(testSize(0) === 'Tiny');
```
`testSize(4)` should return "Tiny"
```js
assert(testSize(4) === 'Tiny');
```
`testSize(5)` should return "Small"
```js
assert(testSize(5) === 'Small');
```
`testSize(8)` should return "Small"
```js
assert(testSize(8) === 'Small');
```
`testSize(10)` should return "Medium"
```js
assert(testSize(10) === 'Medium');
```
`testSize(14)` should return "Medium"
```js
assert(testSize(14) === 'Medium');
```
`testSize(15)` should return "Large"
```js
assert(testSize(15) === 'Large');
```
`testSize(17)` should return "Large"
```js
assert(testSize(17) === 'Large');
```
`testSize(20)` should return "Huge"
```js
assert(testSize(20) === 'Huge');
```
`testSize(25)` should return "Huge"
```js
assert(testSize(25) === 'Huge');
```
# --seed--
## --seed-contents--
```js
function testSize(num) {
// Only change code below this line
return "Change Me";
// Only change code above this line
}
testSize(7);
```
# --solutions--
```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";
}
}
```

View File

@ -0,0 +1,61 @@
---
id: bd7123c9c441eddfaeb4bdef
title: Comment Your JavaScript Code
challengeType: 1
videoUrl: 'https://scrimba.com/c/c7ynnTp'
forumTopicId: 16783
dashedName: comment-your-javascript-code
---
# --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 `//` will tell JavaScript to ignore the remainder of the text on the current line:
```js
// This is an in-line comment.
```
You can make a multi-line comment beginning with `/*` and ending with `*/`:
```js
/* This is a
multi-line comment */
```
**Best Practice**
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—both for others *and* for your future self.
# --instructions--
Try creating one of each type of comment.
# --hints--
You should create a `//` style comment that contains at least five letters.
```js
assert(code.match(/(\/\/)...../g));
```
You should create a `/* */` style comment that contains at least five letters.
```js
assert(code.match(/(\/\*)([^\/]{5,})(?=\*\/)/gm));
```
# --seed--
## --seed-contents--
```js
```
# --solutions--
```js
// Fake Comment
/* Another Comment */
```

View File

@ -0,0 +1,89 @@
---
id: 56533eb9ac21ba0edf2244d0
title: Comparison with the Equality Operator
challengeType: 1
videoUrl: 'https://scrimba.com/c/cKyVMAL'
forumTopicId: 16784
dashedName: comparison-with-the-equality-operator
---
# --description--
There are many <dfn>comparison operators</dfn> in JavaScript. All of these operators return a boolean `true` or `false` value.
The most basic operator is the equality operator `==`. The equality operator compares two values and returns `true` if they're equivalent or `false` if they are not. Note that equality is different from assignment (`=`), which assigns the value on the right of the operator to a variable on the left.
```js
function equalityTest(myVal) {
if (myVal == 10) {
return "Equal";
}
return "Not Equal";
}
```
If `myVal` is equal to `10`, the equality operator returns `true`, so the code in the curly braces will execute, and the function will return `"Equal"`. Otherwise, the function will return `"Not Equal"`. In order for JavaScript to compare two different <dfn>data types</dfn> (for example, `numbers` and `strings`), it must convert one type to another. This is known as "Type Coercion". Once it does, however, it can compare terms as follows:
```js
1 == 1 // true
1 == 2 // false
1 == '1' // true
"3" == 3 // true
```
# --instructions--
Add the equality operator to the indicated line so that the function will return "Equal" when `val` is equivalent to `12`.
# --hints--
`testEqual(10)` should return "Not Equal"
```js
assert(testEqual(10) === 'Not Equal');
```
`testEqual(12)` should return "Equal"
```js
assert(testEqual(12) === 'Equal');
```
`testEqual("12")` should return "Equal"
```js
assert(testEqual('12') === 'Equal');
```
You should use the `==` operator
```js
assert(code.match(/==/g) && !code.match(/===/g));
```
# --seed--
## --seed-contents--
```js
// Setup
function testEqual(val) {
if (val) { // Change this line
return "Equal";
}
return "Not Equal";
}
testEqual(10);
```
# --solutions--
```js
function testEqual(val) {
if (val == 12) {
return "Equal";
}
return "Not Equal";
}
```

View File

@ -0,0 +1,111 @@
---
id: 56533eb9ac21ba0edf2244d4
title: Comparison with the Greater Than Operator
challengeType: 1
videoUrl: 'https://scrimba.com/c/cp6GbH4'
forumTopicId: 16786
dashedName: comparison-with-the-greater-than-operator
---
# --description--
The greater than operator (`>`) compares the values of two numbers. If the number to the left is greater than the number to the right, it returns `true`. Otherwise, it returns `false`.
Like the equality operator, greater than operator will convert data types of values while comparing.
**Examples**
```js
5 > 3 // true
7 > '3' // true
2 > 3 // false
'1' > 9 // false
```
# --instructions--
Add the greater than operator to the indicated lines so that the return statements make sense.
# --hints--
`testGreaterThan(0)` should return "10 or Under"
```js
assert(testGreaterThan(0) === '10 or Under');
```
`testGreaterThan(10)` should return "10 or Under"
```js
assert(testGreaterThan(10) === '10 or Under');
```
`testGreaterThan(11)` should return "Over 10"
```js
assert(testGreaterThan(11) === 'Over 10');
```
`testGreaterThan(99)` should return "Over 10"
```js
assert(testGreaterThan(99) === 'Over 10');
```
`testGreaterThan(100)` should return "Over 10"
```js
assert(testGreaterThan(100) === 'Over 10');
```
`testGreaterThan(101)` should return "Over 100"
```js
assert(testGreaterThan(101) === 'Over 100');
```
`testGreaterThan(150)` should return "Over 100"
```js
assert(testGreaterThan(150) === 'Over 100');
```
You should use the `>` operator at least twice
```js
assert(code.match(/val\s*>\s*('|")*\d+('|")*/g).length > 1);
```
# --seed--
## --seed-contents--
```js
function testGreaterThan(val) {
if (val) { // Change this line
return "Over 100";
}
if (val) { // Change this line
return "Over 10";
}
return "10 or Under";
}
testGreaterThan(10);
```
# --solutions--
```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";
}
```

View File

@ -0,0 +1,113 @@
---
id: 56533eb9ac21ba0edf2244d5
title: Comparison with the Greater Than Or Equal To Operator
challengeType: 1
videoUrl: 'https://scrimba.com/c/c6KBqtV'
forumTopicId: 16785
dashedName: comparison-with-the-greater-than-or-equal-to-operator
---
# --description--
The greater than or equal to operator (`>=`) 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 `true`. Otherwise, it returns `false`.
Like the equality operator, `greater than or equal to` operator will convert data types while comparing.
**Examples**
```js
6 >= 6 // true
7 >= '3' // true
2 >= 3 // false
'7' >= 9 // false
```
# --instructions--
Add the greater than or equal to operator to the indicated lines so that the return statements make sense.
# --hints--
`testGreaterOrEqual(0)` should return "Less than 10"
```js
assert(testGreaterOrEqual(0) === 'Less than 10');
```
`testGreaterOrEqual(9)` should return "Less than 10"
```js
assert(testGreaterOrEqual(9) === 'Less than 10');
```
`testGreaterOrEqual(10)` should return "10 or Over"
```js
assert(testGreaterOrEqual(10) === '10 or Over');
```
`testGreaterOrEqual(11)` should return "10 or Over"
```js
assert(testGreaterOrEqual(11) === '10 or Over');
```
`testGreaterOrEqual(19)` should return "10 or Over"
```js
assert(testGreaterOrEqual(19) === '10 or Over');
```
`testGreaterOrEqual(100)` should return "20 or Over"
```js
assert(testGreaterOrEqual(100) === '20 or Over');
```
`testGreaterOrEqual(21)` should return "20 or Over"
```js
assert(testGreaterOrEqual(21) === '20 or Over');
```
You should use the `>=` operator at least twice
```js
assert(code.match(/val\s*>=\s*('|")*\d+('|")*/g).length > 1);
```
# --seed--
## --seed-contents--
```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";
}
testGreaterOrEqual(10);
```
# --solutions--
```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";
}
```

View File

@ -0,0 +1,91 @@
---
id: 56533eb9ac21ba0edf2244d2
title: Comparison with the Inequality Operator
challengeType: 1
videoUrl: 'https://scrimba.com/c/cdBm9Sr'
forumTopicId: 16787
dashedName: comparison-with-the-inequality-operator
---
# --description--
The inequality operator (`!=`) is the opposite of the equality operator. It means "Not Equal" and returns `false` where equality would return `true` and *vice versa*. Like the equality operator, the inequality operator will convert data types of values while comparing.
**Examples**
```js
1 != 2 // true
1 != "1" // false
1 != '1' // false
1 != true // false
0 != false // false
```
# --instructions--
Add the inequality operator `!=` in the `if` statement so that the function will return "Not Equal" when `val` is not equivalent to `99`
# --hints--
`testNotEqual(99)` should return "Equal"
```js
assert(testNotEqual(99) === 'Equal');
```
`testNotEqual("99")` should return "Equal"
```js
assert(testNotEqual('99') === 'Equal');
```
`testNotEqual(12)` should return "Not Equal"
```js
assert(testNotEqual(12) === 'Not Equal');
```
`testNotEqual("12")` should return "Not Equal"
```js
assert(testNotEqual('12') === 'Not Equal');
```
`testNotEqual("bob")` should return "Not Equal"
```js
assert(testNotEqual('bob') === 'Not Equal');
```
You should use the `!=` operator
```js
assert(code.match(/(?!!==)!=/));
```
# --seed--
## --seed-contents--
```js
// Setup
function testNotEqual(val) {
if (val) { // Change this line
return "Not Equal";
}
return "Equal";
}
testNotEqual(10);
```
# --solutions--
```js
function testNotEqual(val) {
if (val != 99) {
return "Not Equal";
}
return "Equal";
}
```

View File

@ -0,0 +1,106 @@
---
id: 56533eb9ac21ba0edf2244d6
title: Comparison with the Less Than Operator
challengeType: 1
videoUrl: 'https://scrimba.com/c/cNVRWtB'
forumTopicId: 16789
dashedName: comparison-with-the-less-than-operator
---
# --description--
The <dfn>less than</dfn> operator (`<`) compares the values of two numbers. If the number to the left is less than the number to the right, it returns `true`. Otherwise, it returns `false`. Like the equality operator, <dfn>less than</dfn> operator converts data types while comparing.
**Examples**
```js
2 < 5 // true
'3' < 7 // true
5 < 5 // false
3 < 2 // false
'8' < 4 // false
```
# --instructions--
Add the less than operator to the indicated lines so that the return statements make sense.
# --hints--
`testLessThan(0)` should return "Under 25"
```js
assert(testLessThan(0) === 'Under 25');
```
`testLessThan(24)` should return "Under 25"
```js
assert(testLessThan(24) === 'Under 25');
```
`testLessThan(25)` should return "Under 55"
```js
assert(testLessThan(25) === 'Under 55');
```
`testLessThan(54)` should return "Under 55"
```js
assert(testLessThan(54) === 'Under 55');
```
`testLessThan(55)` should return "55 or Over"
```js
assert(testLessThan(55) === '55 or Over');
```
`testLessThan(99)` should return "55 or Over"
```js
assert(testLessThan(99) === '55 or Over');
```
You should use the `<` operator at least twice
```js
assert(code.match(/val\s*<\s*('|")*\d+('|")*/g).length > 1);
```
# --seed--
## --seed-contents--
```js
function testLessThan(val) {
if (val) { // Change this line
return "Under 25";
}
if (val) { // Change this line
return "Under 55";
}
return "55 or Over";
}
testLessThan(10);
```
# --solutions--
```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";
}
```

View File

@ -0,0 +1,112 @@
---
id: 56533eb9ac21ba0edf2244d7
title: Comparison with the Less Than Or Equal To Operator
challengeType: 1
videoUrl: 'https://scrimba.com/c/cNVR7Am'
forumTopicId: 16788
dashedName: comparison-with-the-less-than-or-equal-to-operator
---
# --description--
The less than or equal to operator (`<=`) 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 `true`. If the number on the left is greater than the number on the right, it returns `false`. Like the equality operator, `less than or equal to` converts data types.
**Examples**
```js
4 <= 5 // true
'7' <= 7 // true
5 <= 5 // true
3 <= 2 // false
'8' <= 4 // false
```
# --instructions--
Add the less than or equal to operator to the indicated lines so that the return statements make sense.
# --hints--
`testLessOrEqual(0)` should return "Smaller Than or Equal to 12"
```js
assert(testLessOrEqual(0) === 'Smaller Than or Equal to 12');
```
`testLessOrEqual(11)` should return "Smaller Than or Equal to 12"
```js
assert(testLessOrEqual(11) === 'Smaller Than or Equal to 12');
```
`testLessOrEqual(12)` should return "Smaller Than or Equal to 12"
```js
assert(testLessOrEqual(12) === 'Smaller Than or Equal to 12');
```
`testLessOrEqual(23)` should return "Smaller Than or Equal to 24"
```js
assert(testLessOrEqual(23) === 'Smaller Than or Equal to 24');
```
`testLessOrEqual(24)` should return "Smaller Than or Equal to 24"
```js
assert(testLessOrEqual(24) === 'Smaller Than or Equal to 24');
```
`testLessOrEqual(25)` should return "More Than 24"
```js
assert(testLessOrEqual(25) === 'More Than 24');
```
`testLessOrEqual(55)` should return "More Than 24"
```js
assert(testLessOrEqual(55) === 'More Than 24');
```
You should use the `<=` operator at least twice
```js
assert(code.match(/val\s*<=\s*('|")*\d+('|")*/g).length > 1);
```
# --seed--
## --seed-contents--
```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";
}
testLessOrEqual(10);
```
# --solutions--
```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";
}
```

View File

@ -0,0 +1,80 @@
---
id: 56533eb9ac21ba0edf2244d1
title: Comparison with the Strict Equality Operator
challengeType: 1
videoUrl: 'https://scrimba.com/c/cy87atr'
forumTopicId: 16790
dashedName: comparison-with-the-strict-equality-operator
---
# --description--
Strict equality (`===`) is the counterpart to the equality operator (`==`). 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.
**Examples**
```js
3 === 3 // true
3 === '3' // false
```
In the second example, `3` is a `Number` type and `'3'` is a `String` type.
# --instructions--
Use the strict equality operator in the `if` statement so the function will return "Equal" when `val` is strictly equal to `7`
# --hints--
`testStrict(10)` should return "Not Equal"
```js
assert(testStrict(10) === 'Not Equal');
```
`testStrict(7)` should return "Equal"
```js
assert(testStrict(7) === 'Equal');
```
`testStrict("7")` should return "Not Equal"
```js
assert(testStrict('7') === 'Not Equal');
```
You should use the `===` operator
```js
assert(code.match(/(val\s*===\s*\d+)|(\d+\s*===\s*val)/g).length > 0);
```
# --seed--
## --seed-contents--
```js
// Setup
function testStrict(val) {
if (val) { // Change this line
return "Equal";
}
return "Not Equal";
}
testStrict(10);
```
# --solutions--
```js
function testStrict(val) {
if (val === 7) {
return "Equal";
}
return "Not Equal";
}
```

View File

@ -0,0 +1,83 @@
---
id: 56533eb9ac21ba0edf2244d3
title: Comparison with the Strict Inequality Operator
challengeType: 1
videoUrl: 'https://scrimba.com/c/cKekkUy'
forumTopicId: 16791
dashedName: comparison-with-the-strict-inequality-operator
---
# --description--
The strict inequality operator (`!==`) is the logical opposite of the strict equality operator. It means "Strictly Not Equal" and returns `false` where strict equality would return `true` and *vice versa*. Strict inequality will not convert data types.
**Examples**
```js
3 !== 3 // false
3 !== '3' // true
4 !== 3 // true
```
# --instructions--
Add the strict inequality operator to the `if` statement so the function will return "Not Equal" when `val` is not strictly equal to `17`
# --hints--
`testStrictNotEqual(17)` should return "Equal"
```js
assert(testStrictNotEqual(17) === 'Equal');
```
`testStrictNotEqual("17")` should return "Not Equal"
```js
assert(testStrictNotEqual('17') === 'Not Equal');
```
`testStrictNotEqual(12)` should return "Not Equal"
```js
assert(testStrictNotEqual(12) === 'Not Equal');
```
`testStrictNotEqual("bob")` should return "Not Equal"
```js
assert(testStrictNotEqual('bob') === 'Not Equal');
```
You should use the `!==` operator
```js
assert(code.match(/(val\s*!==\s*\d+)|(\d+\s*!==\s*val)/g).length > 0);
```
# --seed--
## --seed-contents--
```js
// Setup
function testStrictNotEqual(val) {
if (val) { // Change this line
return "Not Equal";
}
return "Equal";
}
testStrictNotEqual(10);
```
# --solutions--
```js
function testStrictNotEqual(val) {
if (val !== 17) {
return "Not Equal";
}
return "Equal";
}
```

View File

@ -0,0 +1,130 @@
---
id: 56533eb9ac21ba0edf2244d8
title: Comparisons with the Logical And Operator
challengeType: 1
videoUrl: 'https://scrimba.com/c/cvbRVtr'
forumTopicId: 16799
dashedName: comparisons-with-the-logical-and-operator
---
# --description--
Sometimes you will need to test more than one thing at a time. The <dfn>logical and</dfn> operator (`&&`) returns `true` 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:
```js
if (num > 5) {
if (num < 10) {
return "Yes";
}
}
return "No";
```
will only return "Yes" if `num` is greater than `5` and less than `10`. The same logic can be written as:
```js
if (num > 5 && num < 10) {
return "Yes";
}
return "No";
```
# --instructions--
Replace the two if statements with one statement, using the && operator, which will return `"Yes"` if `val` is less than or equal to `50` and greater than or equal to `25`. Otherwise, will return `"No"`.
# --hints--
You should use the `&&` operator once
```js
assert(code.match(/&&/g).length === 1);
```
You should only have one `if` statement
```js
assert(code.match(/if/g).length === 1);
```
`testLogicalAnd(0)` should return "No"
```js
assert(testLogicalAnd(0) === 'No');
```
`testLogicalAnd(24)` should return "No"
```js
assert(testLogicalAnd(24) === 'No');
```
`testLogicalAnd(25)` should return "Yes"
```js
assert(testLogicalAnd(25) === 'Yes');
```
`testLogicalAnd(30)` should return "Yes"
```js
assert(testLogicalAnd(30) === 'Yes');
```
`testLogicalAnd(50)` should return "Yes"
```js
assert(testLogicalAnd(50) === 'Yes');
```
`testLogicalAnd(51)` should return "No"
```js
assert(testLogicalAnd(51) === 'No');
```
`testLogicalAnd(75)` should return "No"
```js
assert(testLogicalAnd(75) === 'No');
```
`testLogicalAnd(80)` should return "No"
```js
assert(testLogicalAnd(80) === 'No');
```
# --seed--
## --seed-contents--
```js
function testLogicalAnd(val) {
// Only change code below this line
if (val) {
if (val) {
return "Yes";
}
}
// Only change code above this line
return "No";
}
testLogicalAnd(10);
```
# --solutions--
```js
function testLogicalAnd(val) {
if (val >= 25 && val <= 50) {
return "Yes";
}
return "No";
}
```

View File

@ -0,0 +1,135 @@
---
id: 56533eb9ac21ba0edf2244d9
title: Comparisons with the Logical Or Operator
challengeType: 1
videoUrl: 'https://scrimba.com/c/cEPrGTN'
forumTopicId: 16800
dashedName: comparisons-with-the-logical-or-operator
---
# --description--
The <dfn>logical or</dfn> operator (`||`) returns `true` if either of the <dfn>operands</dfn> is `true`. Otherwise, it returns `false`.
The <dfn>logical or</dfn> operator is composed of two pipe symbols: (`||`). This can typically be found between your Backspace and Enter keys.
The pattern below should look familiar from prior waypoints:
```js
if (num > 10) {
return "No";
}
if (num < 5) {
return "No";
}
return "Yes";
```
will return "Yes" only if `num` is between `5` and `10` (5 and 10 included). The same logic can be written as:
```js
if (num > 10 || num < 5) {
return "No";
}
return "Yes";
```
# --instructions--
Combine the two `if` statements into one statement which returns `"Outside"` if `val` is not between `10` and `20`, inclusive. Otherwise, return `"Inside"`.
# --hints--
You should use the `||` operator once
```js
assert(code.match(/\|\|/g).length === 1);
```
You should only have one `if` statement
```js
assert(code.match(/if/g).length === 1);
```
`testLogicalOr(0)` should return "Outside"
```js
assert(testLogicalOr(0) === 'Outside');
```
`testLogicalOr(9)` should return "Outside"
```js
assert(testLogicalOr(9) === 'Outside');
```
`testLogicalOr(10)` should return "Inside"
```js
assert(testLogicalOr(10) === 'Inside');
```
`testLogicalOr(15)` should return "Inside"
```js
assert(testLogicalOr(15) === 'Inside');
```
`testLogicalOr(19)` should return "Inside"
```js
assert(testLogicalOr(19) === 'Inside');
```
`testLogicalOr(20)` should return "Inside"
```js
assert(testLogicalOr(20) === 'Inside');
```
`testLogicalOr(21)` should return "Outside"
```js
assert(testLogicalOr(21) === 'Outside');
```
`testLogicalOr(25)` should return "Outside"
```js
assert(testLogicalOr(25) === 'Outside');
```
# --seed--
## --seed-contents--
```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";
}
testLogicalOr(15);
```
# --solutions--
```js
function testLogicalOr(val) {
if (val < 10 || val > 20) {
return "Outside";
}
return "Inside";
}
```

View File

@ -0,0 +1,97 @@
---
id: 56533eb9ac21ba0edf2244af
title: Compound Assignment With Augmented Addition
challengeType: 1
videoUrl: 'https://scrimba.com/c/cDR6LCb'
forumTopicId: 16661
dashedName: compound-assignment-with-augmented-addition
---
# --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:
`myVar = myVar + 5;`
to add `5` to `myVar`. 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 `+=` operator.
```js
var myVar = 1;
myVar += 5;
console.log(myVar); // Returns 6
```
# --instructions--
Convert the assignments for `a`, `b`, and `c` to use the `+=` operator.
# --hints--
`a` should equal `15`.
```js
assert(a === 15);
```
`b` should equal `26`.
```js
assert(b === 26);
```
`c` should equal `19`.
```js
assert(c === 19);
```
You should use the `+=` operator for each variable.
```js
assert(code.match(/\+=/g).length === 3);
```
You should not modify the code above the specified comment.
```js
assert(
/var a = 3;/.test(code) &&
/var b = 17;/.test(code) &&
/var c = 12;/.test(code)
);
```
# --seed--
## --after-user-code--
```js
(function(a,b,c){ return "a = " + a + ", b = " + b + ", c = " + c; })(a,b,c);
```
## --seed-contents--
```js
var a = 3;
var b = 17;
var c = 12;
// Only change code below this line
a = a + 12;
b = 9 + b;
c = c + 7;
```
# --solutions--
```js
var a = 3;
var b = 17;
var c = 12;
a += 12;
b += 9;
c += 7;
```

View File

@ -0,0 +1,91 @@
---
id: 56533eb9ac21ba0edf2244b2
title: Compound Assignment With Augmented Division
challengeType: 1
videoUrl: 'https://scrimba.com/c/c2QvKT2'
forumTopicId: 16659
dashedName: compound-assignment-with-augmented-division
---
# --description--
The `/=` operator divides a variable by another number.
`myVar = myVar / 5;`
Will divide `myVar` by `5`. This can be rewritten as:
`myVar /= 5;`
# --instructions--
Convert the assignments for `a`, `b`, and `c` to use the `/=` operator.
# --hints--
`a` should equal `4`.
```js
assert(a === 4);
```
`b` should equal `27`.
```js
assert(b === 27);
```
`c` should equal `3`.
```js
assert(c === 3);
```
You should use the `/=` operator for each variable.
```js
assert(code.match(/\/=/g).length === 3);
```
You should not modify the code above the specified comment.
```js
assert(
/var a = 48;/.test(code) &&
/var b = 108;/.test(code) &&
/var c = 33;/.test(code)
);
```
# --seed--
## --after-user-code--
```js
(function(a,b,c){ return "a = " + a + ", b = " + b + ", c = " + c; })(a,b,c);
```
## --seed-contents--
```js
var a = 48;
var b = 108;
var c = 33;
// Only change code below this line
a = a / 12;
b = b / 4;
c = c / 11;
```
# --solutions--
```js
var a = 48;
var b = 108;
var c = 33;
a /= 12;
b /= 4;
c /= 11;
```

View File

@ -0,0 +1,91 @@
---
id: 56533eb9ac21ba0edf2244b1
title: Compound Assignment With Augmented Multiplication
challengeType: 1
videoUrl: 'https://scrimba.com/c/c83vrfa'
forumTopicId: 16662
dashedName: compound-assignment-with-augmented-multiplication
---
# --description--
The `*=` operator multiplies a variable by a number.
`myVar = myVar * 5;`
will multiply `myVar` by `5`. This can be rewritten as:
`myVar *= 5;`
# --instructions--
Convert the assignments for `a`, `b`, and `c` to use the `*=` operator.
# --hints--
`a` should equal `25`.
```js
assert(a === 25);
```
`b` should equal `36`.
```js
assert(b === 36);
```
`c` should equal `46`.
```js
assert(c === 46);
```
You should use the `*=` operator for each variable.
```js
assert(code.match(/\*=/g).length === 3);
```
You should not modify the code above the specified comment.
```js
assert(
/var a = 5;/.test(code) &&
/var b = 12;/.test(code) &&
/var c = 4\.6;/.test(code)
);
```
# --seed--
## --after-user-code--
```js
(function(a,b,c){ return "a = " + a + ", b = " + b + ", c = " + c; })(a,b,c);
```
## --seed-contents--
```js
var a = 5;
var b = 12;
var c = 4.6;
// Only change code below this line
a = a * 5;
b = 3 * b;
c = c * 10;
```
# --solutions--
```js
var a = 5;
var b = 12;
var c = 4.6;
a *= 5;
b *= 3;
c *= 10;
```

View File

@ -0,0 +1,89 @@
---
id: 56533eb9ac21ba0edf2244b0
title: Compound Assignment With Augmented Subtraction
challengeType: 1
videoUrl: 'https://scrimba.com/c/c2Qv7AV'
forumTopicId: 16660
dashedName: compound-assignment-with-augmented-subtraction
---
# --description--
Like the `+=` operator, `-=` subtracts a number from a variable.
`myVar = myVar - 5;`
will subtract `5` from `myVar`. This can be rewritten as:
`myVar -= 5;`
# --instructions--
Convert the assignments for `a`, `b`, and `c` to use the `-=` operator.
# --hints--
`a` should equal `5`.
```js
assert(a === 5);
```
`b` should equal `-6`.
```js
assert(b === -6);
```
`c` should equal `2`.
```js
assert(c === 2);
```
You should use the `-=` operator for each variable.
```js
assert(code.match(/-=/g).length === 3);
```
You should not modify the code above the specified comment.
```js
assert(
/var a = 11;/.test(code) && /var b = 9;/.test(code) && /var c = 3;/.test(code)
);
```
# --seed--
## --after-user-code--
```js
(function(a,b,c){ return "a = " + a + ", b = " + b + ", c = " + c; })(a,b,c);
```
## --seed-contents--
```js
var a = 11;
var b = 9;
var c = 3;
// Only change code below this line
a = a - 6;
b = b - 15;
c = c - 1;
```
# --solutions--
```js
var a = 11;
var b = 9;
var c = 3;
a -= 6;
b -= 15;
c -= 1;
```

View File

@ -0,0 +1,84 @@
---
id: 56533eb9ac21ba0edf2244b7
title: Concatenating Strings with Plus Operator
challengeType: 1
videoUrl: 'https://scrimba.com/c/cNpM8AN'
forumTopicId: 16802
dashedName: concatenating-strings-with-plus-operator
---
# --description--
In JavaScript, when the `+` operator is used with a `String` 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.
**Example**
```js
'My name is Alan,' + ' I concatenate.'
```
**Note**
Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.
Example:
```js
var ourStr = "I come first. " + "I come second.";
// ourStr is "I come first. I come second."
```
# --instructions--
Build `myStr` from the strings `"This is the start. "` and `"This is the end."` using the `+` operator.
# --hints--
`myStr` should have a value of `This is the start. This is the end.`
```js
assert(myStr === 'This is the start. This is the end.');
```
You should use the `+` operator to build `myStr`.
```js
assert(code.match(/(["']).*\1\s*\+\s*(["']).*\2/g));
```
`myStr` should be created using the `var` keyword.
```js
assert(/var\s+myStr/.test(code));
```
You should assign the result to the `myStr` variable.
```js
assert(/myStr\s*=/.test(code));
```
# --seed--
## --after-user-code--
```js
(function(){
if(typeof myStr === 'string') {
return 'myStr = "' + myStr + '"';
} else {
return 'myStr is not a string';
}
})();
```
## --seed-contents--
```js
var myStr; // Change this line
```
# --solutions--
```js
var myStr = "This is the start. " + "This is the end.";
```

View File

@ -0,0 +1,70 @@
---
id: 56533eb9ac21ba0edf2244b8
title: Concatenating Strings with the Plus Equals Operator
challengeType: 1
videoUrl: 'https://scrimba.com/c/cbQmmC4'
forumTopicId: 16803
dashedName: concatenating-strings-with-the-plus-equals-operator
---
# --description--
We can also use the `+=` 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.
**Note**
Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.
Example:
```js
var ourStr = "I come first. ";
ourStr += "I come second.";
// ourStr is now "I come first. I come second."
```
# --instructions--
Build `myStr` over several lines by concatenating these two strings: `"This is the first sentence. "` and `"This is the second sentence."` using the `+=` operator. Use the `+=` operator similar to how it is shown in the editor. Start by assigning the first string to `myStr`, then add on the second string.
# --hints--
`myStr` should have a value of `This is the first sentence. This is the second sentence.`
```js
assert(myStr === 'This is the first sentence. This is the second sentence.');
```
You should use the `+=` operator to build `myStr`.
```js
assert(code.match(/myStr\s*\+=\s*(["']).*\1/g));
```
# --seed--
## --after-user-code--
```js
(function(){
if(typeof myStr === 'string') {
return 'myStr = "' + myStr + '"';
} else {
return 'myStr is not a string';
}
})();
```
## --seed-contents--
```js
// Only change code below this line
var myStr;
```
# --solutions--
```js
var myStr = "This is the first sentence. ";
myStr += "This is the second sentence.";
```

View File

@ -0,0 +1,74 @@
---
id: 56533eb9ac21ba0edf2244b9
title: Constructing Strings with Variables
challengeType: 1
videoUrl: 'https://scrimba.com/c/cqk8rf4'
forumTopicId: 16805
dashedName: constructing-strings-with-variables
---
# --description--
Sometimes you will need to build a string, [Mad Libs](https://en.wikipedia.org/wiki/Mad_Libs) style. By using the concatenation operator (`+`), you can insert one or more variables into a string you're building.
Example:
```js
var ourName = "freeCodeCamp";
var ourStr = "Hello, our name is " + ourName + ", how are you?";
// ourStr is now "Hello, our name is freeCodeCamp, how are you?"
```
# --instructions--
Set `myName` to a string equal to your name and build `myStr` with `myName` between the strings `"My name is "` and `" and I am well!"`
# --hints--
`myName` should be set to a string at least 3 characters long.
```js
assert(typeof myName !== 'undefined' && myName.length > 2);
```
You should use two `+` operators to build `myStr` with `myName` inside it.
```js
assert(code.match(/["']\s*\+\s*myName\s*\+\s*["']/g).length > 0);
```
# --seed--
## --after-user-code--
```js
(function(){
var output = [];
if(typeof myName === 'string') {
output.push('myName = "' + myName + '"');
} else {
output.push('myName is not a string');
}
if(typeof myStr === 'string') {
output.push('myStr = "' + myStr + '"');
} else {
output.push('myStr is not a string');
}
return output.join('\n');
})();
```
## --seed-contents--
```js
// Only change code below this line
var myName;
var myStr;
```
# --solutions--
```js
var myName = "Bob";
var myStr = "My name is " + myName + " and I am well!";
```

View File

@ -0,0 +1,75 @@
---
id: 56105e7b514f539506016a5e
title: Count Backwards With a For Loop
challengeType: 1
videoUrl: 'https://scrimba.com/c/c2R6BHa'
forumTopicId: 16808
dashedName: count-backwards-with-a-for-loop
---
# --description--
A for loop can also count backwards, so long as we can define the right conditions.
In order to decrement by two each iteration, we'll need to change our `initialization`, `condition`, and `final-expression`.
We'll start at `i = 10` and loop while `i > 0`. We'll decrement `i` by 2 each loop with `i -= 2`.
```js
var ourArray = [];
for (var i = 10; i > 0; i -= 2) {
ourArray.push(i);
}
```
`ourArray` will now contain `[10,8,6,4,2]`. Let's change our `initialization` and `final-expression` so we can count backward by twos by odd numbers.
# --instructions--
Push the odd numbers from 9 through 1 to `myArray` using a `for` loop.
# --hints--
You should be using a `for` loop for this.
```js
assert(/for\s*\([^)]+?\)/.test(code));
```
You should be using the array method `push`.
```js
assert(code.match(/myArray.push/));
```
`myArray` should equal `[9,7,5,3,1]`.
```js
assert.deepEqual(myArray, [9, 7, 5, 3, 1]);
```
# --seed--
## --after-user-code--
```js
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
```
## --seed-contents--
```js
// Setup
var myArray = [];
// Only change code below this line
```
# --solutions--
```js
var myArray = [];
for (var i = 9; i > 0; i -= 2) {
myArray.push(i);
}
```

View File

@ -0,0 +1,203 @@
---
id: 565bbe00e9cc8ac0725390f4
title: Counting Cards
challengeType: 1
videoUrl: 'https://scrimba.com/c/c6KE7ty'
forumTopicId: 16809
dashedName: counting-cards
---
# --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 [Card Counting](https://en.wikipedia.org/wiki/Card_counting).
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 `card` parameter, which can be a number or a string, and increment or decrement the global `count` variable according to the card's value (see table). The function will then return a string with the current count and the string `Bet` if the count is positive, or `Hold` if the count is zero or negative. The current count and the player's decision (`Bet` or `Hold`) should be separated by a single space.
**Example Output**
`-3 Hold`
`5 Bet`
**Hint**
Do NOT reset `count` to 0 when value is 7, 8, or 9. Do NOT return an array.
Do NOT include quotes (single or double) in the output.
# --hints--
Cards Sequence 2, 3, 4, 5, 6 should return `5 Bet`
```js
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 7, 8, 9 should return `0 Hold`
```js
assert(
(function () {
count = 0;
cc(7);
cc(8);
var out = cc(9);
if (out === '0 Hold') {
return true;
}
return false;
})()
);
```
Cards Sequence 10, J, Q, K, A should return `-5 Hold`
```js
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 3, 7, Q, 8, A should return `-1 Hold`
```js
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 2, J, 9, 2, 7 should return `1 Bet`
```js
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, 2, 10 should return `1 Bet`
```js
assert(
(function () {
count = 0;
cc(2);
cc(2);
var out = cc(10);
if (out === '1 Bet') {
return true;
}
return false;
})()
);
```
Cards Sequence 3, 2, A, 10, K should return `-1 Hold`
```js
assert(
(function () {
count = 0;
cc(3);
cc(2);
cc('A');
cc(10);
var out = cc('K');
if (out === '-1 Hold') {
return true;
}
return false;
})()
);
```
# --seed--
## --seed-contents--
```js
var count = 0;
function cc(card) {
// Only change code below this line
return "Change Me";
// Only change code above this line
}
cc(2); cc(3); cc(7); cc('K'); cc('A');
```
# --solutions--
```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";
}
}
```

View File

@ -0,0 +1,55 @@
---
id: cf1391c1c11feddfaeb4bdef
title: Create Decimal Numbers with JavaScript
challengeType: 1
videoUrl: 'https://scrimba.com/c/ca8GEuW'
forumTopicId: 16826
dashedName: create-decimal-numbers-with-javascript
---
# --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>.
**Note**
Not all real numbers can accurately be represented in <dfn>floating point</dfn>. This can lead to rounding errors. [Details Here](https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems).
# --instructions--
Create a variable `myDecimal` and give it a decimal value with a fractional part (e.g. `5.7`).
# --hints--
`myDecimal` should be a number.
```js
assert(typeof myDecimal === 'number');
```
`myDecimal` should have a decimal point
```js
assert(myDecimal % 1 != 0);
```
# --seed--
## --after-user-code--
```js
(function(){if(typeof myDecimal !== "undefined"){return myDecimal;}})();
```
## --seed-contents--
```js
var ourDecimal = 5.7;
// Only change code below this line
```
# --solutions--
```js
var myDecimal = 9.9;
```

View File

@ -0,0 +1,59 @@
---
id: bd7123c9c443eddfaeb5bdef
title: Declare JavaScript Variables
challengeType: 1
videoUrl: 'https://scrimba.com/c/cNanrHq'
forumTopicId: 17556
dashedName: declare-javascript-variables
---
# --description--
In computer science, <dfn>data</dfn> is anything that is meaningful to the computer. JavaScript provides eight different <dfn>data types</dfn> which are `undefined`, `null`, `boolean`, `string`, `symbol`, `bigint`, `number`, and `object`.
For example, computers distinguish between numbers, such as the number `12`, and `strings`, such as `"12"`, `"dog"`, or `"123 cats"`, 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 eight data types may be stored in a variable.
`Variables` 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 `variables` 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 `var` in front of it, like so:
```js
var ourName;
```
creates a `variable` called `ourName`. In JavaScript we end statements with semicolons. `Variable` names can be made up of numbers, letters, and `$` or `_`, but may not contain spaces or start with a number.
# --instructions--
Use the `var` keyword to create a variable called `myName`.
**Hint**
Look at the `ourName` example above if you get stuck.
# --hints--
You should declare `myName` with the `var` keyword, ending with a semicolon
```js
assert(/var\s+myName\s*;/.test(code));
```
# --seed--
## --after-user-code--
```js
if(typeof myName !== "undefined"){(function(v){return v;})(myName);}
```
## --seed-contents--
```js
```
# --solutions--
```js
var myName;
```

View File

@ -0,0 +1,77 @@
---
id: bd7123c9c444eddfaeb5bdef
title: Declare String Variables
challengeType: 1
videoUrl: 'https://scrimba.com/c/c2QvWU6'
forumTopicId: 17557
dashedName: declare-string-variables
---
# --description--
Previously we have used the code
`var myName = "your name";`
`"your name"` 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.
# --instructions--
Create two new `string` variables: `myFirstName` and `myLastName` and assign them the values of your first and last name, respectively.
# --hints--
`myFirstName` should be a string with at least one character in it.
```js
assert(
(function () {
if (
typeof myFirstName !== 'undefined' &&
typeof myFirstName === 'string' &&
myFirstName.length > 0
) {
return true;
} else {
return false;
}
})()
);
```
`myLastName` should be a string with at least one character in it.
```js
assert(
(function () {
if (
typeof myLastName !== 'undefined' &&
typeof myLastName === 'string' &&
myLastName.length > 0
) {
return true;
} else {
return false;
}
})()
);
```
# --seed--
## --after-user-code--
```js
if(typeof myFirstName !== "undefined" && typeof myLastName !== "undefined"){(function(){return myFirstName + ', ' + myLastName;})();}
```
## --seed-contents--
```js
```
# --solutions--
```js
var myFirstName = "Alan";
var myLastName = "Turing";
```

View File

@ -0,0 +1,77 @@
---
id: 56533eb9ac21ba0edf2244ad
title: Decrement a Number with JavaScript
challengeType: 1
videoUrl: 'https://scrimba.com/c/cM2KeS2'
forumTopicId: 17558
dashedName: decrement-a-number-with-javascript
---
# --description--
You can easily <dfn>decrement</dfn> or decrease a variable by one with the `--` operator.
`i--;`
is the equivalent of
`i = i - 1;`
**Note**
The entire line becomes `i--;`, eliminating the need for the equal sign.
# --instructions--
Change the code to use the `--` operator on `myVar`.
# --hints--
`myVar` should equal `10`.
```js
assert(myVar === 10);
```
`myVar = myVar - 1;` should be changed.
```js
assert(
/var\s*myVar\s*=\s*11;\s*\/*.*\s*([-]{2}\s*myVar|myVar\s*[-]{2});/.test(code)
);
```
You should use the `--` operator on `myVar`.
```js
assert(/[-]{2}\s*myVar|myVar\s*[-]{2}/.test(code));
```
You should not change code above the specified comment.
```js
assert(/var myVar = 11;/.test(code));
```
# --seed--
## --after-user-code--
```js
(function(z){return 'myVar = ' + z;})(myVar);
```
## --seed-contents--
```js
var myVar = 11;
// Only change code below this line
myVar = myVar - 1;
```
# --solutions--
```js
var myVar = 11;
myVar--;
```

View File

@ -0,0 +1,93 @@
---
id: 56bbb991ad1ed5201cd392d3
title: Delete Properties from a JavaScript Object
challengeType: 1
videoUrl: 'https://scrimba.com/c/cDqKdTv'
forumTopicId: 17560
dashedName: delete-properties-from-a-javascript-object
---
# --description--
We can also delete properties from objects like this:
`delete ourDog.bark;`
Example:
```js
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"],
"bark": "bow-wow"
};
delete ourDog.bark;
```
After the last line shown above, `ourDog` looks like:
```js
{
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"]
}
```
# --instructions--
Delete the `"tails"` property from `myDog`. You may use either dot or bracket notation.
# --hints--
You should delete the property `"tails"` from `myDog`.
```js
assert(typeof myDog === 'object' && myDog.tails === undefined);
```
You should not modify the `myDog` setup.
```js
assert(code.match(/"tails": 1/g).length > 0);
```
# --seed--
## --after-user-code--
```js
(function(z){return z;})(myDog);
```
## --seed-contents--
```js
// Setup
var myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"],
"bark": "woof"
};
// Only change code below this line
```
# --solutions--
```js
var myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"],
"bark": "woof"
};
delete myDog.tails;
```

View File

@ -0,0 +1,56 @@
---
id: bd7993c9ca9feddfaeb7bdef
title: Divide One Decimal by Another with JavaScript
challengeType: 1
videoUrl: 'https://scrimba.com/c/cBZe9AW'
forumTopicId: 18255
dashedName: divide-one-decimal-by-another-with-javascript
---
# --description--
Now let's divide one decimal by another.
# --instructions--
Change the `0.0` so that `quotient` will equal to `2.2`.
# --hints--
The variable `quotient` should equal `2.2`
```js
assert(quotient === 2.2);
```
You should use the `/` operator to divide 4.4 by 2
```js
assert(/4\.40*\s*\/\s*2\.*0*/.test(code));
```
The quotient variable should only be assigned once
```js
assert(code.match(/quotient/g).length === 1);
```
# --seed--
## --after-user-code--
```js
(function(y){return 'quotient = '+y;})(quotient);
```
## --seed-contents--
```js
var quotient = 0.0 / 2.0; // Change this line
```
# --solutions--
```js
var quotient = 4.4 / 2.0;
```

View File

@ -0,0 +1,58 @@
---
id: cf1111c1c11feddfaeb6bdef
title: Divide One Number by Another with JavaScript
challengeType: 1
videoUrl: 'https://scrimba.com/c/cqkbdAr'
forumTopicId: 17566
dashedName: divide-one-number-by-another-with-javascript
---
# --description--
We can also divide one number by another.
JavaScript uses the `/` symbol for division.
**Example**
```js
myVar = 16 / 2; // assigned 8
```
# --instructions--
Change the `0` so that the `quotient` is equal to `2`.
# --hints--
The variable `quotient` should be equal to 2.
```js
assert(quotient === 2);
```
You should use the `/` operator.
```js
assert(/\d+\s*\/\s*\d+/.test(code));
```
# --seed--
## --after-user-code--
```js
(function(z){return 'quotient = '+z;})(quotient);
```
## --seed-contents--
```js
var quotient = 66 / 0;
```
# --solutions--
```js
var quotient = 66 / 33;
```

View File

@ -0,0 +1,99 @@
---
id: 56533eb9ac21ba0edf2244b6
title: Escape Sequences in Strings
challengeType: 1
videoUrl: 'https://scrimba.com/c/cvmqRh6'
forumTopicId: 17567
dashedName: escape-sequences-in-strings
---
# --description--
Quotes are not the only characters that can be <dfn>escaped</dfn> inside a string. There are two reasons to use escaping characters:
1. To allow you to use characters you may not otherwise be able to type out, such as a carriage return.
2. 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>word boundary</td></tr><tr><td><code>\f</code></td><td>form feed</td></tr></tbody></table>
*Note that the backslash itself must be escaped in order to display as a backslash.*
# --instructions--
Assign the following three lines of text into the single variable `myStr` using escape sequences.
<blockquote>FirstLine<br>    \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.
**Note:** The indentation for `SecondLine` is achieved with the tab escape character, not spaces.
# --hints--
`myStr` should not contain any spaces
```js
assert(!/ /.test(myStr));
```
`myStr` should contain the strings `FirstLine`, `SecondLine` and `ThirdLine` (remember case sensitivity)
```js
assert(
/FirstLine/.test(myStr) && /SecondLine/.test(myStr) && /ThirdLine/.test(myStr)
);
```
`FirstLine` should be followed by the newline character `\n`
```js
assert(/FirstLine\n/.test(myStr));
```
`myStr` should contain a tab character `\t` which follows a newline character
```js
assert(/\n\t/.test(myStr));
```
`SecondLine` should be preceded by the backslash character <code>\\</code>
```js
assert(/\\SecondLine/.test(myStr));
```
There should be a newline character between `SecondLine` and `ThirdLine`
```js
assert(/SecondLine\nThirdLine/.test(myStr));
```
`myStr` should only contain characters shown in the instructions
```js
assert(myStr === 'FirstLine\n\t\\SecondLine\nThirdLine');
```
# --seed--
## --after-user-code--
```js
(function(){
if (myStr !== undefined){
console.log('myStr:\n' + myStr);}})();
```
## --seed-contents--
```js
var myStr; // Change this line
```
# --solutions--
```js
var myStr = "FirstLine\n\t\\SecondLine\nThirdLine";
```

View File

@ -0,0 +1,66 @@
---
id: 56533eb9ac21ba0edf2244b5
title: Escaping Literal Quotes in Strings
challengeType: 1
videoUrl: 'https://scrimba.com/c/c2QvgSr'
forumTopicId: 17568
dashedName: escaping-literal-quotes-in-strings
---
# --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: `"` or `'` 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.
`var sampleStr = "Alan said, \"Peter is learning JavaScript\".";`
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:
`Alan said, "Peter is learning JavaScript".`
# --instructions--
Use <dfn>backslashes</dfn> to assign a string to the `myStr` variable so that if you were to print it to the console, you would see:
`I am a "double quoted" string inside "double quotes".`
# --hints--
You should use two double quotes (`"`) and four escaped double quotes (`\"`).
```js
assert(code.match(/\\"/g).length === 4 && code.match(/[^\\]"/g).length === 2);
```
Variable myStr should contain the string: `I am a "double quoted" string inside "double quotes".`
```js
assert(/I am a "double quoted" string inside "double quotes(\."|"\.)$/.test(myStr));
```
# --seed--
## --after-user-code--
```js
(function(){
if(typeof myStr === 'string') {
console.log("myStr = \"" + myStr + "\"");
} else {
console.log("myStr is undefined");
}
})();
```
## --seed-contents--
```js
var myStr = ""; // Change this line
```
# --solutions--
```js
var myStr = "I am a \"double quoted\" string inside \"double quotes\".";
```

View File

@ -0,0 +1,65 @@
---
id: bd7123c9c448eddfaeb5bdef
title: Find the Length of a String
challengeType: 1
videoUrl: 'https://scrimba.com/c/cvmqEAd'
forumTopicId: 18182
dashedName: find-the-length-of-a-string
---
# --description--
You can find the length of a `String` value by writing `.length` after the string variable or string literal.
`"Alan Peter".length; // 10`
For example, if we created a variable `var firstName = "Charles"`, we could find out how long the string `"Charles"` is by using the `firstName.length` property.
# --instructions--
Use the `.length` property to count the number of characters in the `lastName` variable and assign it to `lastNameLength`.
# --hints--
You should not change the variable declarations in the `// Setup` section.
```js
assert(
code.match(/var lastNameLength = 0;/) &&
code.match(/var lastName = "Lovelace";/)
);
```
`lastNameLength` should be equal to eight.
```js
assert(typeof lastNameLength !== 'undefined' && lastNameLength === 8);
```
You should be getting the length of `lastName` by using `.length` like this: `lastName.length`.
```js
assert(code.match(/=\s*lastName\.length/g) && !code.match(/lastName\s*=\s*8/));
```
# --seed--
## --seed-contents--
```js
// Setup
var lastNameLength = 0;
var lastName = "Lovelace";
// Only change code below this line
lastNameLength = lastName;
```
# --solutions--
```js
var lastNameLength = 0;
var lastName = "Lovelace";
lastNameLength = lastName.length;
```

View File

@ -0,0 +1,70 @@
---
id: 56533eb9ac21ba0edf2244ae
title: Finding a Remainder in JavaScript
challengeType: 1
videoUrl: 'https://scrimba.com/c/cWP24Ub'
forumTopicId: 18184
dashedName: finding-a-remainder-in-javascript
---
# --description--
The <dfn>remainder</dfn> operator `%` gives the remainder of the division of two numbers.
**Example**
<blockquote>5 % 2 = 1 because<br>Math.floor(5 / 2) = 2 (Quotient)<br>2 * 2 = 4<br>5 - 4 = 1 (Remainder)</blockquote>
**Usage**
In mathematics, a number can be checked to be even or odd by checking the remainder of the division of the number by `2`.
<blockquote>17 % 2 = 1 (17 is Odd)<br>48 % 2 = 0 (48 is Even)</blockquote>
**Note**
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.
# --instructions--
Set `remainder` equal to the remainder of `11` divided by `3` using the <dfn>remainder</dfn> (`%`) operator.
# --hints--
The variable `remainder` should be initialized
```js
assert(/var\s+?remainder/.test(code));
```
The value of `remainder` should be `2`
```js
assert(remainder === 2);
```
You should use the `%` operator
```js
assert(/\s+?remainder\s*?=\s*?.*%.*;?/.test(code));
```
# --seed--
## --after-user-code--
```js
(function(y){return 'remainder = '+y;})(remainder);
```
## --seed-contents--
```js
// Only change code below this line
var remainder;
```
# --solutions--
```js
var remainder = 11 % 3;
```

View File

@ -0,0 +1,70 @@
---
id: cf1111c1c11feddfaeb9bdef
title: Generate Random Fractions with JavaScript
challengeType: 1
videoUrl: 'https://scrimba.com/c/cyWJJs3'
forumTopicId: 18185
dashedName: generate-random-fractions-with-javascript
---
# --description--
Random numbers are useful for creating random behavior.
JavaScript has a `Math.random()` function that generates a random decimal number between `0` (inclusive) and not quite up to `1` (exclusive). Thus `Math.random()` can return a `0` but never quite return a `1`
**Note**
Like [Storing Values with the Equal Operator](/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator), all function calls will be resolved before the `return` executes, so we can `return` the value of the `Math.random()` function.
# --instructions--
Change `randomFraction` to return a random number instead of returning `0`.
# --hints--
`randomFraction` should return a random number.
```js
assert(typeof randomFraction() === 'number');
```
The number returned by `randomFraction` should be a decimal.
```js
assert((randomFraction() + '').match(/\./g));
```
You should be using `Math.random` to generate the random decimal number.
```js
assert(code.match(/Math\.random/g).length >= 0);
```
# --seed--
## --after-user-code--
```js
(function(){return randomFraction();})();
```
## --seed-contents--
```js
function randomFraction() {
// Only change code below this line
return 0;
// Only change code above this line
}
```
# --solutions--
```js
function randomFraction() {
return Math.random();
}
```

View File

@ -0,0 +1,88 @@
---
id: cf1111c1c12feddfaeb1bdef
title: Generate Random Whole Numbers with JavaScript
challengeType: 1
videoUrl: 'https://scrimba.com/c/cRn6bfr'
forumTopicId: 18186
dashedName: generate-random-whole-numbers-with-javascript
---
# --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 `Math.random()` can never quite return a `1` and, because we're rounding down, it's impossible to actually get `20`. This technique will give us a whole number between `0` and `19`.
Putting everything together, this is what our code looks like:
`Math.floor(Math.random() * 20);`
We are calling `Math.random()`, multiplying the result by 20, then passing the value to `Math.floor()` function to round the value down to the nearest whole number.
# --instructions--
Use this technique to generate and return a random whole number between `0` and `9`.
# --hints--
The result of `randomWholeNum` should be a whole number.
```js
assert(
typeof randomWholeNum() === 'number' &&
(function () {
var r = randomWholeNum();
return Math.floor(r) === r;
})()
);
```
You should use `Math.random` to generate a random number.
```js
assert(code.match(/Math.random/g).length >= 1);
```
You should have multiplied the result of `Math.random` by 10 to make it a number that is between zero and nine.
```js
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 use `Math.floor` to remove the decimal part of the number.
```js
assert(code.match(/Math.floor/g).length >= 1);
```
# --seed--
## --after-user-code--
```js
(function(){return randomWholeNum();})();
```
## --seed-contents--
```js
function randomWholeNum() {
// Only change code below this line
return Math.random();
}
```
# --solutions--
```js
function randomWholeNum() {
return Math.floor(Math.random() * 10);
}
```

View File

@ -0,0 +1,100 @@
---
id: cf1111c1c12feddfaeb2bdef
title: Generate Random Whole Numbers within a Range
challengeType: 1
videoUrl: 'https://scrimba.com/c/cm83yu6'
forumTopicId: 18187
dashedName: generate-random-whole-numbers-within-a-range
---
# --description--
Instead of generating a random whole number between zero and a given number like we did before, we can generate a random whole number that falls within a range of two specific numbers.
To do this, we'll define a minimum number `min` and a maximum number `max`.
Here's the formula we'll use. Take a moment to read it and try to understand what this code is doing:
`Math.floor(Math.random() * (max - min + 1)) + min`
# --instructions--
Create a function called `randomRange` that takes a range `myMin` and `myMax` and returns a random whole number that's greater than or equal to `myMin`, and is less than or equal to `myMax`, inclusive.
# --hints--
The lowest random number that can be generated by `randomRange` should be equal to your minimum number, `myMin`.
```js
assert(calcMin === 5);
```
The highest random number that can be generated by `randomRange` should be equal to your maximum number, `myMax`.
```js
assert(calcMax === 15);
```
The random number generated by `randomRange` should be an integer, not a decimal.
```js
assert(randomRange(0, 1) % 1 === 0);
```
`randomRange` should use both `myMax` and `myMin`, and return a random number in your range.
```js
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;
}
})()
);
```
# --seed--
## --after-user-code--
```js
var calcMin = 100;
var calcMax = -100;
for(var i = 0; i < 100; i++) {
var result = randomRange(5,15);
calcMin = Math.min(calcMin, result);
calcMax = Math.max(calcMax, result);
}
(function(){
if(typeof myRandom === 'number') {
return "myRandom = " + myRandom;
} else {
return "myRandom undefined";
}
})()
```
## --seed-contents--
```js
function randomRange(myMin, myMax) {
// Only change code below this line
return 0;
// Only change code above this line
}
```
# --solutions--
```js
function randomRange(myMin, myMax) {
return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
}
```

View File

@ -0,0 +1,128 @@
---
id: 56533eb9ac21ba0edf2244be
title: Global Scope and Functions
challengeType: 1
videoUrl: 'https://scrimba.com/c/cQM7mCN'
forumTopicId: 18193
dashedName: global-scope-and-functions
---
# --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 `var` keyword are automatically created in the `global` scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with `var`.
# --instructions--
Using `var`, declare a global variable named `myGlobal` outside of any function. Initialize it with a value of `10`.
Inside function `fun1`, assign `5` to `oopsGlobal` ***without*** using the `var` keyword.
# --hints--
`myGlobal` should be defined
```js
assert(typeof myGlobal != 'undefined');
```
`myGlobal` should have a value of `10`
```js
assert(myGlobal === 10);
```
`myGlobal` should be declared using the `var` keyword
```js
assert(/var\s+myGlobal/.test(code));
```
`oopsGlobal` should be a global variable and have a value of `5`
```js
assert(typeof oopsGlobal != 'undefined' && oopsGlobal === 5);
```
# --seed--
## --before-user-code--
```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();
```
## --after-user-code--
```js
fun1();
fun2();
uncapture();
(function() { return logOutput || "console.log never called"; })();
```
## --seed-contents--
```js
// Declare the myGlobal variable below this line
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);
}
```
# --solutions--
```js
var myGlobal = 10;
function fun1() {
oopsGlobal = 5;
}
function fun2() {
var output = "";
if(typeof myGlobal != "undefined") {
output += "myGlobal: " + myGlobal;
}
if(typeof oopsGlobal != "undefined") {
output += " oopsGlobal: " + oopsGlobal;
}
console.log(output);
}
```

View File

@ -0,0 +1,78 @@
---
id: 56533eb9ac21ba0edf2244c0
title: Global vs. Local Scope in Functions
challengeType: 1
videoUrl: 'https://scrimba.com/c/c2QwKH2'
forumTopicId: 18194
dashedName: global-vs--local-scope-in-functions
---
# --description--
It is possible to have both <dfn>local</dfn> and <dfn>global</dfn> variables with the same name. When you do this, the `local` variable takes precedence over the `global` variable.
In this example:
```js
var someVar = "Hat";
function myFun() {
var someVar = "Head";
return someVar;
}
```
The function `myFun` will return `"Head"` because the `local` version of the variable is present.
# --instructions--
Add a local variable to `myOutfit` function to override the value of `outerWear` with `"sweater"`.
# --hints--
You should not change the value of the global `outerWear`.
```js
assert(outerWear === 'T-Shirt');
```
`myOutfit` should return `"sweater"`.
```js
assert(myOutfit() === 'sweater');
```
You should not change the return statement.
```js
assert(/return outerWear/.test(code));
```
# --seed--
## --seed-contents--
```js
// Setup
var outerWear = "T-Shirt";
function myOutfit() {
// Only change code below this line
// Only change code above this line
return outerWear;
}
myOutfit();
```
# --solutions--
```js
var outerWear = "T-Shirt";
function myOutfit() {
var outerWear = "sweater";
return outerWear;
}
```

View File

@ -0,0 +1,135 @@
---
id: 5664820f61c48e80c9fa476c
title: Golf Code
challengeType: 1
videoUrl: 'https://scrimba.com/c/c9ykNUR'
forumTopicId: 18195
dashedName: golf-code
---
# --description--
In the game of [golf](https://en.wikipedia.org/wiki/Golf) each hole has a `par` meaning the average number of `strokes` 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 `par` your `strokes` are, there is a different nickname.
Your function will be passed `par` and `strokes` 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>&#x3C;= 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>>= par + 3</td><td>"Go Home!"</td></tr></tbody></table>
`par` and `strokes` will always be numeric and positive. We have added an array of all the names for your convenience.
# --hints--
`golfScore(4, 1)` should return "Hole-in-one!"
```js
assert(golfScore(4, 1) === 'Hole-in-one!');
```
`golfScore(4, 2)` should return "Eagle"
```js
assert(golfScore(4, 2) === 'Eagle');
```
`golfScore(5, 2)` should return "Eagle"
```js
assert(golfScore(5, 2) === 'Eagle');
```
`golfScore(4, 3)` should return "Birdie"
```js
assert(golfScore(4, 3) === 'Birdie');
```
`golfScore(4, 4)` should return "Par"
```js
assert(golfScore(4, 4) === 'Par');
```
`golfScore(1, 1)` should return "Hole-in-one!"
```js
assert(golfScore(1, 1) === 'Hole-in-one!');
```
`golfScore(5, 5)` should return "Par"
```js
assert(golfScore(5, 5) === 'Par');
```
`golfScore(4, 5)` should return "Bogey"
```js
assert(golfScore(4, 5) === 'Bogey');
```
`golfScore(4, 6)` should return "Double Bogey"
```js
assert(golfScore(4, 6) === 'Double Bogey');
```
`golfScore(4, 7)` should return "Go Home!"
```js
assert(golfScore(4, 7) === 'Go Home!');
```
`golfScore(5, 9)` should return "Go Home!"
```js
assert(golfScore(5, 9) === 'Go Home!');
```
# --seed--
## --seed-contents--
```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
}
golfScore(5, 4);
```
# --solutions--
```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!";
}
```

View File

@ -0,0 +1,77 @@
---
id: 56533eb9ac21ba0edf2244ac
title: Increment a Number with JavaScript
challengeType: 1
videoUrl: 'https://scrimba.com/c/ca8GLT9'
forumTopicId: 18201
dashedName: increment-a-number-with-javascript
---
# --description--
You can easily <dfn>increment</dfn> or add one to a variable with the `++` operator.
`i++;`
is the equivalent of
`i = i + 1;`
**Note**
The entire line becomes `i++;`, eliminating the need for the equal sign.
# --instructions--
Change the code to use the `++` operator on `myVar`.
# --hints--
`myVar` should equal `88`.
```js
assert(myVar === 88);
```
You should not use the assignment operator.
```js
assert(
/var\s*myVar\s*=\s*87;\s*\/*.*\s*([+]{2}\s*myVar|myVar\s*[+]{2});/.test(code)
);
```
You should use the `++` operator.
```js
assert(/[+]{2}\s*myVar|myVar\s*[+]{2}/.test(code));
```
You should not change code above the specified comment.
```js
assert(/var myVar = 87;/.test(code));
```
# --seed--
## --after-user-code--
```js
(function(z){return 'myVar = ' + z;})(myVar);
```
## --seed-contents--
```js
var myVar = 87;
// Only change code below this line
myVar = myVar + 1;
```
# --solutions--
```js
var myVar = 87;
myVar++;
```

View File

@ -0,0 +1,46 @@
---
id: 56533eb9ac21ba0edf2244a9
title: Initializing Variables with the Assignment Operator
challengeType: 1
videoUrl: 'https://scrimba.com/c/cWJ4Bfb'
forumTopicId: 301171
dashedName: initializing-variables-with-the-assignment-operator
---
# --description--
It is common to <dfn>initialize</dfn> a variable to an initial value in the same line as it is declared.
`var myVar = 0;`
Creates a new variable called `myVar` and assigns it an initial value of `0`.
# --instructions--
Define a variable `a` with `var` and initialize it to a value of `9`.
# --hints--
You should initialize `a` to a value of `9`.
```js
assert(/var\s+a\s*=\s*9(\s*;?\s*)$/.test(code));
```
# --seed--
## --after-user-code--
```js
if(typeof a !== 'undefined') {(function(a){return "a = " + a;})(a);} else { (function() {return 'a is undefined';})(); }
```
## --seed-contents--
```js
```
# --solutions--
```js
var a = 9;
```

View File

@ -0,0 +1,114 @@
---
id: 56533eb9ac21ba0edf2244db
title: Introducing Else If Statements
challengeType: 1
videoUrl: 'https://scrimba.com/c/caeJ2hm'
forumTopicId: 18206
dashedName: introducing-else-if-statements
---
# --description--
If you have multiple conditions that need to be addressed, you can chain `if` statements together with `else if` statements.
```js
if (num > 15) {
return "Bigger than 15";
} else if (num < 5) {
return "Smaller than 5";
} else {
return "Between 5 and 15";
}
```
# --instructions--
Convert the logic to use `else if` statements.
# --hints--
You should have at least two `else` statements
```js
assert(code.match(/else/g).length > 1);
```
You should have at least two `if` statements
```js
assert(code.match(/if/g).length > 1);
```
You should have closing and opening curly braces for each `if else` code block.
```js
assert(
code.match(
/if\s*\((.+)\)\s*\{[\s\S]+\}\s*else\s+if\s*\((.+)\)\s*\{[\s\S]+\}\s*else\s*\{[\s\S]+\s*\}/
)
);
```
`testElseIf(0)` should return "Smaller than 5"
```js
assert(testElseIf(0) === 'Smaller than 5');
```
`testElseIf(5)` should return "Between 5 and 10"
```js
assert(testElseIf(5) === 'Between 5 and 10');
```
`testElseIf(7)` should return "Between 5 and 10"
```js
assert(testElseIf(7) === 'Between 5 and 10');
```
`testElseIf(10)` should return "Between 5 and 10"
```js
assert(testElseIf(10) === 'Between 5 and 10');
```
`testElseIf(12)` should return "Greater than 10"
```js
assert(testElseIf(12) === 'Greater than 10');
```
# --seed--
## --seed-contents--
```js
function testElseIf(val) {
if (val > 10) {
return "Greater than 10";
}
if (val < 5) {
return "Smaller than 5";
}
return "Between 5 and 10";
}
testElseIf(7);
```
# --solutions--
```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";
}
}
```

View File

@ -0,0 +1,106 @@
---
id: 56533eb9ac21ba0edf2244da
title: Introducing Else Statements
challengeType: 1
videoUrl: 'https://scrimba.com/c/cek4Efq'
forumTopicId: 18207
dashedName: introducing-else-statements
---
# --description--
When a condition for an `if` statement is true, the block of code following it is executed. What about when that condition is false? Normally nothing would happen. With an `else` statement, an alternate block of code can be executed.
```js
if (num > 10) {
return "Bigger than 10";
} else {
return "10 or Less";
}
```
# --instructions--
Combine the `if` statements into a single `if/else` statement.
# --hints--
You should only have one `if` statement in the editor
```js
assert(code.match(/if/g).length === 1);
```
You should use an `else` statement
```js
assert(/else/g.test(code));
```
`testElse(4)` should return "5 or Smaller"
```js
assert(testElse(4) === '5 or Smaller');
```
`testElse(5)` should return "5 or Smaller"
```js
assert(testElse(5) === '5 or Smaller');
```
`testElse(6)` should return "Bigger than 5"
```js
assert(testElse(6) === 'Bigger than 5');
```
`testElse(10)` should return "Bigger than 5".
```js
assert(testElse(10) === 'Bigger than 5');
```
You should not change the code above or below the specified comments.
```js
assert(/var result = "";/.test(code) && /return result;/.test(code));
```
# --seed--
## --seed-contents--
```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;
}
testElse(4);
```
# --solutions--
```js
function testElse(val) {
var result = "";
if(val > 5) {
result = "Bigger than 5";
} else {
result = "5 or Smaller";
}
return result;
}
```

View File

@ -0,0 +1,67 @@
---
id: 56104e9e514f539506016a5c
title: Iterate Odd Numbers With a For Loop
challengeType: 1
videoUrl: 'https://scrimba.com/c/cm8n7T9'
forumTopicId: 18212
dashedName: iterate-odd-numbers-with-a-for-loop
---
# --description--
For loops don't have to iterate one at a time. By changing our `final-expression`, we can count by even numbers.
We'll start at `i = 0` and loop while `i < 10`. We'll increment `i` by 2 each loop with `i += 2`.
```js
var ourArray = [];
for (var i = 0; i < 10; i += 2) {
ourArray.push(i);
}
```
`ourArray` will now contain `[0,2,4,6,8]`. Let's change our `initialization` so we can count by odd numbers.
# --instructions--
Push the odd numbers from 1 through 9 to `myArray` using a `for` loop.
# --hints--
You should be using a `for` loop for this.
```js
assert(/for\s*\([^)]+?\)/.test(code));
```
`myArray` should equal `[1,3,5,7,9]`.
```js
assert.deepEqual(myArray, [1, 3, 5, 7, 9]);
```
# --seed--
## --after-user-code--
```js
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
```
## --seed-contents--
```js
// Setup
var myArray = [];
// Only change code below this line
```
# --solutions--
```js
var myArray = [];
for (var i = 1; i < 10; i += 2) {
myArray.push(i);
}
```

View File

@ -0,0 +1,79 @@
---
id: 5675e877dbd60be8ad28edc6
title: Iterate Through an Array with a For Loop
challengeType: 1
videoUrl: 'https://scrimba.com/c/caeR3HB'
forumTopicId: 18216
dashedName: iterate-through-an-array-with-a-for-loop
---
# --description--
A common task in JavaScript is to iterate through the contents of an array. One way to do that is with a `for` loop. This code will output each element of the array `arr` to the console:
```js
var arr = [10, 9, 8, 7, 6];
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
```
Remember that arrays have zero-based indexing, which means the last index of the array is `length - 1`. Our condition for this loop is `i < arr.length`, which stops the loop when `i` is equal to `length`. In this case the last iteration is `i === 4` i.e. when `i` becomes equal to `arr.length` and outputs `6` to the console.
# --instructions--
Declare and initialize a variable `total` to `0`. Use a `for` loop to add the value of each element of the `myArr` array to `total`.
# --hints--
`total` should be declared and initialized to 0.
```js
assert(code.match(/(var|let|const)\s*?total\s*=\s*0.*?;?/));
```
`total` should equal 20.
```js
assert(total === 20);
```
You should use a `for` loop to iterate through `myArr`.
```js
assert(/for\s*\(/g.test(code) && /myArr\s*\[/g.test(code));
```
You should not attempt to directly assign the value 20 to `total`.
```js
assert(!__helpers.removeWhiteSpace(code).match(/total[=+-]0*[1-9]+/gm));
```
# --seed--
## --after-user-code--
```js
(function(){if(typeof total !== 'undefined') { return "total = " + total; } else { return "total is undefined";}})()
```
## --seed-contents--
```js
// Setup
var myArr = [ 2, 3, 4, 5, 6];
// Only change code below this line
```
# --solutions--
```js
var myArr = [ 2, 3, 4, 5, 6];
var total = 0;
for (var i = 0; i < myArr.length; i++) {
total += myArr[i];
}
```

View File

@ -0,0 +1,102 @@
---
id: 5a2efd662fb457916e1fe604
title: Iterate with JavaScript Do...While Loops
challengeType: 1
videoUrl: 'https://scrimba.com/c/cDqWGcp'
forumTopicId: 301172
dashedName: iterate-with-javascript-do---while-loops
---
# --description--
The next type of loop you will learn is called a `do...while` loop. It is called a `do...while` loop because it will first `do` one pass of the code inside the loop no matter what, and then continue to run the loop `while` the specified condition evaluates to `true`.
```js
var ourArray = [];
var i = 0;
do {
ourArray.push(i);
i++;
} while (i < 5);
```
The example above behaves similar to other types of loops, and the resulting array will look like `[0, 1, 2, 3, 4]`. However, what makes the `do...while` 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 `i < 5`:
```js
var ourArray = [];
var i = 5;
while (i < 5) {
ourArray.push(i);
i++;
}
```
In this example, we initialize the value of `ourArray` to an empty array and the value of `i` to 5. When we execute the `while` loop, the condition evaluates to `false` because `i` is not less than 5, so we do not execute the code inside the loop. The result is that `ourArray` will end up with no values added to it, and it will still look like `[]` when all of the code in the example above has completed running. Now, take a look at a `do...while` loop:
```js
var ourArray = [];
var i = 5;
do {
ourArray.push(i);
i++;
} while (i < 5);
```
In this case, we initialize the value of `i` to 5, just like we did with the `while` loop. When we get to the next line, there is no condition to evaluate, so we go to the code inside the curly braces and execute it. We will add a single element to the array and then increment `i` before we get to the condition check. When we finally evaluate the condition `i < 5` on the last line, we see that `i` 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 `ourArray` is `[5]`. Essentially, a `do...while` loop ensures that the code inside the loop will run at least once. Let's try getting a `do...while` loop to work by pushing values to an array.
# --instructions--
Change the `while` loop in the code to a `do...while` loop so the loop will push only the number `10` to `myArray`, and `i` will be equal to `11` when your code has finished running.
# --hints--
You should be using a `do...while` loop for this exercise.
```js
assert(code.match(/do/g));
```
`myArray` should equal `[10]`.
```js
assert.deepEqual(myArray, [10]);
```
`i` should equal `11`
```js
assert.equal(i, 11);
```
# --seed--
## --after-user-code--
```js
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
```
## --seed-contents--
```js
// Setup
var myArray = [];
var i = 10;
// Only change code below this line
while (i < 5) {
myArray.push(i);
i++;
}
```
# --solutions--
```js
var myArray = [];
var i = 10;
do {
myArray.push(i);
i++;
} while (i < 5)
```

View File

@ -0,0 +1,79 @@
---
id: cf1111c1c11feddfaeb5bdef
title: Iterate with JavaScript For Loops
challengeType: 1
videoUrl: 'https://scrimba.com/c/c9yNVCe'
forumTopicId: 18219
dashedName: iterate-with-javascript-for-loops
---
# --description--
You can run the same code multiple times by using a loop.
The most common type of JavaScript loop is called a `for` loop because it runs "for" a specific number of times.
For loops are declared with three optional expressions separated by semicolons:
`for ([initialization]; [condition]; [final-expression])`
The `initialization` statement is executed one time only before the loop starts. It is typically used to define and setup your loop variable.
The `condition` statement is evaluated at the beginning of every loop iteration and will continue as long as it evaluates to `true`. When `condition` is `false` at the start of the iteration, the loop will stop executing. This means if `condition` starts as `false`, your loop will never execute.
The `final-expression` is executed at the end of each loop iteration, prior to the next `condition` check and is usually used to increment or decrement your loop counter.
In the following example we initialize with `i = 0` and iterate while our condition `i < 5` is true. We'll increment `i` by `1` in each loop iteration with `i++` as our `final-expression`.
```js
var ourArray = [];
for (var i = 0; i < 5; i++) {
ourArray.push(i);
}
```
`ourArray` will now contain `[0,1,2,3,4]`.
# --instructions--
Use a `for` loop to work to push the values 1 through 5 onto `myArray`.
# --hints--
You should be using a `for` loop for this.
```js
assert(/for\s*\([^)]+?\)/.test(code));
```
`myArray` should equal `[1,2,3,4,5]`.
```js
assert.deepEqual(myArray, [1, 2, 3, 4, 5]);
```
# --seed--
## --after-user-code--
```js
if (typeof myArray !== "undefined"){(function(){return myArray;})();}
```
## --seed-contents--
```js
// Setup
var myArray = [];
// Only change code below this line
```
# --solutions--
```js
var myArray = [];
for (var i = 1; i < 6; i++) {
myArray.push(i);
}
```

View File

@ -0,0 +1,73 @@
---
id: cf1111c1c11feddfaeb1bdef
title: Iterate with JavaScript While Loops
challengeType: 1
videoUrl: 'https://scrimba.com/c/c8QbnCM'
forumTopicId: 18220
dashedName: iterate-with-javascript-while-loops
---
# --description--
You can run the same code multiple times by using a loop.
The first type of loop we will learn is called a `while` loop because it runs "while" a specified condition is true and stops once that condition is no longer true.
```js
var ourArray = [];
var i = 0;
while(i < 5) {
ourArray.push(i);
i++;
}
```
In the code example above, the `while` loop will execute 5 times and append the numbers 0 through 4 to `ourArray`.
Let's try getting a while loop to work by pushing values to an array.
# --instructions--
Add the numbers 5 through 0 (inclusive) in descending order to `myArray` using a `while` loop.
# --hints--
You should be using a `while` loop for this.
```js
assert(code.match(/while/g));
```
`myArray` should equal `[5,4,3,2,1,0]`.
```js
assert.deepEqual(myArray, [5, 4, 3, 2, 1, 0]);
```
# --seed--
## --after-user-code--
```js
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
```
## --seed-contents--
```js
// Setup
var myArray = [];
// Only change code below this line
```
# --solutions--
```js
var myArray = [];
var i = 5;
while(i >= 0) {
myArray.push(i);
i--;
}
```

View File

@ -0,0 +1,86 @@
---
id: 56533eb9ac21ba0edf2244bf
title: Local Scope and Functions
challengeType: 1
videoUrl: 'https://scrimba.com/c/cd62NhM'
forumTopicId: 18227
dashedName: local-scope-and-functions
---
# --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 `myTest` with a local variable called `loc`.
```js
function myTest() {
var loc = "foo";
console.log(loc);
}
myTest(); // logs "foo"
console.log(loc); // loc is not defined
```
`loc` is not defined outside of the function.
# --instructions--
The editor has two `console.log`s to help you see what is happening. Check the console as you code to see how it changes. Declare a local variable `myVar` inside `myLocalScope` and run the tests.
**Note:** The console will still have 'ReferenceError: myVar is not defined', but this will not cause the tests to fail.
# --hints--
The code should not contain a global `myVar` variable.
```js
function declared() {
myVar;
}
assert.throws(declared, ReferenceError);
```
You should add a local `myVar` variable.
```js
assert(
/functionmyLocalScope\(\)\{.+(var|let|const)myVar[\s\S]*}/.test(
__helpers.removeWhiteSpace(code)
)
);
```
# --seed--
## --seed-contents--
```js
function myLocalScope() {
// Only change code below this line
console.log('inside myLocalScope', myVar);
}
myLocalScope();
// Run and check the console
// myVar is not defined outside of myLocalScope
console.log('outside myLocalScope', myVar);
```
# --solutions--
```js
function myLocalScope() {
// Only change code below this line
var myVar;
console.log('inside myLocalScope', myVar);
}
myLocalScope();
// Run and check the console
// myVar is not defined outside of myLocalScope
console.log('outside myLocalScope', myVar);
```

View File

@ -0,0 +1,107 @@
---
id: 5690307fddb111c6084545d7
title: Logical Order in If Else Statements
challengeType: 1
videoUrl: 'https://scrimba.com/c/cwNvMUV'
forumTopicId: 18228
dashedName: logical-order-in-if-else-statements
---
# --description--
Order is important in `if`, `else if` 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:
```js
function foo(x) {
if (x < 1) {
return "Less than one";
} else if (x < 2) {
return "Less than two";
} else {
return "Greater than or equal to two";
}
}
```
And the second just switches the order of the statements:
```js
function bar(x) {
if (x < 2) {
return "Less than two";
} else if (x < 1) {
return "Less than one";
} else {
return "Greater than or equal to two";
}
}
```
While these two functions look nearly identical if we pass a number to both we get different outputs.
```js
foo(0) // "Less than one"
bar(0) // "Less than two"
```
# --instructions--
Change the order of logic in the function so that it will return the correct statements in all cases.
# --hints--
`orderMyLogic(4)` should return "Less than 5"
```js
assert(orderMyLogic(4) === 'Less than 5');
```
`orderMyLogic(6)` should return "Less than 10"
```js
assert(orderMyLogic(6) === 'Less than 10');
```
`orderMyLogic(11)` should return "Greater than or equal to 10"
```js
assert(orderMyLogic(11) === 'Greater than or equal to 10');
```
# --seed--
## --seed-contents--
```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";
}
}
orderMyLogic(7);
```
# --solutions--
```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";
}
}
```

View File

@ -0,0 +1,88 @@
---
id: 56bbb991ad1ed5201cd392cc
title: Manipulate Arrays With pop()
challengeType: 1
videoUrl: 'https://scrimba.com/c/cRbVZAB'
forumTopicId: 18236
dashedName: manipulate-arrays-with-pop
---
# --description--
Another way to change the data in an array is with the `.pop()` function.
`.pop()` is used to "pop" a value off of the end of an array. We can store this "popped off" value by assigning it to a variable. In other words, `.pop()` removes the last element from an array and returns that element.
Any type of entry can be "popped" off of an array - numbers, strings, even nested arrays.
```js
var threeArr = [1, 4, 6];
var oneDown = threeArr.pop();
console.log(oneDown); // Returns 6
console.log(threeArr); // Returns [1, 4]
```
# --instructions--
Use the `.pop()` function to remove the last item from `myArray`, assigning the "popped off" value to `removedFromMyArray`.
# --hints--
`myArray` should only contain `[["John", 23]]`.
```js
assert(
(function (d) {
if (d[0][0] == 'John' && d[0][1] === 23 && d[1] == undefined) {
return true;
} else {
return false;
}
})(myArray)
);
```
You should use `pop()` on `myArray`.
```js
assert(/removedFromMyArray\s*=\s*myArray\s*.\s*pop\s*(\s*)/.test(code));
```
`removedFromMyArray` should only contain `["cat", 2]`.
```js
assert(
(function (d) {
if (d[0] == 'cat' && d[1] === 2 && d[2] == undefined) {
return true;
} else {
return false;
}
})(removedFromMyArray)
);
```
# --seed--
## --after-user-code--
```js
(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);
```
## --seed-contents--
```js
// Setup
var myArray = [["John", 23], ["cat", 2]];
// Only change code below this line
var removedFromMyArray;
```
# --solutions--
```js
var myArray = [["John", 23], ["cat", 2]];
var removedFromMyArray = myArray.pop();
```

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