chore(learn): audit javascript algorithms and data structures (#41092)

* chore(learn): audit basic algorithm scripting

* chore(learn): audit basic data structures

* chore(learn): audit basic javascript

* chore(learn): audit debugging

* chore(learn): audit es6

* chore(learn): audit functional programming

* chore(learn): audit intermidate algorithms

* chore(learn): audit js projects

* chore(learn): audit object oriented programming

* chore(learn): audit regex

* fix(learn): remove stray .

* fix(learn): string to code

* fix(learn): missed some

* fix(learn): clarify strings

Based on Randy's feedback, clarifies string instances where quotes
were removed in favour of back ticks.

* fix: apply suggestions - thanks Randy! :)

Co-authored-by: Randell Dawson <5313213+RandellDawson@users.noreply.github.com>

* fix: non-suggestion comments

* chore(learn): remove comments from codes

Removes the comments from the description and instruction code
blocks to ensure that all relevant information is translatable.

* fix: Apply suggestions from code review

Co-authored-by: Shaun Hamilton <51722130+ShaunSHamilton@users.noreply.github.com>

* fix: revert crowdin fix

* Update curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/mutations.md

Co-authored-by: Randell Dawson <5313213+RandellDawson@users.noreply.github.com>

* fix: Apply suggestions from code review

Co-authored-by: Shaun Hamilton <51722130+ShaunSHamilton@users.noreply.github.com>

* Update curriculum/challenges/english/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-arrays.md

Co-authored-by: Shaun Hamilton <51722130+ShaunSHamilton@users.noreply.github.com>

* fix: Apply suggestions from code review

Co-authored-by: Oliver Eyton-Williams <ojeytonwilliams@gmail.com>
Co-authored-by: Shaun Hamilton <51722130+ShaunSHamilton@users.noreply.github.com>

* chore: change voice

* fix: Christopher Nolan

* fix: expressions would evaluate

* fix: will -> would

* Update curriculum/challenges/english/02-javascript-algorithms-and-data-structures/object-oriented-programming/add-methods-after-inheritance.md

Co-authored-by: Randell Dawson <5313213+RandellDawson@users.noreply.github.com>

* fix: to work to push

* Update curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-for-loops.md

Co-authored-by: Shaun Hamilton <51722130+ShaunSHamilton@users.noreply.github.com>

* Update curriculum/challenges/english/02-javascript-algorithms-and-data-structures/object-oriented-programming/add-methods-after-inheritance.md

Co-authored-by: Randell Dawson <5313213+RandellDawson@users.noreply.github.com>

Co-authored-by: Randell Dawson <5313213+RandellDawson@users.noreply.github.com>
Co-authored-by: Shaun Hamilton <51722130+ShaunSHamilton@users.noreply.github.com>
Co-authored-by: Oliver Eyton-Williams <ojeytonwilliams@gmail.com>
This commit is contained in:
Nicholas Carrigan (he/him)
2021-03-02 16:12:12 -08:00
committed by GitHub
parent 57f3c80345
commit 7117919d36
226 changed files with 1236 additions and 1077 deletions

View File

@ -8,67 +8,67 @@ dashedName: boo-who
# --description-- # --description--
Check if a value is classified as a boolean primitive. Return true or false. Check if a value is classified as a boolean primitive. Return `true` or `false`.
Boolean primitives are true and false. Boolean primitives are `true` and `false`.
# --hints-- # --hints--
`booWho(true)` should return true. `booWho(true)` should return `true`.
```js ```js
assert.strictEqual(booWho(true), true); assert.strictEqual(booWho(true), true);
``` ```
`booWho(false)` should return true. `booWho(false)` should return `true`.
```js ```js
assert.strictEqual(booWho(false), true); assert.strictEqual(booWho(false), true);
``` ```
`booWho([1, 2, 3])` should return false. `booWho([1, 2, 3])` should return `false`.
```js ```js
assert.strictEqual(booWho([1, 2, 3]), false); assert.strictEqual(booWho([1, 2, 3]), false);
``` ```
`booWho([].slice)` should return false. `booWho([].slice)` should return `false`.
```js ```js
assert.strictEqual(booWho([].slice), false); assert.strictEqual(booWho([].slice), false);
``` ```
`booWho({ "a": 1 })` should return false. `booWho({ "a": 1 })` should return `false`.
```js ```js
assert.strictEqual(booWho({ a: 1 }), false); assert.strictEqual(booWho({ a: 1 }), false);
``` ```
`booWho(1)` should return false. `booWho(1)` should return `false`.
```js ```js
assert.strictEqual(booWho(1), false); assert.strictEqual(booWho(1), false);
``` ```
`booWho(NaN)` should return false. `booWho(NaN)` should return `false`.
```js ```js
assert.strictEqual(booWho(NaN), false); assert.strictEqual(booWho(NaN), false);
``` ```
`booWho("a")` should return false. `booWho("a")` should return `false`.
```js ```js
assert.strictEqual(booWho('a'), false); assert.strictEqual(booWho('a'), false);
``` ```
`booWho("true")` should return false. `booWho("true")` should return `false`.
```js ```js
assert.strictEqual(booWho('true'), false); assert.strictEqual(booWho('true'), false);
``` ```
`booWho("false")` should return false. `booWho("false")` should return `false`.
```js ```js
assert.strictEqual(booWho('false'), false); assert.strictEqual(booWho('false'), false);

View File

@ -14,25 +14,25 @@ This challenge *can* be solved with the `.endsWith()` method, which was introduc
# --hints-- # --hints--
`confirmEnding("Bastian", "n")` should return true. `confirmEnding("Bastian", "n")` should return `true`.
```js ```js
assert(confirmEnding('Bastian', 'n') === true); assert(confirmEnding('Bastian', 'n') === true);
``` ```
`confirmEnding("Congratulation", "on")` should return true. `confirmEnding("Congratulation", "on")` should return `true`.
```js ```js
assert(confirmEnding('Congratulation', 'on') === true); assert(confirmEnding('Congratulation', 'on') === true);
``` ```
`confirmEnding("Connor", "n")` should return false. `confirmEnding("Connor", "n")` should return `false`.
```js ```js
assert(confirmEnding('Connor', 'n') === false); 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. `confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification")` should return `false`.
```js ```js
assert( assert(
@ -43,31 +43,31 @@ assert(
); );
``` ```
`confirmEnding("He has to give me a new name", "name")` should return true. `confirmEnding("He has to give me a new name", "name")` should return `true`.
```js ```js
assert(confirmEnding('He has to give me a new name', 'name') === true); assert(confirmEnding('He has to give me a new name', 'name') === true);
``` ```
`confirmEnding("Open sesame", "same")` should return true. `confirmEnding("Open sesame", "same")` should return `true`.
```js ```js
assert(confirmEnding('Open sesame', 'same') === true); assert(confirmEnding('Open sesame', 'same') === true);
``` ```
`confirmEnding("Open sesame", "sage")` should return false. `confirmEnding("Open sesame", "sage")` should return `false`.
```js ```js
assert(confirmEnding('Open sesame', 'sage') === false); assert(confirmEnding('Open sesame', 'sage') === false);
``` ```
`confirmEnding("Open sesame", "game")` should return false. `confirmEnding("Open sesame", "game")` should return `false`.
```js ```js
assert(confirmEnding('Open sesame', 'game') === false); 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. `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 ```js
assert( assert(
@ -78,7 +78,7 @@ assert(
); );
``` ```
`confirmEnding("Abstraction", "action")` should return true. `confirmEnding("Abstraction", "action")` should return `true`.
```js ```js
assert(confirmEnding('Abstraction', 'action') === true); assert(confirmEnding('Abstraction', 'action') === true);

View File

@ -10,7 +10,7 @@ dashedName: factorialize-a-number
Return the factorial of the provided integer. 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. 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!` Factorials are often represented with the shorthand notation `n!`
@ -26,25 +26,25 @@ Only integers greater than or equal to zero will be supplied to the function.
assert(typeof factorialize(5) === 'number'); assert(typeof factorialize(5) === 'number');
``` ```
`factorialize(5)` should return 120. `factorialize(5)` should return `120`.
```js ```js
assert(factorialize(5) === 120); assert(factorialize(5) === 120);
``` ```
`factorialize(10)` should return 3628800. `factorialize(10)` should return `3628800`.
```js ```js
assert(factorialize(10) === 3628800); assert(factorialize(10) === 3628800);
``` ```
`factorialize(20)` should return 2432902008176640000. `factorialize(20)` should return `2432902008176640000`.
```js ```js
assert(factorialize(20) === 2432902008176640000); assert(factorialize(20) === 2432902008176640000);
``` ```
`factorialize(0)` should return 1. `factorialize(0)` should return `1`.
```js ```js
assert(factorialize(0) === 1); assert(factorialize(0) === 1);

View File

@ -24,7 +24,7 @@ assert(
); );
``` ```
`findLongestWordLength("The quick brown fox jumped over the lazy dog")` should return 6. `findLongestWordLength("The quick brown fox jumped over the lazy dog")` should return `6`.
```js ```js
assert( assert(
@ -32,19 +32,19 @@ assert(
); );
``` ```
`findLongestWordLength("May the force be with you")` should return 5. `findLongestWordLength("May the force be with you")` should return `5`.
```js ```js
assert(findLongestWordLength('May the force be with you') === 5); assert(findLongestWordLength('May the force be with you') === 5);
``` ```
`findLongestWordLength("Google do a barrel roll")` should return 6. `findLongestWordLength("Google do a barrel roll")` should return `6`.
```js ```js
assert(findLongestWordLength('Google do a barrel roll') === 6); assert(findLongestWordLength('Google do a barrel roll') === 6);
``` ```
`findLongestWordLength("What is the average airspeed velocity of an unladen swallow")` should return 8. `findLongestWordLength("What is the average airspeed velocity of an unladen swallow")` should return `8`.
```js ```js
assert( assert(
@ -54,7 +54,7 @@ assert(
); );
``` ```
`findLongestWordLength("What if we try a super-long word such as otorhinolaryngology")` should return 19. `findLongestWordLength("What if we try a super-long word such as otorhinolaryngology")` should return `19`.
```js ```js
assert( assert(

View File

@ -12,7 +12,7 @@ Create a function that looks through an array `arr` and returns the first elemen
# --hints-- # --hints--
`findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; })` should return 8. `findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; })` should return `8`.
```js ```js
assert.strictEqual( assert.strictEqual(
@ -23,7 +23,7 @@ assert.strictEqual(
); );
``` ```
`findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; })` should return undefined. `findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; })` should return `undefined`.
```js ```js
assert.strictEqual( assert.strictEqual(

View File

@ -8,83 +8,83 @@ dashedName: mutations
# --description-- # --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. 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. 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". 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". Lastly, `["Alien", "line"]`, should return `true` because all of the letters in `line` are present in `Alien`.
# --hints-- # --hints--
`mutation(["hello", "hey"])` should return false. `mutation(["hello", "hey"])` should return `false`.
```js ```js
assert(mutation(['hello', 'hey']) === false); assert(mutation(['hello', 'hey']) === false);
``` ```
`mutation(["hello", "Hello"])` should return true. `mutation(["hello", "Hello"])` should return `true`.
```js ```js
assert(mutation(['hello', 'Hello']) === true); assert(mutation(['hello', 'Hello']) === true);
``` ```
`mutation(["zyxwvutsrqponmlkjihgfedcba", "qrstu"])` should return true. `mutation(["zyxwvutsrqponmlkjihgfedcba", "qrstu"])` should return `true`.
```js ```js
assert(mutation(['zyxwvutsrqponmlkjihgfedcba', 'qrstu']) === true); assert(mutation(['zyxwvutsrqponmlkjihgfedcba', 'qrstu']) === true);
``` ```
`mutation(["Mary", "Army"])` should return true. `mutation(["Mary", "Army"])` should return `true`.
```js ```js
assert(mutation(['Mary', 'Army']) === true); assert(mutation(['Mary', 'Army']) === true);
``` ```
`mutation(["Mary", "Aarmy"])` should return true. `mutation(["Mary", "Aarmy"])` should return `true`.
```js ```js
assert(mutation(['Mary', 'Aarmy']) === true); assert(mutation(['Mary', 'Aarmy']) === true);
``` ```
`mutation(["Alien", "line"])` should return true. `mutation(["Alien", "line"])` should return `true`.
```js ```js
assert(mutation(['Alien', 'line']) === true); assert(mutation(['Alien', 'line']) === true);
``` ```
`mutation(["floor", "for"])` should return true. `mutation(["floor", "for"])` should return `true`.
```js ```js
assert(mutation(['floor', 'for']) === true); assert(mutation(['floor', 'for']) === true);
``` ```
`mutation(["hello", "neo"])` should return false. `mutation(["hello", "neo"])` should return `false`.
```js ```js
assert(mutation(['hello', 'neo']) === false); assert(mutation(['hello', 'neo']) === false);
``` ```
`mutation(["voodoo", "no"])` should return false. `mutation(["voodoo", "no"])` should return `false`.
```js ```js
assert(mutation(['voodoo', 'no']) === false); assert(mutation(['voodoo', 'no']) === false);
``` ```
`mutation(["ate", "date"]` should return false. `mutation(["ate", "date"])` should return `false`.
```js ```js
assert(mutation(['ate', 'date']) === false); assert(mutation(['ate', 'date']) === false);
``` ```
`mutation(["Tiger", "Zebra"])` should return false. `mutation(["Tiger", "Zebra"])` should return `false`.
```js ```js
assert(mutation(['Tiger', 'Zebra']) === false); assert(mutation(['Tiger', 'Zebra']) === false);
``` ```
`mutation(["Noel", "Ole"])` should return true. `mutation(["Noel", "Ole"])` should return `true`.
```js ```js
assert(mutation(['Noel', 'Ole']) === true); assert(mutation(['Noel', 'Ole']) === true);

View File

@ -12,37 +12,37 @@ Repeat a given string `str` (first argument) for `num` times (second argument).
# --hints-- # --hints--
`repeatStringNumTimes("*", 3)` should return `"***"`. `repeatStringNumTimes("*", 3)` should return the string `***`.
```js ```js
assert(repeatStringNumTimes('*', 3) === '***'); assert(repeatStringNumTimes('*', 3) === '***');
``` ```
`repeatStringNumTimes("abc", 3)` should return `"abcabcabc"`. `repeatStringNumTimes("abc", 3)` should return the string `abcabcabc`.
```js ```js
assert(repeatStringNumTimes('abc', 3) === 'abcabcabc'); assert(repeatStringNumTimes('abc', 3) === 'abcabcabc');
``` ```
`repeatStringNumTimes("abc", 4)` should return `"abcabcabcabc"`. `repeatStringNumTimes("abc", 4)` should return the string `abcabcabcabc`.
```js ```js
assert(repeatStringNumTimes('abc', 4) === 'abcabcabcabc'); assert(repeatStringNumTimes('abc', 4) === 'abcabcabcabc');
``` ```
`repeatStringNumTimes("abc", 1)` should return `"abc"`. `repeatStringNumTimes("abc", 1)` should return the string `abc`.
```js ```js
assert(repeatStringNumTimes('abc', 1) === 'abc'); assert(repeatStringNumTimes('abc', 1) === 'abc');
``` ```
`repeatStringNumTimes("*", 8)` should return `"********"`. `repeatStringNumTimes("*", 8)` should return the string `********`.
```js ```js
assert(repeatStringNumTimes('*', 8) === '********'); assert(repeatStringNumTimes('*', 8) === '********');
``` ```
`repeatStringNumTimes("abc", -2)` should return `""`. `repeatStringNumTimes("abc", -2)` should return an empty string (`""`).
```js ```js
assert(repeatStringNumTimes('abc', -2) === ''); assert(repeatStringNumTimes('abc', -2) === '');

View File

@ -22,19 +22,19 @@ Your result must be a string.
assert(typeof reverseString('hello') === 'string'); assert(typeof reverseString('hello') === 'string');
``` ```
`reverseString("hello")` should become `"olleh"`. `reverseString("hello")` should return the string `olleh`.
```js ```js
assert(reverseString('hello') === 'olleh'); assert(reverseString('hello') === 'olleh');
``` ```
`reverseString("Howdy")` should become `"ydwoH"`. `reverseString("Howdy")` should return the string `ydwoH`.
```js ```js
assert(reverseString('Howdy') === 'ydwoH'); assert(reverseString('Howdy') === 'ydwoH');
``` ```
`reverseString("Greetings from Earth")` should return `"htraE morf sgniteerG"`. `reverseString("Greetings from Earth")` should return the string `htraE morf sgniteerG`.
```js ```js
assert(reverseString('Greetings from Earth') === 'htraE morf sgniteerG'); assert(reverseString('Greetings from Earth') === 'htraE morf sgniteerG');

View File

@ -10,7 +10,7 @@ dashedName: title-case-a-sentence
Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lower case. 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". For the purpose of this exercise, you should also capitalize connecting words like `the` and `of`.
# --hints-- # --hints--
@ -20,19 +20,19 @@ For the purpose of this exercise, you should also capitalize connecting words li
assert(typeof titleCase("I'm a little tea pot") === 'string'); 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`. `titleCase("I'm a little tea pot")` should return the string `I'm A Little Tea Pot`.
```js ```js
assert(titleCase("I'm a little tea pot") === "I'm A Little Tea Pot"); assert(titleCase("I'm a little tea pot") === "I'm A Little Tea Pot");
``` ```
`titleCase("sHoRt AnD sToUt")` should return `Short And Stout`. `titleCase("sHoRt AnD sToUt")` should return the string `Short And Stout`.
```js ```js
assert(titleCase('sHoRt AnD sToUt') === 'Short And Stout'); 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`. `titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")` should return the string `Here Is My Handle Here Is My Spout`.
```js ```js
assert( assert(

View File

@ -12,7 +12,7 @@ Truncate a string (first argument) if it is longer than the given maximum string
# --hints-- # --hints--
`truncateString("A-tisket a-tasket A green and yellow basket", 8)` should return "A-tisket...". `truncateString("A-tisket a-tasket A green and yellow basket", 8)` should return the string `A-tisket...`.
```js ```js
assert( assert(
@ -21,7 +21,7 @@ assert(
); );
``` ```
`truncateString("Peter Piper picked a peck of pickled peppers", 11)` should return "Peter Piper...". `truncateString("Peter Piper picked a peck of pickled peppers", 11)` should return the string `Peter Piper...`.
```js ```js
assert( assert(
@ -30,7 +30,7 @@ assert(
); );
``` ```
`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". `truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length)` should return the string `A-tisket a-tasket A green and yellow basket`.
```js ```js
assert( assert(
@ -41,7 +41,7 @@ assert(
); );
``` ```
`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". `truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2)` should return the string `A-tisket a-tasket A green and yellow basket`.
```js ```js
assert( assert(
@ -52,13 +52,13 @@ assert(
); );
``` ```
`truncateString("A-", 1)` should return "A...". `truncateString("A-", 1)` should return the string `A...`.
```js ```js
assert(truncateString('A-', 1) === 'A...'); assert(truncateString('A-', 1) === 'A...');
``` ```
`truncateString("Absolutely Longer", 2)` should return "Ab...". `truncateString("Absolutely Longer", 2)` should return the string `Ab...`.
```js ```js
assert(truncateString('Absolutely Longer', 2) === 'Ab...'); assert(truncateString('Absolutely Longer', 2) === 'Ab...');

View File

@ -16,47 +16,47 @@ When we define a simple array as seen below, there are 3 items in it:
let ourArray = ["a", "b", "c"]; 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: 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 ```js
let ourVariable = ourArray[0]; let ourVariable = ourArray[0];
// ourVariable equals "a"
``` ```
Now `ourVariable` has the value of `a`.
In addition to accessing the value associated with an index, you can also *set* an index to a value using the same notation: In addition to accessing the value associated with an index, you can also *set* an index to a value using the same notation:
```js ```js
ourArray[1] = "not b anymore"; 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"`. Using bracket notation, we have now reset the item at index 1 from the string `b`, to `not b anymore`. Now `ourArray` is `["a", "not b anymore", "c"]`.
# --instructions-- # --instructions--
In order to complete this challenge, set the 2nd position (index `1`) of `myArray` to anything you want, besides `"b"`. In order to complete this challenge, set the 2nd position (index `1`) of `myArray` to anything you want, besides the letter `b`.
# --hints-- # --hints--
`myArray[0]` should be equal to `"a"` `myArray[0]` should be equal to the letter `a`
```js ```js
assert.strictEqual(myArray[0], 'a'); assert.strictEqual(myArray[0], 'a');
``` ```
`myArray[1]` should not be equal to `"b"` `myArray[1]` should not be equal to the letter `b`
```js ```js
assert.notStrictEqual(myArray[1], 'b'); assert.notStrictEqual(myArray[1], 'b');
``` ```
`myArray[2]` should be equal to `"c"` `myArray[2]` should be equal to the letter `c`
```js ```js
assert.strictEqual(myArray[2], 'c'); assert.strictEqual(myArray[2], 'c');
``` ```
`myArray[3]` should be equal to `"d"` `myArray[3]` should be equal to the letter `d`
```js ```js
assert.strictEqual(myArray[3], 'd'); assert.strictEqual(myArray[3], 'd');

View File

@ -17,12 +17,16 @@ let twentyThree = 'XXIII';
let romanNumerals = ['XXI', 'XXII']; let romanNumerals = ['XXI', 'XXII'];
romanNumerals.unshift('XIX', 'XX'); 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.
``` ```
`romanNumerals` would have the value `['XIX', 'XX', 'XXI', 'XXII']`.
```js
romanNumerals.push(twentyThree);
```
`romanNumerals` would have the value `['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-- # --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. 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.

View File

@ -16,11 +16,11 @@ const startIndex = 3;
const amountToDelete = 1; const amountToDelete = 1;
numbers.splice(startIndex, amountToDelete, 13, 14); 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); console.log(numbers);
// returns [ 10, 11, 12, 13, 14, 15 ]
``` ```
The second entry of `12` is removed, and we add `13` and `14` at the same index. The `numbers` array would now be `[ 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. 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-- # --instructions--

View File

@ -63,19 +63,19 @@ A `foods` object has been created with three entries. Using the syntax of your c
assert(typeof foods === 'object'); assert(typeof foods === 'object');
``` ```
The `foods` object should have a key `"bananas"` with a value of `13`. The `foods` object should have a key `bananas` with a value of `13`.
```js ```js
assert(foods.bananas === 13); assert(foods.bananas === 13);
``` ```
The `foods` object should have a key `"grapes"` with a value of `35`. The `foods` object should have a key `grapes` with a value of `35`.
```js ```js
assert(foods.grapes === 35); assert(foods.grapes === 35);
``` ```
The `foods` object should have a key `"strawberries"` with a value of `27`. The `foods` object should have a key `strawberries` with a value of `27`.
```js ```js
assert(foods.strawberries === 27); assert(foods.strawberries === 27);

View File

@ -15,11 +15,13 @@ For example:
```js ```js
let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears']; let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears'];
fruits.indexOf('dates'); // returns -1 fruits.indexOf('dates');
fruits.indexOf('oranges'); // returns 2 fruits.indexOf('oranges');
fruits.indexOf('pears'); // returns 1, the first index at which the element exists fruits.indexOf('pears');
``` ```
`indexOf('dates')` returns `-1`, `indexOf('oranges')` returns `2`, and `indexOf('pears')` returns `1` (the first index at which each element exists).
# --instructions-- # --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. `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.

View File

@ -13,9 +13,10 @@ Now we can add, modify, and remove keys from objects. But what if we just wanted
```js ```js
users.hasOwnProperty('Alan'); users.hasOwnProperty('Alan');
'Alan' in users; 'Alan' in users;
// both return true
``` ```
Both of these would return `true`.
# --instructions-- # --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. 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.

View File

@ -8,15 +8,16 @@ dashedName: combine-arrays-with-the-spread-operator
# --description-- # --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: 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 ```js
let thisArray = ['sage', 'rosemary', 'parsley', 'thyme']; let thisArray = ['sage', 'rosemary', 'parsley', 'thyme'];
let thatArray = ['basil', 'cilantro', ...thisArray, 'coriander']; let thatArray = ['basil', 'cilantro', ...thisArray, 'coriander'];
// thatArray now equals ['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']
``` ```
`thatArray` would have the value `['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. Using spread syntax, we have just achieved an operation that would have been more complex and more verbose had we used traditional methods.
# --instructions-- # --instructions--

View File

@ -15,10 +15,10 @@ In practice, we can use the spread operator to copy an array like so:
```js ```js
let thisArray = [true, true, undefined, false, null]; let thisArray = [true, true, undefined, false, null];
let thatArray = [...thisArray]; let thatArray = [...thisArray];
// thatArray equals [true, true, undefined, false, null]
// thisArray remains unchanged and thatArray contains the same elements as thisArray
``` ```
`thatArray` equals `[true, true, undefined, false, null]`. `thisArray` remains unchanged and `thatArray` contains the same elements as `thisArray`.
# --instructions-- # --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!). 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!).

View File

@ -14,15 +14,15 @@ The next method we will cover is `slice()`. Rather than modifying an array, `sli
let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear']; let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];
let todaysWeather = weatherConditions.slice(1, 3); let todaysWeather = weatherConditions.slice(1, 3);
// todaysWeather equals ['snow', 'sleet'];
// weatherConditions still equals ['rain', 'snow', 'sleet', 'hail', 'clear']
``` ```
`todaysWeather` would have the value `['snow', 'sleet']`, while `weatherConditions` would still have `['rain', 'snow', 'sleet', 'hail', 'clear']`.
In effect, we have created a new array by extracting elements from an existing array. In effect, we have created a new array by extracting elements from an existing array.
# --instructions-- # --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'`. 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 string elements `warm` and `sunny`.
# --hints-- # --hints--

View File

@ -13,43 +13,45 @@ Awesome! You have just learned a ton about arrays! This has been a fairly high l
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: 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 ```js
let nestedArray = [ // top, or first level - the outer most array let nestedArray = [
['deep'], // an array within an array, 2 levels of depth ['deep'],
[ [
['deeper'], ['deeper'] // 2 arrays nested 3 levels deep ['deeper'], ['deeper']
], ],
[ [
[ [
['deepest'], ['deepest'] // 2 arrays nested 4 levels deep ['deepest'], ['deepest']
], ],
[ [
[ [
['deepest-est?'] // an array nested 5 levels deep ['deepest-est?']
] ]
] ]
] ]
]; ];
``` ```
The `deep` array is nested 2 levels deep. The `deeper` arrays are 3 levels deep. The `deepest` arrays are 4 levels, and the `deepest-est?` is 5.
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: 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 ```js
console.log(nestedArray[2][1][0][0][0]); 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: This logs the string `deepest-est?`. And now that we know where that piece of data is, we can reset it if we need to:
```js ```js
nestedArray[2][1][0][0][0] = 'deeper still'; nestedArray[2][1][0][0][0] = 'deeper still';
console.log(nestedArray[2][1][0][0][0]); console.log(nestedArray[2][1][0][0][0]);
// now logs: deeper still
``` ```
Now it logs `deeper still`.
# --instructions-- # --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'`. 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-- # --hints--
@ -100,7 +102,7 @@ assert.strictEqual(
); );
``` ```
`myNestedArray` should contain exactly one occurrence of the string `"deep"` on an array nested 3 levels deep `myNestedArray` should contain exactly one occurrence of the string `deep` on an array nested 3 levels deep
```js ```js
assert( assert(
@ -129,7 +131,7 @@ assert(
); );
``` ```
`myNestedArray` should contain exactly one occurrence of the string `"deeper"` on an array nested 4 levels deep `myNestedArray` should contain exactly one occurrence of the string `deeper` on an array nested 4 levels deep
```js ```js
assert( assert(
@ -158,7 +160,7 @@ assert(
); );
``` ```
`myNestedArray` should contain exactly one occurrence of the string `"deepest"` on an array nested 5 levels deep `myNestedArray` should contain exactly one occurrence of the string `deepest` on an array nested 5 levels deep
```js ```js
assert( assert(

View File

@ -24,10 +24,9 @@ function greaterThanTen(arr) {
} }
greaterThanTen([2, 12, 8, 14, 80, 0, 1]); 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. 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, `[12, 14, 80]`, containing those items.
# --instructions-- # --instructions--
@ -35,7 +34,7 @@ We have defined a function, `filteredArray`, which takes `arr`, a nested array,
# --hints-- # --hints--
`filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)` should return `[ [10, 8, 3], [14, 6, 23] ]` `filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)` should return `[[10, 8, 3], [14, 6, 23]]`
```js ```js
assert.deepEqual( assert.deepEqual(
@ -54,7 +53,7 @@ assert.deepEqual(
); );
``` ```
`filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2)` should return `[ ["flutes", 4] ]` `filteredArray([["trumpets", 2], ["flutes", 4], ["saxophones", 2]], 2)` should return `[["flutes", 4]]`
```js ```js
assert.deepEqual( assert.deepEqual(
@ -70,7 +69,7 @@ assert.deepEqual(
); );
``` ```
`filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter")` should return `[ ["amy", "beth", "sam"] ]` `filteredArray([["amy", "beth", "sam"], ["dave", "sean", "peter"]], "peter")` should return `[["amy", "beth", "sam"]]`
```js ```js
assert.deepEqual( assert.deepEqual(
@ -85,7 +84,7 @@ assert.deepEqual(
); );
``` ```
`filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)` should return `[ ]` `filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)` should return `[]`
```js ```js
assert.deepEqual( assert.deepEqual(

View File

@ -14,15 +14,13 @@ Sometimes you may need to iterate through all the keys within an object. This re
for (let user in users) { for (let user in users) {
console.log(user); 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. This would log `Alan`, `Jeff`, `Sarah`, and `Ryan` - each value on its own line.
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-- # --instructions--

View File

@ -16,20 +16,24 @@ Let's take a look:
let greetings = ['whats up?', 'hello', 'see ya!']; let greetings = ['whats up?', 'hello', 'see ya!'];
greetings.pop(); greetings.pop();
// now equals ['whats up?', 'hello']
greetings.shift();
// now equals ['hello']
``` ```
`greetings` would have the value `['whats up?', 'hello']`.
```js
greetings.shift();
```
`greetings` would have the value `['hello']`.
We can also return the value of the removed element with either method like this: We can also return the value of the removed element with either method like this:
```js ```js
let popped = greetings.pop(); let popped = greetings.pop();
// returns 'hello'
// greetings now equals []
``` ```
`greetings` would have the value `[]`, and `popped` would have the value `hello`.
# --instructions-- # --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. 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.

View File

@ -16,19 +16,20 @@ Ok, so we've learned how to remove elements from the beginning and end of arrays
let array = ['today', 'was', 'not', 'so', 'great']; let array = ['today', 'was', 'not', 'so', 'great'];
array.splice(2, 2); array.splice(2, 2);
// remove 2 elements beginning with the 3rd element
// array now equals ['today', 'was', 'great']
``` ```
Here we remove 2 elements, beginning with the third element (at index 2). `array` would have the value `['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: `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 ```js
let array = ['I', 'am', 'feeling', 'really', 'happy']; let array = ['I', 'am', 'feeling', 'really', 'happy'];
let newArray = array.splice(3, 2); let newArray = array.splice(3, 2);
// newArray equals ['really', 'happy']
``` ```
`newArray` has the value `['really', 'happy']`.
# --instructions-- # --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`. 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`.

View File

@ -13,9 +13,10 @@ The below is an example of the simplest implementation of an array data structur
```js ```js
let simpleArray = ['one', 2, 'three', true, false, undefined, null]; let simpleArray = ['one', 2, 'three', true, false, undefined, null];
console.log(simpleArray.length); console.log(simpleArray.length);
// logs 7
``` ```
The `console.log` call displays `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. 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 ```js

View File

@ -19,12 +19,13 @@ Array indexes are written in the same bracket notation that strings use, except
```js ```js
var array = [50,60,70]; var array = [50,60,70];
array[0]; // equals 50 array[0];
var data = array[1]; // equals 60 var data = array[1];
``` ```
**Note** `array[0]` is now `50`, and `data` has the value `60`.
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.
**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-- # --instructions--

View File

@ -20,13 +20,14 @@ var arr = [
[7,8,9], [7,8,9],
[[10,11,12], 13, 14] [[10,11,12], 13, 14]
]; ];
arr[3]; // equals [[10,11,12], 13, 14] arr[3];
arr[3][0]; // equals [10,11,12] arr[3][0];
arr[3][0][1]; // equals 11 arr[3][0][1];
``` ```
**Note** `arr[3]` is `[[10, 11, 12], 13, 14]`, `arr[3][0]` is `[10, 11, 12]`, and `arr[3][0][1]` is `11`.
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.
**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-- # --instructions--

View File

@ -9,7 +9,7 @@ dashedName: accessing-nested-arrays
# --description-- # --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. 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: Here is an example of how to access a nested array:
@ -32,17 +32,19 @@ var ourPets = [
] ]
} }
]; ];
ourPets[0].names[1]; // "Fluffy" ourPets[0].names[1];
ourPets[1].names[0]; // "Spot" ourPets[1].names[0];
``` ```
`ourPets[0].names[1]` would be the string `Fluffy`, and `ourPets[1].names[0]` would be the string `Spot`.
# --instructions-- # --instructions--
Retrieve the second tree from the variable `myPlants` using object dot and array bracket notation. Retrieve the second tree from the variable `myPlants` using object dot and array bracket notation.
# --hints-- # --hints--
`secondTree` should equal "pine". `secondTree` should equal the string `pine`.
```js ```js
assert(secondTree === 'pine'); assert(secondTree === 'pine');

View File

@ -26,17 +26,19 @@ var ourStorage = {
"bottom drawer": "soda" "bottom drawer": "soda"
} }
}; };
ourStorage.cabinet["top drawer"].folder2; // "secrets" ourStorage.cabinet["top drawer"].folder2;
ourStorage.desk.drawer; // "stapler" ourStorage.desk.drawer;
``` ```
`ourStorage.cabinet["top drawer"].folder2` would be the string `secrets`, and `ourStorage.desk.drawer` would be the string `stapler`.
# --instructions-- # --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. 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-- # --hints--
`gloveBoxContents` should equal "maps". `gloveBoxContents` should equal the string `maps`.
```js ```js
assert(gloveBoxContents === 'maps'); assert(gloveBoxContents === 'maps');

View File

@ -21,16 +21,18 @@ var myObj = {
"More Space": "Spock", "More Space": "Spock",
"NoSpace": "USS Enterprise" "NoSpace": "USS Enterprise"
}; };
myObj["Space Name"]; // Kirk myObj["Space Name"];
myObj['More Space']; // Spock myObj['More Space'];
myObj["NoSpace"]; // USS Enterprise myObj["NoSpace"];
``` ```
`myObj["Space Name"]` would be the string `Kirk`, `myObj['More Space']` would be the string `Spock`, and `myObj["NoSpace"]` would be the string `USS Enterprise`.
Note that property names with spaces in them must be in quotes (single or double). Note that property names with spaces in them must be in quotes (single or double).
# --instructions-- # --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. 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-- # --hints--
@ -40,7 +42,7 @@ Read the values of the properties `"an entree"` and `"the drink"` of `testObj` u
assert(typeof entreeValue === 'string'); assert(typeof entreeValue === 'string');
``` ```
The value of `entreeValue` should be `"hamburger"` The value of `entreeValue` should be the string `hamburger`
```js ```js
assert(entreeValue === 'hamburger'); assert(entreeValue === 'hamburger');
@ -52,7 +54,7 @@ assert(entreeValue === 'hamburger');
assert(typeof drinkValue === 'string'); assert(typeof drinkValue === 'string');
``` ```
The value of `drinkValue` should be `"water"` The value of `drinkValue` should be the string `water`
```js ```js
assert(drinkValue === 'water'); assert(drinkValue === 'water');

View File

@ -20,10 +20,11 @@ var myObj = {
prop1: "val1", prop1: "val1",
prop2: "val2" prop2: "val2"
}; };
var prop1val = myObj.prop1; // val1 var prop1val = myObj.prop1;
var prop2val = myObj.prop2; // val2 var prop2val = myObj.prop2;
``` ```
`prop1val` would have a value of the string `val1`, and `prop2val` would have a value of the string `val2`.
# --instructions-- # --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`. 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`.
@ -36,7 +37,7 @@ Read in the property values of `testObj` using dot notation. Set the variable `h
assert(typeof hatValue === 'string'); assert(typeof hatValue === 'string');
``` ```
The value of `hatValue` should be `"ballcap"` The value of `hatValue` should be the string `ballcap`
```js ```js
assert(hatValue === 'ballcap'); assert(hatValue === 'ballcap');
@ -48,7 +49,7 @@ assert(hatValue === 'ballcap');
assert(typeof shirtValue === 'string'); assert(typeof shirtValue === 'string');
``` ```
The value of `shirtValue` should be `"jersey"` The value of `shirtValue` should be the string `jersey`
```js ```js
assert(shirtValue === 'jersey'); assert(shirtValue === 'jersey');

View File

@ -19,9 +19,11 @@ var dogs = {
}; };
var myDog = "Hunter"; var myDog = "Hunter";
var myBreed = dogs[myDog]; var myBreed = dogs[myDog];
console.log(myBreed); // "Doberman" console.log(myBreed);
``` ```
The string `Doberman` would be displayed in the console.
Another way you can use this concept is when the property's name is collected dynamically during the program execution, as follows: Another way you can use this concept is when the property's name is collected dynamically during the program execution, as follows:
```js ```js
@ -32,10 +34,12 @@ function propPrefix(str) {
var s = "prop"; var s = "prop";
return s + str; return s + str;
} }
var someProp = propPrefix("Name"); // someProp now holds the value 'propName' var someProp = propPrefix("Name");
console.log(someObj[someProp]); // "John" console.log(someObj[someProp]);
``` ```
`someProp` would have a value of the string `propName`, and the string `John` would be displayed in the console.
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*. 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-- # --instructions--
@ -56,7 +60,7 @@ The variable `player` should be a string
assert(typeof player === 'string'); assert(typeof player === 'string');
``` ```
The value of `player` should be "Montana" The value of `player` should be the string `Montana`
```js ```js
assert(player === 'Montana'); assert(player === 'Montana');

View File

@ -11,7 +11,7 @@ dashedName: add-new-properties-to-a-javascript-object
You can add new properties to existing JavaScript objects the same way you would modify them. 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`: Here's how we would add a `bark` property to `ourDog`:
`ourDog.bark = "bow-wow";` `ourDog.bark = "bow-wow";`
@ -19,7 +19,7 @@ or
`ourDog["bark"] = "bow-wow";` `ourDog["bark"] = "bow-wow";`
Now when we evaluate `ourDog.bark`, we'll get his bark, "bow-wow". Now when we evaluate `ourDog.bark`, we'll get his bark, `bow-wow`.
Example: Example:
@ -36,17 +36,17 @@ ourDog.bark = "bow-wow";
# --instructions-- # --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. 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-- # --hints--
You should add the property `"bark"` to `myDog`. You should add the property `bark` to `myDog`.
```js ```js
assert(myDog.bark !== undefined); assert(myDog.bark !== undefined);
``` ```
You should not add `"bark"` to the setup section. You should not add `bark` to the setup section.
```js ```js
assert(!/bark[^\n]:/.test(code)); assert(!/bark[^\n]:/.test(code));

View File

@ -18,9 +18,11 @@ JavaScript uses the `+` symbol as an addition operator when placed between two n
**Example:** **Example:**
```js ```js
myVar = 5 + 10; // assigned 15 myVar = 5 + 10;
``` ```
`myVar` now has the value `15`.
# --instructions-- # --instructions--
Change the `0` so that sum will equal `20`. Change the `0` so that sum will equal `20`.

View File

@ -31,38 +31,38 @@ switch (num) {
# --instructions-- # --instructions--
Write a switch statement to set `answer` for the following conditions: Write a switch statement to set `answer` for the following conditions:
`"a"` - "apple" `a` - `apple`
`"b"` - "bird" `b` - `bird`
`"c"` - "cat" `c` - `cat`
`default` - "stuff" `default` - `stuff`
# --hints-- # --hints--
`switchOfStuff("a")` should have a value of "apple" `switchOfStuff("a")` should return the string `apple`
```js ```js
assert(switchOfStuff('a') === 'apple'); assert(switchOfStuff('a') === 'apple');
``` ```
`switchOfStuff("b")` should have a value of "bird" `switchOfStuff("b")` should return the string `bird`
```js ```js
assert(switchOfStuff('b') === 'bird'); assert(switchOfStuff('b') === 'bird');
``` ```
`switchOfStuff("c")` should have a value of "cat" `switchOfStuff("c")` should return the string `cat`
```js ```js
assert(switchOfStuff('c') === 'cat'); assert(switchOfStuff('c') === 'cat');
``` ```
`switchOfStuff("d")` should have a value of "stuff" `switchOfStuff("d")` should return the string `stuff`
```js ```js
assert(switchOfStuff('d') === 'stuff'); assert(switchOfStuff('d') === 'stuff');
``` ```
`switchOfStuff(4)` should have a value of "stuff" `switchOfStuff(4)` should return the string `stuff`
```js ```js
assert(switchOfStuff(4) === 'stuff'); assert(switchOfStuff(4) === 'stuff');

View File

@ -17,9 +17,10 @@ Example:
var anAdjective = "awesome!"; var anAdjective = "awesome!";
var ourStr = "freeCodeCamp is "; var ourStr = "freeCodeCamp is ";
ourStr += anAdjective; ourStr += anAdjective;
// ourStr is now "freeCodeCamp is awesome!"
``` ```
`ourStr` would have the value `freeCodeCamp is awesome!`.
# --instructions-- # --instructions--
Set `someAdjective` to a string of at least 3 characters and append it to `myStr` using the `+=` operator. Set `someAdjective` to a string of at least 3 characters and append it to `myStr` using the `+=` operator.

View File

@ -32,7 +32,7 @@ You should not change code above the specified comment.
assert(/var a;/.test(code) && /a = 7;/.test(code) && /var b;/.test(code)); assert(/var a;/.test(code) && /a = 7;/.test(code) && /var b;/.test(code));
``` ```
`b` should have a value of 7. `b` should have a value of `7`.
```js ```js
assert(typeof b === 'number' && b === 7); assert(typeof b === 'number' && b === 7);

View File

@ -26,7 +26,7 @@ var cat = {
}; };
``` ```
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: 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 ```js
var anotherObject = { var anotherObject = {
@ -40,9 +40,9 @@ However, if your object has any non-string properties, JavaScript will automatic
# --instructions-- # --instructions--
Make an object that represents a dog called `myDog` which contains the properties `"name"` (a string), `"legs"`, `"tails"` and `"friends"`. 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. 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-- # --hints--

View File

@ -28,11 +28,11 @@ if (condition1) {
Write chained `if`/`else if` statements to fulfill the following conditions: Write chained `if`/`else if` statements to fulfill the following conditions:
`num < 5` - return "Tiny" `num < 5` - return `Tiny`
`num < 10` - return "Small" `num < 10` - return `Small`
`num < 15` - return "Medium" `num < 15` - return `Medium`
`num < 20` - return "Large" `num < 20` - return `Large`
`num >= 20` - return "Huge" `num >= 20` - return `Huge`
# --hints-- # --hints--
@ -54,61 +54,61 @@ You should have at least one `return` statement
assert(code.match(/return/g).length >= 1); assert(code.match(/return/g).length >= 1);
``` ```
`testSize(0)` should return "Tiny" `testSize(0)` should return the string `Tiny`
```js ```js
assert(testSize(0) === 'Tiny'); assert(testSize(0) === 'Tiny');
``` ```
`testSize(4)` should return "Tiny" `testSize(4)` should return the string `Tiny`
```js ```js
assert(testSize(4) === 'Tiny'); assert(testSize(4) === 'Tiny');
``` ```
`testSize(5)` should return "Small" `testSize(5)` should return the string `Small`
```js ```js
assert(testSize(5) === 'Small'); assert(testSize(5) === 'Small');
``` ```
`testSize(8)` should return "Small" `testSize(8)` should return the string `Small`
```js ```js
assert(testSize(8) === 'Small'); assert(testSize(8) === 'Small');
``` ```
`testSize(10)` should return "Medium" `testSize(10)` should return the string `Medium`
```js ```js
assert(testSize(10) === 'Medium'); assert(testSize(10) === 'Medium');
``` ```
`testSize(14)` should return "Medium" `testSize(14)` should return the string `Medium`
```js ```js
assert(testSize(14) === 'Medium'); assert(testSize(14) === 'Medium');
``` ```
`testSize(15)` should return "Large" `testSize(15)` should return the string `Large`
```js ```js
assert(testSize(15) === 'Large'); assert(testSize(15) === 'Large');
``` ```
`testSize(17)` should return "Large" `testSize(17)` should return the string `Large`
```js ```js
assert(testSize(17) === 'Large'); assert(testSize(17) === 'Large');
``` ```
`testSize(20)` should return "Huge" `testSize(20)` should return the string `Huge`
```js ```js
assert(testSize(20) === 'Huge'); assert(testSize(20) === 'Huge');
``` ```
`testSize(25)` should return "Huge" `testSize(25)` should return the string `Huge`
```js ```js
assert(testSize(25) === 'Huge'); assert(testSize(25) === 'Huge');

View File

@ -13,21 +13,20 @@ Comments are lines of code that JavaScript will intentionally ignore. Comments a
There are two ways to write comments in JavaScript: There are two ways to write comments in JavaScript:
Using `//` will tell JavaScript to ignore the remainder of the text on the current line: Using `//` will tell JavaScript to ignore the remainder of the text on the current line. This is an in-line comment:
```js ```js
// This is an in-line comment. // This is an in-line comment.
``` ```
You can make a multi-line comment beginning with `/*` and ending with `*/`: You can make a multi-line comment beginning with `/*` and ending with `*/`. This is a multi-line comment:
```js ```js
/* This is a /* This is a
multi-line comment */ multi-line comment */
``` ```
**Best Practice** **NOTE:** 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.
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-- # --instructions--

View File

@ -22,34 +22,36 @@ function equalityTest(myVal) {
} }
``` ```
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: 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 ```js
1 == 1 // true 1 == 1
1 == 2 // false 1 == 2
1 == '1' // true 1 == '1'
"3" == 3 // true "3" == 3
``` ```
In order, these expressions would evaluate to `true`, `false`, `true`, and `true`.
# --instructions-- # --instructions--
Add the equality operator to the indicated line so that the function will return "Equal" when `val` is equivalent to `12`. Add the equality operator to the indicated line so that the function will return the string `Equal` when `val` is equivalent to `12`.
# --hints-- # --hints--
`testEqual(10)` should return "Not Equal" `testEqual(10)` should return the string `Not Equal`
```js ```js
assert(testEqual(10) === 'Not Equal'); assert(testEqual(10) === 'Not Equal');
``` ```
`testEqual(12)` should return "Equal" `testEqual(12)` should return the string `Equal`
```js ```js
assert(testEqual(12) === 'Equal'); assert(testEqual(12) === 'Equal');
``` ```
`testEqual("12")` should return "Equal" `testEqual("12")` should return the string `Equal`
```js ```js
assert(testEqual('12') === 'Equal'); assert(testEqual('12') === 'Equal');

View File

@ -16,55 +16,57 @@ Like the equality operator, greater than operator will convert data types of val
**Examples** **Examples**
```js ```js
5 > 3 // true 5 > 3
7 > '3' // true 7 > '3'
2 > 3 // false 2 > 3
'1' > 9 // false '1' > 9
``` ```
In order, these expressions would evaluate to `true`, `true`, `false`, and `false`.
# --instructions-- # --instructions--
Add the greater than operator to the indicated lines so that the return statements make sense. Add the greater than operator to the indicated lines so that the return statements make sense.
# --hints-- # --hints--
`testGreaterThan(0)` should return "10 or Under" `testGreaterThan(0)` should return the string `10 or Under`
```js ```js
assert(testGreaterThan(0) === '10 or Under'); assert(testGreaterThan(0) === '10 or Under');
``` ```
`testGreaterThan(10)` should return "10 or Under" `testGreaterThan(10)` should return the string `10 or Under`
```js ```js
assert(testGreaterThan(10) === '10 or Under'); assert(testGreaterThan(10) === '10 or Under');
``` ```
`testGreaterThan(11)` should return "Over 10" `testGreaterThan(11)` should return the string `Over 10`
```js ```js
assert(testGreaterThan(11) === 'Over 10'); assert(testGreaterThan(11) === 'Over 10');
``` ```
`testGreaterThan(99)` should return "Over 10" `testGreaterThan(99)` should return the string `Over 10`
```js ```js
assert(testGreaterThan(99) === 'Over 10'); assert(testGreaterThan(99) === 'Over 10');
``` ```
`testGreaterThan(100)` should return "Over 10" `testGreaterThan(100)` should return the string `Over 10`
```js ```js
assert(testGreaterThan(100) === 'Over 10'); assert(testGreaterThan(100) === 'Over 10');
``` ```
`testGreaterThan(101)` should return "Over 100" `testGreaterThan(101)` should return the string `Over 100`
```js ```js
assert(testGreaterThan(101) === 'Over 100'); assert(testGreaterThan(101) === 'Over 100');
``` ```
`testGreaterThan(150)` should return "Over 100" `testGreaterThan(150)` should return the string `Over 100`
```js ```js
assert(testGreaterThan(150) === 'Over 100'); assert(testGreaterThan(150) === 'Over 100');

View File

@ -16,55 +16,57 @@ Like the equality operator, the `>=` will convert data types while comparing.
**Examples** **Examples**
```js ```js
6 >= 6 // true 6 >= 6
7 >= '3' // true 7 >= '3'
2 >= 3 // false 2 >= 3
'7' >= 9 // false '7' >= 9
``` ```
In order, these expressions would evaluate to `true`, `true`, `false`, and `false`.
# --instructions-- # --instructions--
Add the greater than or equal to operator to the indicated lines so that the return statements make sense. Add the greater than or equal to operator to the indicated lines so that the return statements make sense.
# --hints-- # --hints--
`testGreaterOrEqual(0)` should return "Less than 10" `testGreaterOrEqual(0)` should return the string `Less than 10`
```js ```js
assert(testGreaterOrEqual(0) === 'Less than 10'); assert(testGreaterOrEqual(0) === 'Less than 10');
``` ```
`testGreaterOrEqual(9)` should return "Less than 10" `testGreaterOrEqual(9)` should return the string `Less than 10`
```js ```js
assert(testGreaterOrEqual(9) === 'Less than 10'); assert(testGreaterOrEqual(9) === 'Less than 10');
``` ```
`testGreaterOrEqual(10)` should return "10 or Over" `testGreaterOrEqual(10)` should return the string `10 or Over`
```js ```js
assert(testGreaterOrEqual(10) === '10 or Over'); assert(testGreaterOrEqual(10) === '10 or Over');
``` ```
`testGreaterOrEqual(11)` should return "10 or Over" `testGreaterOrEqual(11)` should return the string `10 or Over`
```js ```js
assert(testGreaterOrEqual(11) === '10 or Over'); assert(testGreaterOrEqual(11) === '10 or Over');
``` ```
`testGreaterOrEqual(19)` should return "10 or Over" `testGreaterOrEqual(19)` should return the string `10 or Over`
```js ```js
assert(testGreaterOrEqual(19) === '10 or Over'); assert(testGreaterOrEqual(19) === '10 or Over');
``` ```
`testGreaterOrEqual(100)` should return "20 or Over" `testGreaterOrEqual(100)` should return the string `20 or Over`
```js ```js
assert(testGreaterOrEqual(100) === '20 or Over'); assert(testGreaterOrEqual(100) === '20 or Over');
``` ```
`testGreaterOrEqual(21)` should return "20 or Over" `testGreaterOrEqual(21)` should return the string `20 or Over`
```js ```js
assert(testGreaterOrEqual(21) === '20 or Over'); assert(testGreaterOrEqual(21) === '20 or Over');

View File

@ -9,49 +9,51 @@ dashedName: comparison-with-the-inequality-operator
# --description-- # --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. 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** **Examples**
```js ```js
1 != 2 // true 1 != 2
1 != "1" // false 1 != "1"
1 != '1' // false 1 != '1'
1 != true // false 1 != true
0 != false // false 0 != false
``` ```
In order, these expressions would evaluate to `true`, `false`, `false`, `false`, and `false`.
# --instructions-- # --instructions--
Add the inequality operator `!=` in the `if` statement so that the function will return "Not Equal" when `val` is not equivalent to `99` Add the inequality operator `!=` in the `if` statement so that the function will return the string `Not Equal` when `val` is not equivalent to `99`
# --hints-- # --hints--
`testNotEqual(99)` should return "Equal" `testNotEqual(99)` should return the string `Equal`
```js ```js
assert(testNotEqual(99) === 'Equal'); assert(testNotEqual(99) === 'Equal');
``` ```
`testNotEqual("99")` should return "Equal" `testNotEqual("99")` should return the string `Equal`
```js ```js
assert(testNotEqual('99') === 'Equal'); assert(testNotEqual('99') === 'Equal');
``` ```
`testNotEqual(12)` should return "Not Equal" `testNotEqual(12)` should return the string `Not Equal`
```js ```js
assert(testNotEqual(12) === 'Not Equal'); assert(testNotEqual(12) === 'Not Equal');
``` ```
`testNotEqual("12")` should return "Not Equal" `testNotEqual("12")` should return the string `Not Equal`
```js ```js
assert(testNotEqual('12') === 'Not Equal'); assert(testNotEqual('12') === 'Not Equal');
``` ```
`testNotEqual("bob")` should return "Not Equal" `testNotEqual("bob")` should return the string `Not Equal`
```js ```js
assert(testNotEqual('bob') === 'Not Equal'); assert(testNotEqual('bob') === 'Not Equal');

View File

@ -14,50 +14,52 @@ The <dfn>less than</dfn> operator (`<`) compares the values of two numbers. If t
**Examples** **Examples**
```js ```js
2 < 5 // true 2 < 5
'3' < 7 // true '3' < 7
5 < 5 // false 5 < 5
3 < 2 // false 3 < 2
'8' < 4 // false '8' < 4
``` ```
In order, these expressions would evaluate to `true`, `true`, `false`, `false`, and `false`.
# --instructions-- # --instructions--
Add the less than operator to the indicated lines so that the return statements make sense. Add the less than operator to the indicated lines so that the return statements make sense.
# --hints-- # --hints--
`testLessThan(0)` should return "Under 25" `testLessThan(0)` should return the string `Under 25`
```js ```js
assert(testLessThan(0) === 'Under 25'); assert(testLessThan(0) === 'Under 25');
``` ```
`testLessThan(24)` should return "Under 25" `testLessThan(24)` should return the string `Under 25`
```js ```js
assert(testLessThan(24) === 'Under 25'); assert(testLessThan(24) === 'Under 25');
``` ```
`testLessThan(25)` should return "Under 55" `testLessThan(25)` should return the string `Under 55`
```js ```js
assert(testLessThan(25) === 'Under 55'); assert(testLessThan(25) === 'Under 55');
``` ```
`testLessThan(54)` should return "Under 55" `testLessThan(54)` should return the string `Under 55`
```js ```js
assert(testLessThan(54) === 'Under 55'); assert(testLessThan(54) === 'Under 55');
``` ```
`testLessThan(55)` should return "55 or Over" `testLessThan(55)` should return the string `55 or Over`
```js ```js
assert(testLessThan(55) === '55 or Over'); assert(testLessThan(55) === '55 or Over');
``` ```
`testLessThan(99)` should return "55 or Over" `testLessThan(99)` should return the string `55 or Over`
```js ```js
assert(testLessThan(99) === '55 or Over'); assert(testLessThan(99) === '55 or Over');

View File

@ -14,56 +14,58 @@ The less than or equal to operator (`<=`) compares the values of two numbers. If
**Examples** **Examples**
```js ```js
4 <= 5 // true 4 <= 5
'7' <= 7 // true '7' <= 7
5 <= 5 // true 5 <= 5
3 <= 2 // false 3 <= 2
'8' <= 4 // false '8' <= 4
``` ```
In order, these expressions would evaluate to `true`, `true`, `true`, `false`, and `false`.
# --instructions-- # --instructions--
Add the less than or equal to operator to the indicated lines so that the return statements make sense. Add the less than or equal to operator to the indicated lines so that the return statements make sense.
# --hints-- # --hints--
`testLessOrEqual(0)` should return "Smaller Than or Equal to 12" `testLessOrEqual(0)` should return the string `Smaller Than or Equal to 12`
```js ```js
assert(testLessOrEqual(0) === 'Smaller Than or Equal to 12'); assert(testLessOrEqual(0) === 'Smaller Than or Equal to 12');
``` ```
`testLessOrEqual(11)` should return "Smaller Than or Equal to 12" `testLessOrEqual(11)` should return the string `Smaller Than or Equal to 12`
```js ```js
assert(testLessOrEqual(11) === 'Smaller Than or Equal to 12'); assert(testLessOrEqual(11) === 'Smaller Than or Equal to 12');
``` ```
`testLessOrEqual(12)` should return "Smaller Than or Equal to 12" `testLessOrEqual(12)` should return the string `Smaller Than or Equal to 12`
```js ```js
assert(testLessOrEqual(12) === 'Smaller Than or Equal to 12'); assert(testLessOrEqual(12) === 'Smaller Than or Equal to 12');
``` ```
`testLessOrEqual(23)` should return "Smaller Than or Equal to 24" `testLessOrEqual(23)` should return the string `Smaller Than or Equal to 24`
```js ```js
assert(testLessOrEqual(23) === 'Smaller Than or Equal to 24'); assert(testLessOrEqual(23) === 'Smaller Than or Equal to 24');
``` ```
`testLessOrEqual(24)` should return "Smaller Than or Equal to 24" `testLessOrEqual(24)` should return the string `Smaller Than or Equal to 24`
```js ```js
assert(testLessOrEqual(24) === 'Smaller Than or Equal to 24'); assert(testLessOrEqual(24) === 'Smaller Than or Equal to 24');
``` ```
`testLessOrEqual(25)` should return "More Than 24" `testLessOrEqual(25)` should return the string `More Than 24`
```js ```js
assert(testLessOrEqual(25) === 'More Than 24'); assert(testLessOrEqual(25) === 'More Than 24');
``` ```
`testLessOrEqual(55)` should return "More Than 24" `testLessOrEqual(55)` should return the string `More Than 24`
```js ```js
assert(testLessOrEqual(55) === 'More Than 24'); assert(testLessOrEqual(55) === 'More Than 24');

View File

@ -16,31 +16,33 @@ If the values being compared have different types, they are considered unequal,
**Examples** **Examples**
```js ```js
3 === 3 // true 3 === 3
3 === '3' // false 3 === '3'
``` ```
These conditions would return `true` and `false` respectively.
In the second example, `3` is a `Number` type and `'3'` is a `String` type. In the second example, `3` is a `Number` type and `'3'` is a `String` type.
# --instructions-- # --instructions--
Use the strict equality operator in the `if` statement so the function will return "Equal" when `val` is strictly equal to `7` Use the strict equality operator in the `if` statement so the function will return the string `Equal` when `val` is strictly equal to `7`
# --hints-- # --hints--
`testStrict(10)` should return "Not Equal" `testStrict(10)` should return the string `Not Equal`
```js ```js
assert(testStrict(10) === 'Not Equal'); assert(testStrict(10) === 'Not Equal');
``` ```
`testStrict(7)` should return "Equal" `testStrict(7)` should return the string `Equal`
```js ```js
assert(testStrict(7) === 'Equal'); assert(testStrict(7) === 'Equal');
``` ```
`testStrict("7")` should return "Not Equal" `testStrict("7")` should return the string `Not Equal`
```js ```js
assert(testStrict('7') === 'Not Equal'); assert(testStrict('7') === 'Not Equal');

View File

@ -14,36 +14,38 @@ The strict inequality operator (`!==`) is the logical opposite of the strict equ
**Examples** **Examples**
```js ```js
3 !== 3 // false 3 !== 3
3 !== '3' // true 3 !== '3'
4 !== 3 // true 4 !== 3
``` ```
In order, these expressions would evaluate to `false`, `true`, and `true`.
# --instructions-- # --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` Add the strict inequality operator to the `if` statement so the function will return the string `Not Equal` when `val` is not strictly equal to `17`
# --hints-- # --hints--
`testStrictNotEqual(17)` should return "Equal" `testStrictNotEqual(17)` should return the string `Equal`
```js ```js
assert(testStrictNotEqual(17) === 'Equal'); assert(testStrictNotEqual(17) === 'Equal');
``` ```
`testStrictNotEqual("17")` should return "Not Equal" `testStrictNotEqual("17")` should return the string `Not Equal`
```js ```js
assert(testStrictNotEqual('17') === 'Not Equal'); assert(testStrictNotEqual('17') === 'Not Equal');
``` ```
`testStrictNotEqual(12)` should return "Not Equal" `testStrictNotEqual(12)` should return the string `Not Equal`
```js ```js
assert(testStrictNotEqual(12) === 'Not Equal'); assert(testStrictNotEqual(12) === 'Not Equal');
``` ```
`testStrictNotEqual("bob")` should return "Not Equal" `testStrictNotEqual("bob")` should return the string `Not Equal`
```js ```js
assert(testStrictNotEqual('bob') === 'Not Equal'); assert(testStrictNotEqual('bob') === 'Not Equal');

View File

@ -22,7 +22,7 @@ if (num > 5) {
return "No"; return "No";
``` ```
will only return "Yes" if `num` is greater than `5` and less than `10`. The same logic can be written as: will only return `Yes` if `num` is greater than `5` and less than `10`. The same logic can be written as:
```js ```js
if (num > 5 && num < 10) { if (num > 5 && num < 10) {
@ -33,7 +33,7 @@ return "No";
# --instructions-- # --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"`. Replace the two if statements with one statement, using the `&&` operator, which will return the string `Yes` if `val` is less than or equal to `50` and greater than or equal to `25`. Otherwise, will return the string `No`.
# --hints-- # --hints--
@ -49,49 +49,49 @@ You should only have one `if` statement
assert(code.match(/if/g).length === 1); assert(code.match(/if/g).length === 1);
``` ```
`testLogicalAnd(0)` should return "No" `testLogicalAnd(0)` should return the string `No`
```js ```js
assert(testLogicalAnd(0) === 'No'); assert(testLogicalAnd(0) === 'No');
``` ```
`testLogicalAnd(24)` should return "No" `testLogicalAnd(24)` should return the string `No`
```js ```js
assert(testLogicalAnd(24) === 'No'); assert(testLogicalAnd(24) === 'No');
``` ```
`testLogicalAnd(25)` should return "Yes" `testLogicalAnd(25)` should return the string `Yes`
```js ```js
assert(testLogicalAnd(25) === 'Yes'); assert(testLogicalAnd(25) === 'Yes');
``` ```
`testLogicalAnd(30)` should return "Yes" `testLogicalAnd(30)` should return the string `Yes`
```js ```js
assert(testLogicalAnd(30) === 'Yes'); assert(testLogicalAnd(30) === 'Yes');
``` ```
`testLogicalAnd(50)` should return "Yes" `testLogicalAnd(50)` should return the string `Yes`
```js ```js
assert(testLogicalAnd(50) === 'Yes'); assert(testLogicalAnd(50) === 'Yes');
``` ```
`testLogicalAnd(51)` should return "No" `testLogicalAnd(51)` should return the string `No`
```js ```js
assert(testLogicalAnd(51) === 'No'); assert(testLogicalAnd(51) === 'No');
``` ```
`testLogicalAnd(75)` should return "No" `testLogicalAnd(75)` should return the string `No`
```js ```js
assert(testLogicalAnd(75) === 'No'); assert(testLogicalAnd(75) === 'No');
``` ```
`testLogicalAnd(80)` should return "No" `testLogicalAnd(80)` should return the string `No`
```js ```js
assert(testLogicalAnd(80) === 'No'); assert(testLogicalAnd(80) === 'No');

View File

@ -25,7 +25,7 @@ if (num < 5) {
return "Yes"; return "Yes";
``` ```
will return "Yes" only if `num` is between `5` and `10` (5 and 10 included). The same logic can be written as: will return `Yes` only if `num` is between `5` and `10` (5 and 10 included). The same logic can be written as:
```js ```js
if (num > 10 || num < 5) { if (num > 10 || num < 5) {
@ -36,7 +36,7 @@ return "Yes";
# --instructions-- # --instructions--
Combine the two `if` statements into one statement which returns `"Outside"` if `val` is not between `10` and `20`, inclusive. Otherwise, return `"Inside"`. Combine the two `if` statements into one statement which returns the string `Outside` if `val` is not between `10` and `20`, inclusive. Otherwise, return the string `Inside`.
# --hints-- # --hints--
@ -52,49 +52,49 @@ You should only have one `if` statement
assert(code.match(/if/g).length === 1); assert(code.match(/if/g).length === 1);
``` ```
`testLogicalOr(0)` should return "Outside" `testLogicalOr(0)` should return the string `Outside`
```js ```js
assert(testLogicalOr(0) === 'Outside'); assert(testLogicalOr(0) === 'Outside');
``` ```
`testLogicalOr(9)` should return "Outside" `testLogicalOr(9)` should return the string `Outside`
```js ```js
assert(testLogicalOr(9) === 'Outside'); assert(testLogicalOr(9) === 'Outside');
``` ```
`testLogicalOr(10)` should return "Inside" `testLogicalOr(10)` should return the string `Inside`
```js ```js
assert(testLogicalOr(10) === 'Inside'); assert(testLogicalOr(10) === 'Inside');
``` ```
`testLogicalOr(15)` should return "Inside" `testLogicalOr(15)` should return the string `Inside`
```js ```js
assert(testLogicalOr(15) === 'Inside'); assert(testLogicalOr(15) === 'Inside');
``` ```
`testLogicalOr(19)` should return "Inside" `testLogicalOr(19)` should return the string `Inside`
```js ```js
assert(testLogicalOr(19) === 'Inside'); assert(testLogicalOr(19) === 'Inside');
``` ```
`testLogicalOr(20)` should return "Inside" `testLogicalOr(20)` should return the string `Inside`
```js ```js
assert(testLogicalOr(20) === 'Inside'); assert(testLogicalOr(20) === 'Inside');
``` ```
`testLogicalOr(21)` should return "Outside" `testLogicalOr(21)` should return the string `Outside`
```js ```js
assert(testLogicalOr(21) === 'Outside'); assert(testLogicalOr(21) === 'Outside');
``` ```
`testLogicalOr(25)` should return "Outside" `testLogicalOr(25)` should return the string `Outside`
```js ```js
assert(testLogicalOr(25) === 'Outside'); assert(testLogicalOr(25) === 'Outside');

View File

@ -20,9 +20,11 @@ One such operator is the `+=` operator.
```js ```js
var myVar = 1; var myVar = 1;
myVar += 5; myVar += 5;
console.log(myVar); // Returns 6 console.log(myVar);
``` ```
`6` would be displayed in the console.
# --instructions-- # --instructions--
Convert the assignments for `a`, `b`, and `c` to use the `+=` operator. Convert the assignments for `a`, `b`, and `c` to use the `+=` operator.

View File

@ -17,23 +17,22 @@ In JavaScript, when the `+` operator is used with a `String` value, it is called
'My name is Alan,' + ' I concatenate.' 'My name is Alan,' + ' I concatenate.'
``` ```
**Note** **Note:** Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.
Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.
Example: Example:
```js ```js
var ourStr = "I come first. " + "I come second."; var ourStr = "I come first. " + "I come second.";
// ourStr is "I come first. I come second."
``` ```
The string `I come first. I come second.` would be displayed in the console.
# --instructions-- # --instructions--
Build `myStr` from the strings `"This is the start. "` and `"This is the end."` using the `+` operator. Build `myStr` from the strings `This is the start. ` and `This is the end.` using the `+` operator.
# --hints-- # --hints--
`myStr` should have a value of `This is the start. This is the end.` `myStr` should have a value of the string `This is the start. This is the end.`
```js ```js
assert(myStr === 'This is the start. This is the end.'); assert(myStr === 'This is the start. This is the end.');

View File

@ -11,24 +11,24 @@ dashedName: concatenating-strings-with-the-plus-equals-operator
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. 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** **Note:** Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.
Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.
Example: Example:
```js ```js
var ourStr = "I come first. "; var ourStr = "I come first. ";
ourStr += "I come second."; ourStr += "I come second.";
// ourStr is now "I come first. I come second."
``` ```
`ourStr` now has a value of the string `I come first. I come second.`.
# --instructions-- # --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. 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-- # --hints--
`myStr` should have a value of `This is the first sentence. This is the second sentence.` `myStr` should have a value of the string `This is the first sentence. This is the second sentence.`
```js ```js
assert(myStr === 'This is the first sentence. This is the second sentence.'); assert(myStr === 'This is the first sentence. This is the second sentence.');

View File

@ -16,12 +16,13 @@ Example:
```js ```js
var ourName = "freeCodeCamp"; var ourName = "freeCodeCamp";
var ourStr = "Hello, our name is " + ourName + ", how are you?"; var ourStr = "Hello, our name is " + ourName + ", how are you?";
// ourStr is now "Hello, our name is freeCodeCamp, how are you?"
``` ```
`ourStr` would have a value of the string `Hello, our name is freeCodeCamp, how are you?`.
# --instructions-- # --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!"` 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-- # --hints--

View File

@ -11,7 +11,7 @@ dashedName: count-backwards-with-a-for-loop
A for loop can also count backwards, so long as we can define the right conditions. 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`. 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`. We'll start at `i = 10` and loop while `i > 0`. We'll decrement `i` by 2 each loop with `i -= 2`.
@ -22,7 +22,7 @@ for (var i = 10; i > 0; i -= 2) {
} }
``` ```
`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. `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-- # --instructions--

View File

@ -47,7 +47,7 @@ assert(
); );
``` ```
Cards Sequence 7, 8, 9 should return `0 Hold` Cards Sequence 7, 8, 9 should return the string `0 Hold`
```js ```js
assert( assert(
@ -64,7 +64,7 @@ assert(
); );
``` ```
Cards Sequence 10, J, Q, K, A should return `-5 Hold` Cards Sequence 10, J, Q, K, A should return the string `-5 Hold`
```js ```js
assert( assert(
@ -83,7 +83,7 @@ assert(
); );
``` ```
Cards Sequence 3, 7, Q, 8, A should return `-1 Hold` Cards Sequence 3, 7, Q, 8, A should return the string `-1 Hold`
```js ```js
assert( assert(
@ -102,7 +102,7 @@ assert(
); );
``` ```
Cards Sequence 2, J, 9, 2, 7 should return `1 Bet` Cards Sequence 2, J, 9, 2, 7 should return the string `1 Bet`
```js ```js
assert( assert(
@ -121,7 +121,7 @@ assert(
); );
``` ```
Cards Sequence 2, 2, 10 should return `1 Bet` Cards Sequence 2, 2, 10 should return the string `1 Bet`
```js ```js
assert( assert(
@ -138,7 +138,7 @@ assert(
); );
``` ```
Cards Sequence 3, 2, A, 10, K should return `-1 Hold` Cards Sequence 3, 2, A, 10, K should return the string `-1 Hold`
```js ```js
assert( assert(

View File

@ -11,8 +11,7 @@ dashedName: create-decimal-numbers-with-javascript
We can store decimal numbers in variables too. Decimal numbers are sometimes referred to as <dfn>floating point</dfn> numbers or <dfn>floats</dfn>. 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** **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).
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-- # --instructions--

View File

@ -17,7 +17,7 @@ Previously we have used the code
# --instructions-- # --instructions--
Create two new `string` variables: `myFirstName` and `myLastName` and assign them the values of your first and last name, respectively. Create two new string variables: `myFirstName` and `myLastName` and assign them the values of your first and last name, respectively.
# --hints-- # --hints--

View File

@ -17,8 +17,7 @@ is the equivalent of
`i = i - 1;` `i = i - 1;`
**Note** **Note:** The entire line becomes `i--;`, eliminating the need for the equal sign.
The entire line becomes `i--;`, eliminating the need for the equal sign.
# --instructions-- # --instructions--

View File

@ -40,11 +40,11 @@ After the last line shown above, `ourDog` looks like:
# --instructions-- # --instructions--
Delete the `"tails"` property from `myDog`. You may use either dot or bracket notation. Delete the `tails` property from `myDog`. You may use either dot or bracket notation.
# --hints-- # --hints--
You should delete the property `"tails"` from `myDog`. You should delete the property `tails` from `myDog`.
```js ```js
assert(typeof myDog === 'object' && myDog.tails === undefined); assert(typeof myDog === 'object' && myDog.tails === undefined);

View File

@ -16,9 +16,10 @@ JavaScript uses the `/` symbol for division.
**Example** **Example**
```js ```js
myVar = 16 / 2; // assigned 8 myVar = 16 / 2;
``` ```
`myVar` now has the value `8`.
# --instructions-- # --instructions--
Change the `0` so that the `quotient` is equal to `2`. Change the `0` so that the `quotient` is equal to `2`.

View File

@ -11,9 +11,13 @@ dashedName: find-the-length-of-a-string
You can find the length of a `String` value by writing `.length` after the string variable or string literal. You can find the length of a `String` value by writing `.length` after the string variable or string literal.
`"Alan Peter".length; // 10` ```js
console.log("Alan Peter".length);
```
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. The value `10` would be displayed in the console.
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-- # --instructions--

View File

@ -20,8 +20,7 @@ In mathematics, a number can be checked to be even or odd by checking the remain
<blockquote>17 % 2 = 1 (17 is Odd)<br>48 % 2 = 0 (48 is Even)</blockquote> <blockquote>17 % 2 = 1 (17 is Odd)<br>48 % 2 = 0 (48 is Even)</blockquote>
**Note** **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.
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-- # --instructions--

View File

@ -13,8 +13,7 @@ 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` 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** **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.
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-- # --instructions--

View File

@ -21,11 +21,11 @@ function myFun() {
} }
``` ```
The function `myFun` will return `"Head"` because the `local` version of the variable is present. The function `myFun` will return the string `Head` because the `local` version of the variable is present.
# --instructions-- # --instructions--
Add a local variable to `myOutfit` function to override the value of `outerWear` with `"sweater"`. Add a local variable to `myOutfit` function to override the value of `outerWear` with the string `sweater`.
# --hints-- # --hints--
@ -35,7 +35,7 @@ You should not change the value of the global `outerWear`.
assert(outerWear === 'T-Shirt'); assert(outerWear === 'T-Shirt');
``` ```
`myOutfit` should return `"sweater"`. `myOutfit` should return the string `sweater`.
```js ```js
assert(myOutfit() === 'sweater'); assert(myOutfit() === 'sweater');

View File

@ -19,67 +19,67 @@ Your function will be passed `par` and `strokes` arguments. Return the correct s
# --hints-- # --hints--
`golfScore(4, 1)` should return "Hole-in-one!" `golfScore(4, 1)` should return the string `Hole-in-one!`
```js ```js
assert(golfScore(4, 1) === 'Hole-in-one!'); assert(golfScore(4, 1) === 'Hole-in-one!');
``` ```
`golfScore(4, 2)` should return "Eagle" `golfScore(4, 2)` should return the string `Eagle`
```js ```js
assert(golfScore(4, 2) === 'Eagle'); assert(golfScore(4, 2) === 'Eagle');
``` ```
`golfScore(5, 2)` should return "Eagle" `golfScore(5, 2)` should return the string `Eagle`
```js ```js
assert(golfScore(5, 2) === 'Eagle'); assert(golfScore(5, 2) === 'Eagle');
``` ```
`golfScore(4, 3)` should return "Birdie" `golfScore(4, 3)` should return the string `Birdie`
```js ```js
assert(golfScore(4, 3) === 'Birdie'); assert(golfScore(4, 3) === 'Birdie');
``` ```
`golfScore(4, 4)` should return "Par" `golfScore(4, 4)` should return the string `Par`
```js ```js
assert(golfScore(4, 4) === 'Par'); assert(golfScore(4, 4) === 'Par');
``` ```
`golfScore(1, 1)` should return "Hole-in-one!" `golfScore(1, 1)` should return the string `Hole-in-one!`
```js ```js
assert(golfScore(1, 1) === 'Hole-in-one!'); assert(golfScore(1, 1) === 'Hole-in-one!');
``` ```
`golfScore(5, 5)` should return "Par" `golfScore(5, 5)` should return the string `Par`
```js ```js
assert(golfScore(5, 5) === 'Par'); assert(golfScore(5, 5) === 'Par');
``` ```
`golfScore(4, 5)` should return "Bogey" `golfScore(4, 5)` should return the string `Bogey`
```js ```js
assert(golfScore(4, 5) === 'Bogey'); assert(golfScore(4, 5) === 'Bogey');
``` ```
`golfScore(4, 6)` should return "Double Bogey" `golfScore(4, 6)` should return the string `Double Bogey`
```js ```js
assert(golfScore(4, 6) === 'Double Bogey'); assert(golfScore(4, 6) === 'Double Bogey');
``` ```
`golfScore(4, 7)` should return "Go Home!" `golfScore(4, 7)` should return the string `Go Home!`
```js ```js
assert(golfScore(4, 7) === 'Go Home!'); assert(golfScore(4, 7) === 'Go Home!');
``` ```
`golfScore(5, 9)` should return "Go Home!" `golfScore(5, 9)` should return the string `Go Home!`
```js ```js
assert(golfScore(5, 9) === 'Go Home!'); assert(golfScore(5, 9) === 'Go Home!');

View File

@ -17,8 +17,7 @@ is the equivalent of
`i = i + 1;` `i = i + 1;`
**Note** **Note:** The entire line becomes `i++;`, eliminating the need for the equal sign.
The entire line becomes `i++;`, eliminating the need for the equal sign.
# --instructions-- # --instructions--

View File

@ -49,31 +49,31 @@ assert(
); );
``` ```
`testElseIf(0)` should return "Smaller than 5" `testElseIf(0)` should return the string `Smaller than 5`
```js ```js
assert(testElseIf(0) === 'Smaller than 5'); assert(testElseIf(0) === 'Smaller than 5');
``` ```
`testElseIf(5)` should return "Between 5 and 10" `testElseIf(5)` should return the string `Between 5 and 10`
```js ```js
assert(testElseIf(5) === 'Between 5 and 10'); assert(testElseIf(5) === 'Between 5 and 10');
``` ```
`testElseIf(7)` should return "Between 5 and 10" `testElseIf(7)` should return the string `Between 5 and 10`
```js ```js
assert(testElseIf(7) === 'Between 5 and 10'); assert(testElseIf(7) === 'Between 5 and 10');
``` ```
`testElseIf(10)` should return "Between 5 and 10" `testElseIf(10)` should return the string `Between 5 and 10`
```js ```js
assert(testElseIf(10) === 'Between 5 and 10'); assert(testElseIf(10) === 'Between 5 and 10');
``` ```
`testElseIf(12)` should return "Greater than 10" `testElseIf(12)` should return the string `Greater than 10`
```js ```js
assert(testElseIf(12) === 'Greater than 10'); assert(testElseIf(12) === 'Greater than 10');

View File

@ -37,25 +37,25 @@ You should use an `else` statement
assert(/else/g.test(code)); assert(/else/g.test(code));
``` ```
`testElse(4)` should return "5 or Smaller" `testElse(4)` should return the string `5 or Smaller`
```js ```js
assert(testElse(4) === '5 or Smaller'); assert(testElse(4) === '5 or Smaller');
``` ```
`testElse(5)` should return "5 or Smaller" `testElse(5)` should return the string `5 or Smaller`
```js ```js
assert(testElse(5) === '5 or Smaller'); assert(testElse(5) === '5 or Smaller');
``` ```
`testElse(6)` should return "Bigger than 5" `testElse(6)` should return the string `Bigger than 5`
```js ```js
assert(testElse(6) === 'Bigger than 5'); assert(testElse(6) === 'Bigger than 5');
``` ```
`testElse(10)` should return "Bigger than 5". `testElse(10)` should return the string `Bigger than 5`
```js ```js
assert(testElse(10) === 'Bigger than 5'); assert(testElse(10) === 'Bigger than 5');

View File

@ -11,19 +11,19 @@ dashedName: iterate-with-javascript-for-loops
You can run the same code multiple times by using a loop. 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. 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 loops are declared with three optional expressions separated by semicolons:
`for ([initialization]; [condition]; [final-expression])` `for (a; b; c)`, where `a` is the intialization statement, `b` is the condition statement, and `c` is the 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 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 condition statement is evaluated at the beginning of every loop iteration and will continue as long as it evaluates to `true`. When the condition is `false` at the start of the iteration, the loop will stop executing. This means if the 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. 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`. 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 ```js
var ourArray = []; var ourArray = [];
@ -32,11 +32,11 @@ for (var i = 0; i < 5; i++) {
} }
``` ```
`ourArray` will now contain `[0,1,2,3,4]`. `ourArray` will now have the value `[0,1,2,3,4]`.
# --instructions-- # --instructions--
Use a `for` loop to work to push the values 1 through 5 onto `myArray`. Use a `for` loop to push the values 1 through 5 onto `myArray`.
# --hints-- # --hints--

View File

@ -11,7 +11,7 @@ dashedName: iterate-with-javascript-while-loops
You can run the same code multiple times by using a loop. 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. 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 ```js
var ourArray = []; var ourArray = [];

View File

@ -9,7 +9,7 @@ dashedName: local-scope-and-functions
# --description-- # --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. 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`. Here is a function `myTest` with a local variable called `loc`.
@ -18,17 +18,17 @@ function myTest() {
var loc = "foo"; var loc = "foo";
console.log(loc); console.log(loc);
} }
myTest(); // logs "foo" myTest();
console.log(loc); // loc is not defined console.log(loc);
``` ```
`loc` is not defined outside of the function. The `myTest()` function call will display the string `foo` in the console. The `console.log(loc)` line will throw an error, as `loc` is not defined outside of the function.
# --instructions-- # --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. 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. **Note:** The console will still display `ReferenceError: myVar is not defined`, but this will not cause the tests to fail.
# --hints-- # --hints--

View File

@ -46,29 +46,31 @@ function bar(x) {
While these two functions look nearly identical if we pass a number to both we get different outputs. While these two functions look nearly identical if we pass a number to both we get different outputs.
```js ```js
foo(0) // "Less than one" foo(0)
bar(0) // "Less than two" bar(0)
``` ```
`foo(0)` will return the string `Less than one`, and `bar(0)` will return the string `Less than two`.
# --instructions-- # --instructions--
Change the order of logic in the function so that it will return the correct statements in all cases. Change the order of logic in the function so that it will return the correct statements in all cases.
# --hints-- # --hints--
`orderMyLogic(4)` should return "Less than 5" `orderMyLogic(4)` should return the string `Less than 5`
```js ```js
assert(orderMyLogic(4) === 'Less than 5'); assert(orderMyLogic(4) === 'Less than 5');
``` ```
`orderMyLogic(6)` should return "Less than 10" `orderMyLogic(6)` should return the string `Less than 10`
```js ```js
assert(orderMyLogic(6) === 'Less than 10'); assert(orderMyLogic(6) === 'Less than 10');
``` ```
`orderMyLogic(11)` should return "Greater than or equal to 10" `orderMyLogic(11)` should return the string `Greater than or equal to 10`
```js ```js
assert(orderMyLogic(11) === 'Greater than or equal to 10'); assert(orderMyLogic(11) === 'Greater than or equal to 10');

View File

@ -11,20 +11,22 @@ dashedName: manipulate-arrays-with-pop
Another way to change the data in an array is with the `.pop()` function. 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. `.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. Any type of entry can be popped off of an array - numbers, strings, even nested arrays.
```js ```js
var threeArr = [1, 4, 6]; var threeArr = [1, 4, 6];
var oneDown = threeArr.pop(); var oneDown = threeArr.pop();
console.log(oneDown); // Returns 6 console.log(oneDown);
console.log(threeArr); // Returns [1, 4] console.log(threeArr);
``` ```
The first `console.log` will display the value `6`, and the second will display the value `[1, 4]`.
# --instructions-- # --instructions--
Use the `.pop()` function to remove the last item from `myArray`, assigning the "popped off" value to `removedFromMyArray`. Use the `.pop()` function to remove the last item from `myArray`, assigning the popped off value to `removedFromMyArray`.
# --hints-- # --hints--

View File

@ -18,13 +18,13 @@ Examples:
```js ```js
var arr1 = [1,2,3]; var arr1 = [1,2,3];
arr1.push(4); arr1.push(4);
// arr1 is now [1,2,3,4]
var arr2 = ["Stimpson", "J", "cat"]; var arr2 = ["Stimpson", "J", "cat"];
arr2.push(["happy", "joy"]); arr2.push(["happy", "joy"]);
// arr2 now equals ["Stimpson", "J", "cat", ["happy", "joy"]]
``` ```
`arr1` now has the value `[1, 2, 3, 4]` and `arr2` has the value `["Stimpson", "J", "cat", ["happy", "joy"]]`.
# --instructions-- # --instructions--
Push `["dog", 3]` onto the end of the `myArray` variable. Push `["dog", 3]` onto the end of the `myArray` variable.

View File

@ -18,9 +18,10 @@ Example:
```js ```js
var ourArray = ["Stimpson", "J", ["cat"]]; var ourArray = ["Stimpson", "J", ["cat"]];
var removedFromOurArray = ourArray.shift(); var removedFromOurArray = ourArray.shift();
// removedFromOurArray now equals "Stimpson" and ourArray now equals ["J", ["cat"]].
``` ```
`removedFromOurArray` would have a value of the string `Stimpson`, and `ourArray` would have `["J", ["cat"]]`.
# --instructions-- # --instructions--
Use the `.shift()` function to remove the first item from `myArray`, assigning the "shifted off" value to `removedFromMyArray`. Use the `.shift()` function to remove the first item from `myArray`, assigning the "shifted off" value to `removedFromMyArray`.

View File

@ -17,11 +17,12 @@ Example:
```js ```js
var ourArray = ["Stimpson", "J", "cat"]; var ourArray = ["Stimpson", "J", "cat"];
ourArray.shift(); // ourArray now equals ["J", "cat"] ourArray.shift();
ourArray.unshift("Happy"); ourArray.unshift("Happy");
// ourArray now equals ["Happy", "J", "cat"]
``` ```
After the `shift`, `ourArray` would have the value `["J", "cat"]`. After the `unshift`, `ourArray` would have the value `["Happy", "J", "cat"]`.
# --instructions-- # --instructions--
Add `["Paul",35]` to the beginning of the `myArray` variable using `unshift()`. Add `["Paul",35]` to the beginning of the `myArray` variable using `unshift()`.

View File

@ -29,7 +29,7 @@ var ourMusic = [
]; ];
``` ```
This is an array which contains one object inside. The object has various pieces of <dfn>metadata</dfn> about an album. It also has a nested `"formats"` array. If you want to add more album records, you can do this by adding records to the top level array. Objects hold data in a property, which has a key-value format. In the example above, `"artist": "Daft Punk"` is a property that has a key of `"artist"` and a value of `"Daft Punk"`. [JavaScript Object Notation](http://www.json.org/) or `JSON` is a related data interchange format used to store data. This is an array which contains one object inside. The object has various pieces of <dfn>metadata</dfn> about an album. It also has a nested `formats` array. If you want to add more album records, you can do this by adding records to the top level array. Objects hold data in a property, which has a key-value format. In the example above, `"artist": "Daft Punk"` is a property that has a key of `artist` and a value of `Daft Punk`. [JavaScript Object Notation](http://www.json.org/) or `JSON` is a related data interchange format used to store data.
```json ```json
{ {
@ -45,8 +45,7 @@ This is an array which contains one object inside. The object has various pieces
} }
``` ```
**Note** **Note:** You will need to place a comma after every object in the array, unless it is the last object in the array.
You will need to place a comma after every object in the array, unless it is the last object in the array.
# --instructions-- # --instructions--

View File

@ -15,11 +15,12 @@ Unlike strings, the entries of arrays are <dfn>mutable</dfn> and can be changed
```js ```js
var ourArray = [50,40,30]; var ourArray = [50,40,30];
ourArray[0] = 15; // equals [15,40,30] ourArray[0] = 15;
``` ```
**Note** `ourArray` now has the value `[15, 40, 30]`.
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.
**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-- # --instructions--
@ -27,7 +28,7 @@ Modify the data stored at index `0` of `myArray` to a value of `45`.
# --hints-- # --hints--
`myArray` should now be [45,64,99]. `myArray` should now be `[45,64,99]`.
```js ```js
assert( assert(

View File

@ -29,64 +29,63 @@ Cases for 1, 2, and 3 will all produce the same result.
# --instructions-- # --instructions--
Write a switch statement to set `answer` for the following ranges: Write a switch statement to set `answer` for the following ranges:
`1-3` - "Low" `1-3` - `Low`
`4-6` - "Mid" `4-6` - `Mid`
`7-9` - "High" `7-9` - `High`
**Note** **Note:** You will need to have a `case` statement for each number in the range.
You will need to have a `case` statement for each number in the range.
# --hints-- # --hints--
`sequentialSizes(1)` should return "Low" `sequentialSizes(1)` should return the string `Low`
```js ```js
assert(sequentialSizes(1) === 'Low'); assert(sequentialSizes(1) === 'Low');
``` ```
`sequentialSizes(2)` should return "Low" `sequentialSizes(2)` should return the string `Low`
```js ```js
assert(sequentialSizes(2) === 'Low'); assert(sequentialSizes(2) === 'Low');
``` ```
`sequentialSizes(3)` should return "Low" `sequentialSizes(3)` should return the string `Low`
```js ```js
assert(sequentialSizes(3) === 'Low'); assert(sequentialSizes(3) === 'Low');
``` ```
`sequentialSizes(4)` should return "Mid" `sequentialSizes(4)` should return the string `Mid`
```js ```js
assert(sequentialSizes(4) === 'Mid'); assert(sequentialSizes(4) === 'Mid');
``` ```
`sequentialSizes(5)` should return "Mid" `sequentialSizes(5)` should return the string `Mid`
```js ```js
assert(sequentialSizes(5) === 'Mid'); assert(sequentialSizes(5) === 'Mid');
``` ```
`sequentialSizes(6)` should return "Mid" `sequentialSizes(6)` should return the string `Mid`
```js ```js
assert(sequentialSizes(6) === 'Mid'); assert(sequentialSizes(6) === 'Mid');
``` ```
`sequentialSizes(7)` should return "High" `sequentialSizes(7)` should return the string `High`
```js ```js
assert(sequentialSizes(7) === 'High'); assert(sequentialSizes(7) === 'High');
``` ```
`sequentialSizes(8)` should return "High" `sequentialSizes(8)` should return the string `High`
```js ```js
assert(sequentialSizes(8) === 'High'); assert(sequentialSizes(8) === 'High');
``` ```
`sequentialSizes(9)` should return "High" `sequentialSizes(9)` should return the string `High`
```js ```js
assert(sequentialSizes(9) === 'High'); assert(sequentialSizes(9) === 'High');

View File

@ -16,9 +16,11 @@ JavaScript uses the `*` symbol for multiplication of two numbers.
**Example** **Example**
```js ```js
myVar = 13 * 13; // assigned 169 myVar = 13 * 13;
``` ```
`myVar` would have the value `169`.
# --instructions-- # --instructions--
Change the `0` so that product will equal `80`. Change the `0` so that product will equal `80`.

View File

@ -15,32 +15,30 @@ If the values being compared are not of the same type, the equality operator wil
**Examples** **Examples**
```js `3 == '3'` returns `true` because JavaScript performs type conversion from string to number. `3 === '3'` returns false because the types are different and type conversion is not performed.
3 == '3' // returns true because JavaScript performs type conversion from string to number
3 === '3' // returns false because the types are different and type conversion is not performed
```
**Note** **Note:** In JavaScript, you can determine the type of a variable or a value with the `typeof` operator, as follows:
In JavaScript, you can determine the type of a variable or a value with the `typeof` operator, as follows:
```js ```js
typeof 3 // returns 'number' typeof 3
typeof '3' // returns 'string' typeof '3'
``` ```
`typeof 3` returns the string `number`, and `typeof '3'` returns the string `string`.
# --instructions-- # --instructions--
The `compareEquality` function in the editor compares two values using the equality operator. Modify the function so that it returns "Equal" only when the values are strictly equal. The `compareEquality` function in the editor compares two values using the equality operator. Modify the function so that it returns the string `Equal` only when the values are strictly equal.
# --hints-- # --hints--
`compareEquality(10, "10")` should return "Not Equal" `compareEquality(10, "10")` should return the string `Not Equal`
```js ```js
assert(compareEquality(10, '10') === 'Not Equal'); assert(compareEquality(10, '10') === 'Not Equal');
``` ```
`compareEquality("20", 20)` should return "Not Equal" `compareEquality("20", 20)` should return the string `Not Equal`
```js ```js
assert(compareEquality('20', 20) === 'Not Equal'); assert(compareEquality('20', 20) === 'Not Equal');

View File

@ -17,13 +17,13 @@ The function should check if `name` is an actual contact's `firstName` and the g
If both are true, then return the "value" of that property. If both are true, then return the "value" of that property.
If `name` does not correspond to any contacts then return `"No such contact"`. If `name` does not correspond to any contacts then return the string `No such contact`.
If `prop` does not correspond to any valid properties of a contact found to match `name` then return `"No such property"`. If `prop` does not correspond to any valid properties of a contact found to match `name` then return the string `No such property`.
# --hints-- # --hints--
`lookUpProfile("Kristian", "lastName")` should return `"Vos"` `lookUpProfile("Kristian", "lastName")` should return the string `Vos`
```js ```js
assert(lookUpProfile('Kristian', 'lastName') === 'Vos'); assert(lookUpProfile('Kristian', 'lastName') === 'Vos');
@ -44,19 +44,19 @@ assert.deepEqual(lookUpProfile('Sherlock', 'likes'), [
assert(typeof lookUpProfile('Harry', 'likes') === 'object'); assert(typeof lookUpProfile('Harry', 'likes') === 'object');
``` ```
`lookUpProfile("Bob", "number")` should return "No such contact" `lookUpProfile("Bob", "number")` should return the string `No such contact`
```js ```js
assert(lookUpProfile('Bob', 'number') === 'No such contact'); assert(lookUpProfile('Bob', 'number') === 'No such contact');
``` ```
`lookUpProfile("Bob", "potato")` should return "No such contact" `lookUpProfile("Bob", "potato")` should return the string `No such contact`
```js ```js
assert(lookUpProfile('Bob', 'potato') === 'No such contact'); assert(lookUpProfile('Bob', 'potato') === 'No such contact');
``` ```
`lookUpProfile("Akira", "address")` should return "No such property" `lookUpProfile("Akira", "address")` should return the string `No such property`
```js ```js
assert(lookUpProfile('Akira', 'address') === 'No such property'); assert(lookUpProfile('Akira', 'address') === 'No such property');

View File

@ -26,12 +26,14 @@ However, this becomes a problem if you need to use the outermost quotes within i
```js ```js
goodStr = 'Jake asks Finn, "Hey, let\'s go on an adventure?"'; goodStr = 'Jake asks Finn, "Hey, let\'s go on an adventure?"';
badStr = 'Finn responds, "Let's go!"'; // Throws an error badStr = 'Finn responds, "Let's go!"';
``` ```
In the <dfn>goodStr</dfn> above, you can use both quotes safely by using the backslash <code>\\</code> as an escape character. Here `badStr` will throw an error.
**Note:** The backslash <code>\\</code> should not be confused with the forward slash `/`. They do not do the same thing. In the <dfn>goodStr</dfn> above, you can use both quotes safely by using the backslash `\` as an escape character.
**Note:** The backslash `\` should not be confused with the forward slash `/`. They do not do the same thing.
# --instructions-- # --instructions--

View File

@ -22,7 +22,7 @@ You start with an `updateRecords` function that takes an object like `collection
# --hints-- # --hints--
After `updateRecords(collection, 5439, "artist", "ABBA")`, `artist` should be `ABBA` After `updateRecords(collection, 5439, "artist", "ABBA")`, `artist` should be the string `ABBA`
```js ```js
assert( assert(
@ -31,7 +31,7 @@ assert(
); );
``` ```
After `updateRecords(collection, 5439, "tracks", "Take a Chance on Me")`, `tracks` should have `Take a Chance on Me` as the last element. After `updateRecords(collection, 5439, "tracks", "Take a Chance on Me")`, `tracks` should have the string `Take a Chance on Me` as the last element.
```js ```js
assert( assert(
@ -48,7 +48,7 @@ updateRecords(_recordCollection, 2548, 'artist', '');
assert(!_recordCollection[2548].hasOwnProperty('artist')); assert(!_recordCollection[2548].hasOwnProperty('artist'));
``` ```
After `updateRecords(collection, 1245, "tracks", "Addicted to Love")`, `tracks` should have `Addicted to Love` as the last element. After `updateRecords(collection, 1245, "tracks", "Addicted to Love")`, `tracks` should have the string `Addicted to Love` as the last element.
```js ```js
assert( assert(
@ -58,7 +58,7 @@ assert(
); );
``` ```
After `updateRecords(collection, 2468, "tracks", "Free")`, `tracks` should have `1999` as the first element. After `updateRecords(collection, 2468, "tracks", "Free")`, `tracks` should have the string `1999` as the first element.
```js ```js
assert( assert(
@ -75,7 +75,7 @@ updateRecords(_recordCollection, 2548, 'tracks', '');
assert(!_recordCollection[2548].hasOwnProperty('tracks')); assert(!_recordCollection[2548].hasOwnProperty('tracks'));
``` ```
After `updateRecords(collection, 1245, "albumTitle", "Riptide")`, `albumTitle` should be `Riptide` After `updateRecords(collection, 1245, "albumTitle", "Riptide")`, `albumTitle` should be the string `Riptide`
```js ```js
assert( assert(

View File

@ -60,43 +60,43 @@ You should have at least four `break` statements
assert(code.match(/break/g).length >= 4); assert(code.match(/break/g).length >= 4);
``` ```
`chainToSwitch("bob")` should be "Marley" `chainToSwitch("bob")` should be the string `Marley`
```js ```js
assert(chainToSwitch('bob') === 'Marley'); assert(chainToSwitch('bob') === 'Marley');
``` ```
`chainToSwitch(42)` should be "The Answer" `chainToSwitch(42)` should be the string `The Answer`
```js ```js
assert(chainToSwitch(42) === 'The Answer'); assert(chainToSwitch(42) === 'The Answer');
``` ```
`chainToSwitch(1)` should be "There is no #1" `chainToSwitch(1)` should be the string `There is no #1`
```js ```js
assert(chainToSwitch(1) === 'There is no #1'); assert(chainToSwitch(1) === 'There is no #1');
``` ```
`chainToSwitch(99)` should be "Missed me by this much!" `chainToSwitch(99)` should be the string `Missed me by this much!`
```js ```js
assert(chainToSwitch(99) === 'Missed me by this much!'); assert(chainToSwitch(99) === 'Missed me by this much!');
``` ```
`chainToSwitch(7)` should be "Ate Nine" `chainToSwitch(7)` should be the string `Ate Nine`
```js ```js
assert(chainToSwitch(7) === 'Ate Nine'); assert(chainToSwitch(7) === 'Ate Nine');
``` ```
`chainToSwitch("John")` should be "" (empty string) `chainToSwitch("John")` should be `""` (empty string)
```js ```js
assert(chainToSwitch('John') === ''); assert(chainToSwitch('John') === '');
``` ```
`chainToSwitch(156)` should be "" (empty string) `chainToSwitch(156)` should be `""` (empty string)
```js ```js
assert(chainToSwitch(156) === ''); assert(chainToSwitch(156) === '');

View File

@ -17,9 +17,11 @@ We can pass values into a function with <dfn>arguments</dfn>. You can use a `ret
function plusThree(num) { function plusThree(num) {
return num + 3; return num + 3;
} }
var answer = plusThree(5); // 8 var answer = plusThree(5);
``` ```
`answer` has the value `8`.
`plusThree` takes an <dfn>argument</dfn> for `num` and returns a value equal to `num + 3`. `plusThree` takes an <dfn>argument</dfn> for `num` and returns a value equal to `num + 3`.
# --instructions-- # --instructions--

View File

@ -22,7 +22,7 @@ function myFun() {
myFun(); myFun();
``` ```
The above outputs "Hello" to the console, returns "World", but `"byebye"` is never output, because the function exits at the `return` statement. The above will display the string `Hello` in the console, and return the string `World`. The string `byebye` will never display in the console, because the function exits at the `return` statement.
# --instructions-- # --instructions--

View File

@ -11,7 +11,7 @@ dashedName: returning-boolean-values-from-functions
You may recall from [Comparison with the Equality Operator](/learn/javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator) that all comparison operators return a boolean `true` or `false` value. You may recall from [Comparison with the Equality Operator](/learn/javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator) that all comparison operators return a boolean `true` or `false` value.
Sometimes people use an if/else statement to do a comparison, like this: Sometimes people use an `if/else` statement to do a comparison, like this:
```js ```js
function isEqual(a,b) { function isEqual(a,b) {

View File

@ -29,32 +29,32 @@ switch(lowercaseLetter) {
# --instructions-- # --instructions--
Write a switch statement which tests `val` and sets `answer` for the following conditions: Write a switch statement which tests `val` and sets `answer` for the following conditions:
`1` - "alpha" `1` - `alpha`
`2` - "beta" `2` - `beta`
`3` - "gamma" `3` - `gamma`
`4` - "delta" `4` - `delta`
# --hints-- # --hints--
`caseInSwitch(1)` should have a value of "alpha" `caseInSwitch(1)` should have a value of the string `alpha`
```js ```js
assert(caseInSwitch(1) === 'alpha'); assert(caseInSwitch(1) === 'alpha');
``` ```
`caseInSwitch(2)` should have a value of "beta" `caseInSwitch(2)` should have a value of the string `beta`
```js ```js
assert(caseInSwitch(2) === 'beta'); assert(caseInSwitch(2) === 'beta');
``` ```
`caseInSwitch(3)` should have a value of "gamma" `caseInSwitch(3)` should have a value of the string `gamma`
```js ```js
assert(caseInSwitch(3) === 'gamma'); assert(caseInSwitch(3) === 'gamma');
``` ```
`caseInSwitch(4)` should have a value of "delta" `caseInSwitch(4)` should have a value of the string `delta`
```js ```js
assert(caseInSwitch(4) === 'delta'); assert(caseInSwitch(4) === 'delta');

View File

@ -16,9 +16,10 @@ JavaScript uses the `-` symbol for subtraction.
**Example** **Example**
```js ```js
myVar = 12 - 6; // assigned 6 myVar = 12 - 6;
``` ```
`myVar` would have the value `6`.
# --instructions-- # --instructions--
Change the `0` so the difference is `12`. Change the `0` so the difference is `12`.

View File

@ -18,17 +18,19 @@ var myObj = {
top: "hat", top: "hat",
bottom: "pants" bottom: "pants"
}; };
myObj.hasOwnProperty("top"); // true myObj.hasOwnProperty("top");
myObj.hasOwnProperty("middle"); // false myObj.hasOwnProperty("middle");
``` ```
The first `hasOwnProperty` returns `true`, while the second returns `false`.
# --instructions-- # --instructions--
Modify the function `checkObj` to test if an object passed to the function (`obj`) contains a specific property (`checkProp`). If the property is found, return that property's value. If not, return `"Not Found"`. Modify the function `checkObj` to test if an object passed to the function (`obj`) contains a specific property (`checkProp`). If the property is found, return that property's value. If not, return `"Not Found"`.
# --hints-- # --hints--
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "gift")` should return `"pony"`. `checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "gift")` should return the string `pony`.
```js ```js
assert( assert(
@ -36,7 +38,7 @@ assert(
); );
``` ```
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "pet")` should return `"kitten"`. `checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "pet")` should return the string `kitten`.
```js ```js
assert( assert(
@ -44,7 +46,7 @@ assert(
); );
``` ```
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "house")` should return `"Not Found"`. `checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "house")` should return the string `Not Found`.
```js ```js
assert( assert(
@ -53,19 +55,19 @@ assert(
); );
``` ```
`checkObj({city: "Seattle"}, "city")` should return `"Seattle"`. `checkObj({city: "Seattle"}, "city")` should return the string `Seattle`.
```js ```js
assert(checkObj({ city: 'Seattle' }, 'city') === 'Seattle'); assert(checkObj({ city: 'Seattle' }, 'city') === 'Seattle');
``` ```
`checkObj({city: "Seattle"}, "district")` should return `"Not Found"`. `checkObj({city: "Seattle"}, "district")` should return the string `Not Found`.
```js ```js
assert(checkObj({ city: 'Seattle' }, 'district') === 'Not Found'); assert(checkObj({ city: 'Seattle' }, 'district') === 'Not Found');
``` ```
`checkObj({pet: "kitten", bed: "sleigh"}, "gift")` should return `"Not Found"`. `checkObj({pet: "kitten", bed: "sleigh"}, "gift")` should return the string `Not Found`.
```js ```js
assert(checkObj({ pet: 'kitten', bed: 'sleigh' }, 'gift') === 'Not Found'); assert(checkObj({ pet: 'kitten', bed: 'sleigh' }, 'gift') === 'Not Found');

View File

@ -18,7 +18,7 @@ var myStr = "Bob";
myStr[0] = "J"; myStr[0] = "J";
``` ```
cannot change the value of `myStr` to "Job", because the contents of `myStr` cannot be altered. Note that this does *not* mean that `myStr` cannot be changed, just that the individual characters of a <dfn>string literal</dfn> cannot be changed. The only way to change `myStr` would be to assign it with a new string, like this: cannot change the value of `myStr` to `Job`, because the contents of `myStr` cannot be altered. Note that this does *not* mean that `myStr` cannot be changed, just that the individual characters of a <dfn>string literal</dfn> cannot be changed. The only way to change `myStr` would be to assign it with a new string, like this:
```js ```js
var myStr = "Bob"; var myStr = "Bob";
@ -31,7 +31,7 @@ Correct the assignment to `myStr` so it contains the string value of `Hello Worl
# --hints-- # --hints--
`myStr` should have a value of `Hello World`. `myStr` should have a value of the string `Hello World`.
```js ```js
assert(myStr === 'Hello World'); assert(myStr === 'Hello World');

View File

@ -9,10 +9,9 @@ dashedName: understanding-boolean-values
# --description-- # --description--
Another data type is the <dfn>Boolean</dfn>. Booleans may only be one of two values: `true` or `false`. They are basically little on-off switches, where `true` is "on" and `false` is "off". These two states are mutually exclusive. Another data type is the <dfn>Boolean</dfn>. Booleans may only be one of two values: `true` or `false`. They are basically little on-off switches, where `true` is on and `false` is off. These two states are mutually exclusive.
**Note** **Note:** Boolean values are never written with quotes. The strings `"true"` and `"false"` are not Boolean and have no special meaning in JavaScript.
Boolean values are never written with quotes. The strings `"true"` and `"false"` are not Boolean and have no special meaning in JavaScript.
# --instructions-- # --instructions--

View File

@ -27,7 +27,8 @@ var thisVariableNameIsSoLong;
# --instructions-- # --instructions--
Modify the existing declarations and assignments so their names use <dfn>camelCase</dfn>. Modify the existing declarations and assignments so their names use <dfn>camelCase</dfn>.
Do not create any new variables. Do not create any new variables.
# --hints-- # --hints--
@ -38,7 +39,7 @@ Do not create any new variables.
assert(typeof studlyCapVar !== 'undefined' && studlyCapVar === 10); assert(typeof studlyCapVar !== 'undefined' && studlyCapVar === 10);
``` ```
`properCamelCase` should be defined and have a value of `"A String"`. `properCamelCase` should be defined and have a value of the string `A String`.
```js ```js
assert( assert(

View File

@ -18,7 +18,7 @@ var sum = 0;
function addSum(num) { function addSum(num) {
sum = sum + num; sum = sum + num;
} }
addSum(3); // sum will be modified but returned value is undefined addSum(3);
``` ```
`addSum` is a function without a `return` statement. The function will change the global `sum` variable but the returned value of the function is `undefined`. `addSum` is a function without a `return` statement. The function will change the global `sum` variable but the returned value of the function is `undefined`.
@ -35,7 +35,7 @@ Create a function `addFive` without any arguments. This function adds 5 to the `
assert(typeof addFive === 'function'); assert(typeof addFive === 'function');
``` ```
Once both functions have ran, the `sum` should be equal to 8. Once both functions have run, the `sum` should be equal to `8`.
```js ```js
assert(sum === 8); assert(sum === 8);

View File

@ -9,7 +9,7 @@ dashedName: understanding-uninitialized-variables
# --description-- # --description--
When JavaScript variables are declared, they have an initial value of `undefined`. If you do a mathematical operation on an `undefined` variable your result will be `NaN` which means <dfn>"Not a Number"</dfn>. If you concatenate a string with an `undefined` variable, you will get a literal <dfn>string</dfn> of `"undefined"`. When JavaScript variables are declared, they have an initial value of `undefined`. If you do a mathematical operation on an `undefined` variable your result will be `NaN` which means <dfn>"Not a Number"</dfn>. If you concatenate a string with an `undefined` variable, you will get a literal <dfn>string</dfn> of `undefined`.
# --instructions-- # --instructions--
@ -29,7 +29,7 @@ assert(typeof a === 'number' && a === 6);
assert(typeof b === 'number' && b === 15); assert(typeof b === 'number' && b === 15);
``` ```
`c` should not contain `undefined` and should have a value of "I am a String!" `c` should not contain `undefined` and should have a value of the string `I am a String!`
```js ```js
assert(!/undefined/.test(c) && c === 'I am a String!'); assert(!/undefined/.test(c) && c === 'I am a String!');

View File

@ -22,15 +22,15 @@ var ourDog = {
}; };
``` ```
Since he's a particularly happy dog, let's change his name to "Happy Camper". Here's how we update his object's name property: `ourDog.name = "Happy Camper";` or `ourDog["name"] = "Happy Camper";` Now when we evaluate `ourDog.name`, instead of getting "Camper", we'll get his new name, "Happy Camper". Since he's a particularly happy dog, let's change his name to the string `Happy Camper`. Here's how we update his object's name property: `ourDog.name = "Happy Camper";` or `ourDog["name"] = "Happy Camper";` Now when we evaluate `ourDog.name`, instead of getting `Camper`, we'll get his new name, `Happy Camper`.
# --instructions-- # --instructions--
Update the `myDog` object's name property. Let's change her name from "Coder" to "Happy Coder". You can use either dot or bracket notation. Update the `myDog` object's name property. Let's change her name from `Coder` to `Happy Coder`. You can use either dot or bracket notation.
# --hints-- # --hints--
You should update `myDog`'s `"name"` property to equal "Happy Coder". You should update `myDog`'s `name` property to equal the string `Happy Coder`.
```js ```js
assert(/happy coder/gi.test(myDog.name)); assert(/happy coder/gi.test(myDog.name));

View File

@ -9,19 +9,21 @@ dashedName: use-bracket-notation-to-find-the-first-character-in-a-string
# --description-- # --description--
<dfn>Bracket notation</dfn> is a way to get a character at a specific `index` within a string. <dfn>Bracket notation</dfn> is a way to get a character at a specific index within a string.
Most modern programming languages, like JavaScript, don't start counting at 1 like humans do. They start at 0. This is referred to as <dfn>Zero-based</dfn> indexing. Most modern programming languages, like JavaScript, don't start counting at 1 like humans do. They start at 0. This is referred to as <dfn>Zero-based</dfn> indexing.
For example, the character at index 0 in the word "Charles" is "C". So if `var firstName = "Charles"`, you can get the value of the first letter of the string by using `firstName[0]`. For example, the character at index 0 in the word `Charles` is `C`. So if `var firstName = "Charles"`, you can get the value of the first letter of the string by using `firstName[0]`.
Example: Example:
```js ```js
var firstName = "Charles"; var firstName = "Charles";
var firstLetter = firstName[0]; // firstLetter is "C" var firstLetter = firstName[0];
``` ```
`firstLetter` would have a value of the string `C`.
# --instructions-- # --instructions--
Use bracket notation to find the first character in the `lastName` variable and assign it to `firstLetterOfLastName`. Use bracket notation to find the first character in the `lastName` variable and assign it to `firstLetterOfLastName`.

View File

@ -17,9 +17,11 @@ Example:
```js ```js
var firstName = "Charles"; var firstName = "Charles";
var lastLetter = firstName[firstName.length - 1]; // lastLetter is "s" var lastLetter = firstName[firstName.length - 1];
``` ```
`lastLetter` would have a value of the string `s`.
# --instructions-- # --instructions--
Use <dfn>bracket notation</dfn> to find the last character in the `lastName` variable. Use <dfn>bracket notation</dfn> to find the last character in the `lastName` variable.
@ -28,7 +30,7 @@ Use <dfn>bracket notation</dfn> to find the last character in the `lastName` var
# --hints-- # --hints--
`lastLetterOfLastName` should be "e". `lastLetterOfLastName` should be the letter `e`.
```js ```js
assert(lastLetterOfLastName === 'e'); assert(lastLetterOfLastName === 'e');

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