feat(curriculum): introduce let and const earlier (#43133)

* fix: move "Explore Differences Between..." to basic JS, update seed and tests

* fix: resequence "Declare String Variables"

* fix: move "Declare a Read-Only Variable..." to basic JS, update seed and tests

* fix: revert changes to non-English "Explore Differences Between..." test text

* fix: revert test strings, solutions, and seeds for non-English challenges

* fix: update "Declare String Variables" description

* fix: sync quotation marks in description and seed

* fix: modify note in "Declare a Read-Only..." challenge

* fix: update operator and compound assignment challenges

* fix: update string challenges

* fix: update array and array method challenges

* fix: update function and scope challenges, resequence slightly

* fix: "Word Blanks" solution

* fix: add spacing to seed

* fix: concatenating += challenge spacing

* fix: appending variables to strings spacing

* fix: find the length of a string spacing

* fix: removed instances of removedFromMyArray = 0

* fix: switch challenges

* fix: function argument and param spacing

* fix: update counting cards, object challenges, and record collection

* fix: finish rest of Basic JS section

* fix: introducing else statements solution

* fix: update spacing and wording

* fix: update wording for const challenge

* fix: update functional programming challenges

* fix: intermediate algorithms and cert challenges

* fix: revert some spacing and remove comments for fp challenge solutions

* feat: add notes with links to moved let and const challenges in first two es6 challenges

* fix: update es6 intro text

* Update curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/concatenating-strings-with-the-plus-equals-operator.md

Co-authored-by: Shaun Hamilton <shauhami020@gmail.com>

* Update curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/finding-a-remainder-in-javascript.md

Co-authored-by: Shaun Hamilton <shauhami020@gmail.com>

* Update curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/global-scope-and-functions.md

Co-authored-by: Shaun Hamilton <shauhami020@gmail.com>

* Update curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-through-an-array-with-a-for-loop.md

Co-authored-by: Shaun Hamilton <shauhami020@gmail.com>

* Update curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-through-an-array-with-a-for-loop.md

Co-authored-by: Shaun Hamilton <shauhami020@gmail.com>

* Update curriculum/challenges/english/02-javascript-algorithms-and-data-structures/functional-programming/implement-map-on-a-prototype.md

Co-authored-by: Shaun Hamilton <shauhami020@gmail.com>

* Update curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/declare-a-read-only-variable-with-the-const-keyword.md

Co-authored-by: Shaun Hamilton <shauhami020@gmail.com>

* fix: concatenating strings with plus operator seed

* fix: add comments back to Declare a Read-Only Variable... seed

* feat: add es6 to basic javascript redirect tests for let and const challenges

* fix: revert "Concatenating Strings with Plus Operator" seed

* fix: move test file to cypress/integration/learn/redirects, separate redirect tests

Co-authored-by: Shaun Hamilton <shauhami020@gmail.com>
pull/44002/head
Kristofer Koishigawa 2021-10-26 01:55:58 +09:00 committed by GitHub
parent 71b555ab16
commit bcc9beff1f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
134 changed files with 888 additions and 882 deletions

View File

@ -122,7 +122,7 @@
"intro": [
"ECMAScript, or ES, is a standardized version of JavaScript. Because all major browsers follow this specification, the terms ECMAScript and JavaScript are interchangeable.",
"Most of the JavaScript you've learned up to this point was in ES5 (ECMAScript 5), which was finalized in 2009. While you can still write programs in ES5, JavaScript is constantly evolving, and new features are released every year.",
"ES6, released in 2015, added many powerful new features to the language. In this course, you'll learn these new features, including <code>let</code> and <code>const</code>, arrow functions, classes, promises, and modules."
"ES6, released in 2015, added many powerful new features to the language. In this course, you'll learn these new features, including arrow functions, destructuring, classes, promises, and modules."
]
},
"regular-expressions": {

View File

@ -29,6 +29,10 @@
"56533eb9ac21ba0edf2244a9",
"Initializing Variables with the Assignment Operator"
],
[
"bd7123c9c444eddfaeb5bdef",
"Declare String Variables"
],
[
"56533eb9ac21ba0edf2244aa",
"Understanding Uninitialized Variables"
@ -37,6 +41,14 @@
"56533eb9ac21ba0edf2244ab",
"Understanding Case Sensitivity in Variables"
],
[
"587d7b87367417b2b2512b3f",
"Explore Differences Between the var and let Keywords"
],
[
"587d7b87367417b2b2512b41",
"Declare a Read-Only Variable with the const Keyword"
],
[
"cf1111c1c11feddfaeb3bdef",
"Add Two Numbers with JavaScript"
@ -93,10 +105,6 @@
"56533eb9ac21ba0edf2244b2",
"Compound Assignment With Augmented Division"
],
[
"bd7123c9c444eddfaeb5bdef",
"Declare String Variables"
],
[
"56533eb9ac21ba0edf2244b5",
"Escaping Literal Quotes in Strings"
@ -201,6 +209,10 @@
"56533eb9ac21ba0edf2244bd",
"Passing Values to Functions with Arguments"
],
[
"56533eb9ac21ba0edf2244c2",
"Return a Value from a Function with Return"
],
[
"56533eb9ac21ba0edf2244be",
"Global Scope and Functions"
@ -213,10 +225,6 @@
"56533eb9ac21ba0edf2244c0",
"Global vs. Local Scope in Functions"
],
[
"56533eb9ac21ba0edf2244c2",
"Return a Value from a Function with Return"
],
[
"598e8944f009e646fc236146",
"Understanding Undefined Value returned from a Function"

View File

@ -9,18 +9,10 @@
"superBlock": "javascript-algorithms-and-data-structures",
"superOrder": 2,
"challengeOrder": [
[
"587d7b87367417b2b2512b3f",
"Explore Differences Between the var and let Keywords"
],
[
"587d7b87367417b2b2512b40",
"Compare Scopes of the var and let Keywords"
],
[
"587d7b87367417b2b2512b41",
"Declare a Read-Only Variable with the const Keyword"
],
[
"587d7b87367417b2b2512b42",
"Mutate an Array Declared with const"

View File

@ -18,9 +18,9 @@ Array indexes are written in the same bracket notation that strings use, except
**Example**
```js
var array = [50,60,70];
const array = [50, 60, 70];
array[0];
var data = array[1];
const data = array[1];
```
`array[0]` is now `50`, and `data` has the value `60`.
@ -76,7 +76,7 @@ if(typeof myArray !== "undefined" && typeof myData !== "undefined"){(function(y,
## --seed-contents--
```js
var myArray = [50,60,70];
const myArray = [50, 60, 70];
```
@ -84,6 +84,6 @@ var myArray = [50,60,70];
# --solutions--
```js
var myArray = [50,60,70];
var myData = myArray[0];
const myArray = [50, 60, 70];
const myData = myArray[0];
```

View File

@ -14,12 +14,13 @@ One way to think of a <dfn>multi-dimensional</dfn> array, is as an *array of arr
**Example**
```js
var arr = [
[1,2,3],
[4,5,6],
[7,8,9],
[[10,11,12], 13, 14]
const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[[10, 11, 12], 13, 14]
];
arr[3];
arr[3][0];
arr[3][0][1];
@ -58,14 +59,19 @@ if(typeof myArray !== "undefined"){(function(){return "myData: " + myData + " my
## --seed-contents--
```js
var myArray = [[1,2,3], [4,5,6], [7,8,9], [[10,11,12], 13, 14]];
const myArray = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[[10, 11, 12], 13, 14],
];
var myData = myArray[0][0];
const myData = myArray[0][0];
```
# --solutions--
```js
var myArray = [[1,2,3],[4,5,6], [7,8,9], [[10,11,12], 13, 14]];
var myData = myArray[2][1];
const myArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [[10, 11, 12], 13, 14]];
const myData = myArray[2][1];
```

View File

@ -14,7 +14,7 @@ As we have seen in earlier examples, objects can contain both nested objects and
Here is an example of how to access a nested array:
```js
var ourPets = [
const ourPets = [
{
animalType: "cat",
names: [
@ -32,6 +32,7 @@ var ourPets = [
]
}
];
ourPets[0].names[1];
ourPets[1].names[0];
```
@ -72,7 +73,7 @@ assert(/=\s*myPlants\[1\].list\[1\]/.test(code));
## --seed-contents--
```js
var myPlants = [
const myPlants = [
{
type: "flowers",
list: [
@ -91,13 +92,13 @@ var myPlants = [
}
];
var secondTree = "";
const secondTree = "";
```
# --solutions--
```js
var myPlants = [
const myPlants = [
{
type: "flowers",
list: [
@ -116,5 +117,5 @@ var myPlants = [
}
];
var secondTree = myPlants[1].list[1];
const secondTree = myPlants[1].list[1];
```

View File

@ -14,7 +14,7 @@ The sub-properties of objects can be accessed by chaining together the dot or br
Here is a nested object:
```js
var ourStorage = {
const ourStorage = {
"desk": {
"drawer": "stapler"
},
@ -26,6 +26,7 @@ var ourStorage = {
"bottom drawer": "soda"
}
};
ourStorage.cabinet["top drawer"].folder2;
ourStorage.desk.drawer;
```
@ -66,7 +67,7 @@ assert(/=\s*myStorage\.car\.inside\[\s*("|')glove box\1\s*\]/g.test(code));
## --seed-contents--
```js
var myStorage = {
const myStorage = {
"car": {
"inside": {
"glove box": "maps",
@ -78,13 +79,13 @@ var myStorage = {
}
};
var gloveBoxContents = undefined;
const gloveBoxContents = undefined;
```
# --solutions--
```js
var myStorage = {
const myStorage = {
"car":{
"inside":{
"glove box":"maps",
@ -95,5 +96,5 @@ var myStorage = {
}
}
};
var gloveBoxContents = myStorage.car.inside["glove box"];
const gloveBoxContents = myStorage.car.inside["glove box"];
```

View File

@ -16,11 +16,12 @@ However, you can still use bracket notation on object properties without spaces.
Here is a sample of using bracket notation to read an object's property:
```js
var myObj = {
const myObj = {
"Space Name": "Kirk",
"More Space": "Spock",
"NoSpace": "USS Enterprise"
};
myObj["Space Name"];
myObj['More Space'];
myObj["NoSpace"];
@ -78,26 +79,25 @@ assert(code.match(/testObj\s*?\[('|")[^'"]+\1\]/g).length > 1);
```js
// Setup
var testObj = {
const testObj = {
"an entree": "hamburger",
"my side": "veggies",
"the drink": "water"
};
// Only change code below this line
var entreeValue = testObj; // Change this line
var drinkValue = testObj; // Change this line
const entreeValue = testObj; // Change this line
const drinkValue = testObj; // Change this line
```
# --solutions--
```js
var testObj = {
const testObj = {
"an entree": "hamburger",
"my side": "veggies",
"the drink": "water"
};
var entreeValue = testObj["an entree"];
var drinkValue = testObj['the drink'];
const entreeValue = testObj["an entree"];
const drinkValue = testObj['the drink'];
```

View File

@ -16,15 +16,17 @@ Dot notation is what you use when you know the name of the property you're tryin
Here is a sample of using dot notation (`.`) to read an object's property:
```js
var myObj = {
const myObj = {
prop1: "val1",
prop2: "val2"
};
var prop1val = myObj.prop1;
var prop2val = myObj.prop2;
const prop1val = myObj.prop1;
const prop2val = myObj.prop2;
```
`prop1val` would have a value of the string `val1`, and `prop2val` would have a value of the string `val2`.
# --instructions--
Read in the property values of `testObj` using dot notation. Set the variable `hatValue` equal to the object's property `hat` and set the variable `shirtValue` equal to the object's property `shirt`.
@ -73,27 +75,26 @@ assert(code.match(/testObj\.\w+/g).length > 1);
```js
// Setup
var testObj = {
const testObj = {
"hat": "ballcap",
"shirt": "jersey",
"shoes": "cleats"
};
// Only change code below this line
var hatValue = testObj; // Change this line
var shirtValue = testObj; // Change this line
const hatValue = testObj; // Change this line
const shirtValue = testObj; // Change this line
```
# --solutions--
```js
var testObj = {
const testObj = {
"hat": "ballcap",
"shirt": "jersey",
"shoes": "cleats"
};
var hatValue = testObj.hat;
var shirtValue = testObj.shirt;
const hatValue = testObj.hat;
const shirtValue = testObj.shirt;
```

View File

@ -14,11 +14,14 @@ Another use of bracket notation on objects is to access a property which is stor
Here is an example of using a variable to access a property:
```js
var dogs = {
Fido: "Mutt", Hunter: "Doberman", Snoopie: "Beagle"
const dogs = {
Fido: "Mutt",
Hunter: "Doberman",
Snoopie: "Beagle"
};
var myDog = "Hunter";
var myBreed = dogs[myDog];
const myDog = "Hunter";
const myBreed = dogs[myDog];
console.log(myBreed);
```
@ -27,14 +30,16 @@ 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:
```js
var someObj = {
const someObj = {
propName: "John"
};
function propPrefix(str) {
var s = "prop";
const s = "prop";
return s + str;
}
var someProp = propPrefix("Name");
const someProp = propPrefix("Name");
console.log(someObj[someProp]);
```
@ -96,26 +101,25 @@ if(typeof player !== "undefined"){(function(v){return v;})(player);}
```js
// Setup
var testObj = {
const testObj = {
12: "Namath",
16: "Montana",
19: "Unitas"
};
// Only change code below this line
var playerNumber; // Change this line
var player = testObj; // Change this line
const playerNumber; // Change this line
const player = testObj; // Change this line
```
# --solutions--
```js
var testObj = {
const testObj = {
12: "Namath",
16: "Montana",
19: "Unitas"
};
var playerNumber = 16;
var player = testObj[playerNumber];
const playerNumber = 16;
const player = testObj[playerNumber];
```

View File

@ -28,7 +28,7 @@ Now when we evaluate `ourDog.bark`, we'll get his bark, `bow-wow`.
Example:
```js
var ourDog = {
const ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
@ -67,7 +67,7 @@ assert(!/bark[^\n]:/.test(code));
## --seed-contents--
```js
var myDog = {
const myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
@ -80,7 +80,7 @@ var myDog = {
# --solutions--
```js
var myDog = {
const myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,

View File

@ -18,7 +18,7 @@ JavaScript uses the `+` symbol as an addition operator when placed between two n
**Example:**
```js
myVar = 5 + 10;
const myVar = 5 + 10;
```
`myVar` now has the value `15`.
@ -52,11 +52,11 @@ assert(/\+/.test(code));
## --seed-contents--
```js
var sum = 10 + 0;
const sum = 10 + 0;
```
# --solutions--
```js
var sum = 10 + 10;
const sum = 10 + 10;
```

View File

@ -92,7 +92,7 @@ assert(code.match(/break/g).length > 2);
```js
function switchOfStuff(val) {
var answer = "";
let answer = "";
// Only change code below this line
@ -108,7 +108,7 @@ switchOfStuff(1);
```js
function switchOfStuff(val) {
var answer = "";
let answer = "";
switch(val) {
case "a":

View File

@ -14,8 +14,8 @@ Just as we can build a string over multiple lines out of string <dfn>literals</d
Example:
```js
var anAdjective = "awesome!";
var ourStr = "freeCodeCamp is ";
const anAdjective = "awesome!";
let ourStr = "freeCodeCamp is ";
ourStr += anAdjective;
```
@ -64,15 +64,14 @@ assert(code.match(/myStr\s*\+=\s*someAdjective\s*/).length > 0);
```js
// Change code below this line
var someAdjective;
var myStr = "Learning to code is ";
const someAdjective = "";
let myStr = "Learning to code is ";
```
# --solutions--
```js
var someAdjective = "neat";
var myStr = "Learning to code is ";
const someAdjective = "neat";
let myStr = "Learning to code is ";
myStr += someAdjective;
```

View File

@ -17,7 +17,7 @@ Assume we have pre-defined a function `sum` which adds two numbers together, the
ourSum = sum(5, 12);
```
will call `sum` function, which returns a value of `17` and assigns it to `ourSum` variable.
will call the `sum` function, which returns a value of `17` and assigns it to the `ourSum` variable.
# --instructions--
@ -49,13 +49,14 @@ assert(/processed\s*=\s*processArg\(\s*7\s*\)/.test(code));
```js
// Setup
var processed = 0;
let processed = 0;
function processArg(num) {
return (num + 3) / 5;
}
// Only change code below this line
```
# --solutions--

View File

@ -18,7 +18,7 @@ Objects are useful for storing data in a structured way, and can represent real
Here's a sample cat object:
```js
var cat = {
const cat = {
"name": "Whiskers",
"legs": 4,
"tails": 1,
@ -29,7 +29,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:
```js
var anotherObject = {
const anotherObject = {
make: "Ford",
5: "five",
"model": "focus"
@ -139,18 +139,18 @@ assert(
## --seed-contents--
```js
var myDog = {
// Only change code below this line
const myDog = {
// Only change code below this line
// Only change code above this line
// Only change code above this line
};
```
# --solutions--
```js
var myDog = {
const myDog = {
"name": "Camper",
"legs": 4,
"tails": 1,

View File

@ -16,7 +16,7 @@ The most basic operator is the equality operator `==`. The equality operator com
```js
function equalityTest(myVal) {
if (myVal == 10) {
return "Equal";
return "Equal";
}
return "Not Equal";
}

View File

@ -25,7 +25,7 @@ In order, these expressions would evaluate to `true`, `false`, `false`, `false`,
# --instructions--
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`
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--

View File

@ -26,7 +26,7 @@ In the second example, `3` is a `Number` type and `'3'` is a `String` type.
# --instructions--
Use the strict equality operator in the `if` statement so the function will return the string `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--

View File

@ -20,7 +20,7 @@ to add `5` to `myVar`. Since this is such a common pattern, there are operators
One such operator is the `+=` operator.
```js
var myVar = 1;
let myVar = 1;
myVar += 5;
console.log(myVar);
```
@ -61,9 +61,9 @@ You should not modify the code above the specified comment.
```js
assert(
/var a = 3;/.test(code) &&
/var b = 17;/.test(code) &&
/var c = 12;/.test(code)
/let a = 3;/.test(code) &&
/let b = 17;/.test(code) &&
/let c = 12;/.test(code)
);
```
@ -78,9 +78,9 @@ assert(
## --seed-contents--
```js
var a = 3;
var b = 17;
var c = 12;
let a = 3;
let b = 17;
let c = 12;
// Only change code below this line
a = a + 12;
@ -91,9 +91,9 @@ c = c + 7;
# --solutions--
```js
var a = 3;
var b = 17;
var c = 12;
let a = 3;
let b = 17;
let c = 12;
a += 12;
b += 9;

View File

@ -55,9 +55,9 @@ You should not modify the code above the specified comment.
```js
assert(
/var a = 48;/.test(code) &&
/var b = 108;/.test(code) &&
/var c = 33;/.test(code)
/let a = 48;/.test(code) &&
/let b = 108;/.test(code) &&
/let c = 33;/.test(code)
);
```
@ -72,9 +72,9 @@ assert(
## --seed-contents--
```js
var a = 48;
var b = 108;
var c = 33;
let a = 48;
let b = 108;
let c = 33;
// Only change code below this line
a = a / 12;
@ -85,9 +85,9 @@ c = c / 11;
# --solutions--
```js
var a = 48;
var b = 108;
var c = 33;
let a = 48;
let b = 108;
let c = 33;
a /= 12;
b /= 4;

View File

@ -55,9 +55,9 @@ You should not modify the code above the specified comment.
```js
assert(
/var a = 5;/.test(code) &&
/var b = 12;/.test(code) &&
/var c = 4\.6;/.test(code)
/let a = 5;/.test(code) &&
/let b = 12;/.test(code) &&
/let c = 4\.6;/.test(code)
);
```
@ -72,9 +72,9 @@ assert(
## --seed-contents--
```js
var a = 5;
var b = 12;
var c = 4.6;
let a = 5;
let b = 12;
let c = 4.6;
// Only change code below this line
a = a * 5;
@ -85,9 +85,9 @@ c = c * 10;
# --solutions--
```js
var a = 5;
var b = 12;
var c = 4.6;
let a = 5;
let b = 12;
let c = 4.6;
a *= 5;
b *= 3;

View File

@ -55,7 +55,7 @@ You should not modify the code above the specified comment.
```js
assert(
/var a = 11;/.test(code) && /var b = 9;/.test(code) && /var c = 3;/.test(code)
/let a = 11;/.test(code) && /let b = 9;/.test(code) && /let c = 3;/.test(code)
);
```
@ -70,9 +70,9 @@ assert(
## --seed-contents--
```js
var a = 11;
var b = 9;
var c = 3;
let a = 11;
let b = 9;
let c = 3;
// Only change code below this line
a = a - 6;
@ -83,9 +83,9 @@ c = c - 1;
# --solutions--
```js
var a = 11;
var b = 9;
var c = 3;
let a = 11;
let b = 9;
let c = 3;
a -= 6;
b -= 15;

View File

@ -22,7 +22,7 @@ In JavaScript, when the `+` operator is used with a `String` value, it is called
Example:
```js
var ourStr = "I come first. " + "I come second.";
const ourStr = "I come first. " + "I come second.";
```
The string `I come first. I come second.` would be displayed in the console.
@ -44,10 +44,10 @@ You should use the `+` operator to build `myStr`.
assert(code.match(/(["']).*\1\s*\+\s*(["']).*\2/g));
```
`myStr` should be created using the `var` keyword.
`myStr` should be created using the `const` keyword.
```js
assert(/var\s+myStr/.test(code));
assert(/const\s+myStr/.test(code));
```
You should assign the result to the `myStr` variable.
@ -73,11 +73,11 @@ assert(/myStr\s*=/.test(code));
## --seed-contents--
```js
var myStr; // Change this line
const myStr = ""; // Change this line
```
# --solutions--
```js
var myStr = "This is the start. " + "This is the end.";
const myStr = "This is the start. " + "This is the end.";
```

View File

@ -16,7 +16,7 @@ We can also use the `+=` operator to <dfn>concatenate</dfn> a string onto the en
Example:
```js
var ourStr = "I come first. ";
let ourStr = "I come first. ";
ourStr += "I come second.";
```
@ -57,14 +57,12 @@ assert(code.match(/myStr\s*\+=\s*(["']).*\1/g));
## --seed-contents--
```js
// Only change code below this line
var myStr;
let myStr;
```
# --solutions--
```js
var myStr = "This is the first sentence. ";
let myStr = "This is the first sentence. ";
myStr += "This is the second sentence.";
```

View File

@ -14,8 +14,8 @@ Sometimes you will need to build a string, [Mad Libs](https://en.wikipedia.org/w
Example:
```js
var ourName = "freeCodeCamp";
var ourStr = "Hello, our name is " + ourName + ", how are you?";
const ourName = "freeCodeCamp";
const ourStr = "Hello, our name is " + ourName + ", how are you?";
```
`ourStr` would have a value of the string `Hello, our name is freeCodeCamp, how are you?`.
@ -63,13 +63,13 @@ assert(code.match(/["']\s*\+\s*myName\s*\+\s*["']/g).length > 0);
```js
// Only change code below this line
var myName;
var myStr;
const myName = "";
const myStr = "";
```
# --solutions--
```js
var myName = "Bob";
var myStr = "My name is " + myName + " and I am well!";
const myName = "Bob";
const myStr = "My name is " + myName + " and I am well!";
```

View File

@ -16,13 +16,14 @@ In order to decrement by two each iteration, we'll need to change our initializa
We'll start at `i = 10` and loop while `i > 0`. We'll decrement `i` by 2 each loop with `i -= 2`.
```js
var ourArray = [];
for (var i = 10; i > 0; i -= 2) {
const ourArray = [];
for (let i = 10; i > 0; i -= 2) {
ourArray.push(i);
}
```
`ourArray` will now contain `[10,8,6,4,2]`. Let's change our initialization and final expression so we can count backwards by twos to create an array of descending odd numbers.
`ourArray` will now contain `[10, 8, 6, 4, 2]`. Let's change our initialization and final expression so we can count backwards by twos to create an array of descending odd numbers.
# --instructions--
@ -42,7 +43,7 @@ You should be using the array method `push`.
assert(code.match(/myArray.push/));
```
`myArray` should equal `[9,7,5,3,1]`.
`myArray` should equal `[9, 7, 5, 3, 1]`.
```js
assert.deepEqual(myArray, [9, 7, 5, 3, 1]);
@ -60,16 +61,17 @@ if(typeof myArray !== "undefined"){(function(){return myArray;})();}
```js
// Setup
var myArray = [];
const myArray = [];
// Only change code below this line
```
# --solutions--
```js
var myArray = [];
for (var i = 9; i > 0; i -= 2) {
const myArray = [];
for (let i = 9; i > 0; i -= 2) {
myArray.push(i);
}
```

View File

@ -160,7 +160,7 @@ assert(
## --seed-contents--
```js
var count = 0;
let count = 0;
function cc(card) {
// Only change code below this line
@ -176,7 +176,7 @@ cc(2); cc(3); cc(7); cc('K'); cc('A');
# --solutions--
```js
var count = 0;
let count = 0;
function cc(card) {
switch(card) {
case 2:

View File

@ -42,13 +42,14 @@ assert(myDecimal % 1 != 0);
## --seed-contents--
```js
var ourDecimal = 5.7;
const ourDecimal = 5.7;
// Only change code below this line
```
# --solutions--
```js
var myDecimal = 9.9;
const myDecimal = 9.9;
```

View File

@ -0,0 +1,91 @@
---
id: 587d7b87367417b2b2512b41
title: Declare a Read-Only Variable with the const Keyword
challengeType: 1
forumTopicId: 301201
dashedName: declare-a-read-only-variable-with-the-const-keyword
---
# --description--
The keyword `let` is not the only new way to declare variables. In ES6, you can also declare variables using the `const` keyword.
`const` has all the awesome features that `let` has, with the added bonus that variables declared using `const` are read-only. They are a constant value, which means that once a variable is assigned with `const`, it cannot be reassigned:
```js
const FAV_PET = "Cats";
FAV_PET = "Dogs";
```
The console will display an error due to reassigning the value of `FAV_PET`.
You should always name variables you don't want to reassign using the `const` keyword. This helps when you accidentally attempt to reassign a variable that is meant to stay constant.
A common practice when naming constants is to use all uppercase letters, with words separated by an underscore.
**Note:** It is common for developers to use uppercase variable identifiers for immutable values and lowercase or camelCase for mutable values (objects and arrays). You will learn more about objects, arrays, and immutable and mutable values in later challenges. Also in later challenges, you will see examples of uppercase, lowercase, or camelCase variable identifiers.
# --instructions--
Change the code so that all variables are declared using `let` or `const`. Use `let` when you want the variable to change, and `const` when you want the variable to remain constant. Also, rename variables declared with `const` to conform to common practices, meaning constants should be in all caps.
# --hints--
`var` should not exist in your code.
```js
(getUserInput) => assert(!getUserInput('index').match(/var/g));
```
You should change `fCC` to all uppercase.
```js
(getUserInput) => {
assert(getUserInput('index').match(/(FCC)/));
assert(!getUserInput('index').match(/fCC/));
}
```
`FCC` should be a constant variable declared with `const`.
```js
assert.equal(FCC, 'freeCodeCamp');
assert.match(code, /const\s+FCC/);
```
`fact` should be declared with `let`.
```js
(getUserInput) => assert(getUserInput('index').match(/(let fact)/g));
```
`console.log` should be changed to print the `FCC` and `fact` variables.
```js
(getUserInput) =>
assert(getUserInput('index').match(/console\.log\(\s*FCC\s*\,\s*fact\s*\)\s*;?/g));
```
# --seed--
## --seed-contents--
```js
// Only change code below this line
var fCC = "freeCodeCamp";
var fact = "is cool!";
// Only change code above this line
fact = "is awesome!";
console.log(fCC, fact);
```
# --solutions--
```js
const FCC = "freeCodeCamp";
let fact = "is cool!";
fact = "is awesome!";
console.log(FCC, fact);
```

View File

@ -9,13 +9,19 @@ dashedName: declare-string-variables
# --description--
Previously we have used the code
Previously you used the following code to declare a variable:
```js
var myName;
```
But you can also declare a string variable like this:
```js
var myName = "your name";
```
`"your name"` is called a <dfn>string</dfn> <dfn>literal</dfn>. It is a string because it is a series of zero or more characters enclosed in single or double quotes.
`"your name"` is called a <dfn>string</dfn> <dfn>literal</dfn>. A string literal, or string, is a series of zero or more characters enclosed in single or double quotes.
# --instructions--

View File

@ -39,7 +39,7 @@ assert(myVar === 10);
```js
assert(
/var\s*myVar\s*=\s*11;\s*\/*.*\s*([-]{2}\s*myVar|myVar\s*[-]{2});/.test(code)
/let\s*myVar\s*=\s*11;\s*\/*.*\s*([-]{2}\s*myVar|myVar\s*[-]{2});/.test(code)
);
```
@ -52,7 +52,7 @@ assert(/[-]{2}\s*myVar|myVar\s*[-]{2}/.test(code));
You should not change code above the specified comment.
```js
assert(/var myVar = 11;/.test(code));
assert(/let myVar = 11;/.test(code));
```
# --seed--
@ -66,7 +66,7 @@ assert(/var myVar = 11;/.test(code));
## --seed-contents--
```js
var myVar = 11;
let myVar = 11;
// Only change code below this line
myVar = myVar - 1;
@ -75,6 +75,6 @@ myVar = myVar - 1;
# --solutions--
```js
var myVar = 11;
let myVar = 11;
myVar--;
```

View File

@ -18,7 +18,7 @@ delete ourDog.bark;
Example:
```js
var ourDog = {
const ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
@ -70,7 +70,7 @@ assert(code.match(/"tails": 1/g).length > 0);
```js
// Setup
var myDog = {
const myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
@ -79,12 +79,13 @@ var myDog = {
};
// Only change code below this line
```
# --solutions--
```js
var myDog = {
const myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,

View File

@ -46,11 +46,11 @@ assert(code.match(/quotient/g).length === 1);
## --seed-contents--
```js
var quotient = 0.0 / 2.0; // Change this line
const quotient = 0.0 / 2.0; // Change this line
```
# --solutions--
```js
var quotient = 4.4 / 2.0;
const quotient = 4.4 / 2.0;
```

View File

@ -16,7 +16,7 @@ JavaScript uses the `/` symbol for division.
**Example**
```js
myVar = 16 / 2;
const myVar = 16 / 2;
```
`myVar` now has the value `8`.
@ -49,11 +49,11 @@ assert(/\d+\s*\/\s*\d+/.test(code));
## --seed-contents--
```js
var quotient = 66 / 0;
const quotient = 66 / 0;
```
# --solutions--
```js
var quotient = 66 / 33;
const quotient = 66 / 33;
```

View File

@ -89,11 +89,11 @@ console.log('myStr:\n' + myStr);}})();
## --seed-contents--
```js
var myStr; // Change this line
const myStr = ""; // Change this line
```
# --solutions--
```js
var myStr = "FirstLine\n\t\\SecondLine\nThirdLine";
const myStr = "FirstLine\n\t\\SecondLine\nThirdLine";
```

View File

@ -14,7 +14,7 @@ When you are defining a string you must start and end with a single or double qu
In JavaScript, you can <dfn>escape</dfn> a quote from considering it as an end of string quote by placing a <dfn>backslash</dfn> (`\`) in front of the quote.
```js
var sampleStr = "Alan said, \"Peter is learning JavaScript\".";
const sampleStr = "Alan said, \"Peter is learning JavaScript\".";
```
This signals to JavaScript that the following quote is not the end of the string, but should instead appear inside the string. So if you were to print this to the console, you would get:
@ -62,11 +62,11 @@ assert(/I am a "double quoted" string inside "double quotes(\."|"\.)$/.test(mySt
## --seed-contents--
```js
var myStr = ""; // Change this line
const myStr = ""; // Change this line
```
# --solutions--
```js
var myStr = "I am a \"double quoted\" string inside \"double quotes\".";
const myStr = "I am a \"double quoted\" string inside \"double quotes\".";
```

View File

@ -0,0 +1,74 @@
---
id: 587d7b87367417b2b2512b3f
title: Explore Differences Between the var and let Keywords
challengeType: 1
forumTopicId: 301202
dashedName: explore-differences-between-the-var-and-let-keywords
---
# --description--
One of the biggest problems with declaring variables with the `var` keyword is that you can easily overwrite variable declarations:
```js
var camper = "James";
var camper = "David";
console.log(camper);
```
In the code above, the `camper` variable is originally declared as `James`, and is then overridden to be `David`. The console then displays the string `David`.
In a small application, you might not run into this type of problem. But as your codebase becomes larger, you might accidentally overwrite a variable that you did not intend to. Because this behavior does not throw an error, searching for and fixing bugs becomes more difficult.
A keyword called `let` was introduced in ES6, a major update to JavaScript, to solve this potential issue with the `var` keyword. You'll learn about other ES6 features in later challenges.
If you replace `var` with `let` in the code above, it results in an error:
```js
let camper = "James";
let camper = "David";
```
The error can be seen in your browser console.
So unlike `var`, when you use `let`, a variable with the same name can only be declared once.
# --instructions--
Update the code so it only uses the `let` keyword.
# --hints--
`var` should not exist in the code.
```js
(getUserInput) => assert(!getUserInput('index').match(/var/g));
```
`catName` should be the string `Oliver`.
```js
assert(catName === 'Oliver');
```
`catSound` should be the string `Meow!`
```js
assert(catSound === 'Meow!');
```
# --seed--
## --seed-contents--
```js
var catName = "Oliver";
var catSound = "Meow!";
```
# --solutions--
```js
let catName = "Oliver";
let catSound = "Meow!";
```

View File

@ -17,7 +17,7 @@ console.log("Alan Peter".length);
The value `10` would be displayed in the console.
For example, if we created a variable `var firstName = "Ada"`, we could find out how long the string `Ada` is by using the `firstName.length` property.
For example, if we created a variable `const firstName = "Ada"`, we could find out how long the string `Ada` is by using the `firstName.length` property.
# --instructions--
@ -29,8 +29,8 @@ You should not change the variable declarations in the `// Setup` section.
```js
assert(
code.match(/var lastNameLength = 0;/) &&
code.match(/var lastName = "Lovelace";/)
code.match(/let lastNameLength = 0;/) &&
code.match(/const lastName = "Lovelace";/)
);
```
@ -52,18 +52,17 @@ assert(code.match(/=\s*lastName\.length/g) && !code.match(/lastName\s*=\s*8/));
```js
// Setup
var lastNameLength = 0;
var lastName = "Lovelace";
let lastNameLength = 0;
const lastName = "Lovelace";
// Only change code below this line
lastNameLength = lastName;
```
# --solutions--
```js
var lastNameLength = 0;
var lastName = "Lovelace";
let lastNameLength = 0;
const lastName = "Lovelace";
lastNameLength = lastName.length;
```

View File

@ -31,7 +31,7 @@ Set `remainder` equal to the remainder of `11` divided by `3` using the <dfn>rem
The variable `remainder` should be initialized
```js
assert(/var\s+?remainder/.test(code));
assert(/(const|let|var)\s+?remainder/.test(code));
```
The value of `remainder` should be `2`
@ -57,13 +57,11 @@ assert(/\s+?remainder\s*?=\s*?.*%.*;?/.test(code));
## --seed-contents--
```js
// Only change code below this line
var remainder;
const remainder = 0;
```
# --solutions--
```js
var remainder = 11 % 3;
const remainder = 11 % 3;
```

View File

@ -11,13 +11,13 @@ dashedName: global-scope-and-functions
In JavaScript, <dfn>scope</dfn> refers to the visibility of variables. Variables which are defined outside of a function block have <dfn>Global</dfn> scope. This means, they can be seen everywhere in your JavaScript code.
Variables which are declared without the `var` keyword are automatically created in the `global` scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with `var`.
Variables which are declared without the `let` or `const` keywords are automatically created in the `global` scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with `let` or `const`.
# --instructions--
Using `var`, declare a global variable named `myGlobal` outside of any function. Initialize it with a value of `10`.
Using `let` or `const`, declare a global variable named `myGlobal` outside of any function. Initialize it with a value of `10`.
Inside function `fun1`, assign `5` to `oopsGlobal` ***without*** using the `var` keyword.
Inside function `fun1`, assign `5` to `oopsGlobal` ***without*** using the `let` or `const` keywords.
# --hints--
@ -33,10 +33,10 @@ assert(typeof myGlobal != 'undefined');
assert(myGlobal === 10);
```
`myGlobal` should be declared using the `var` keyword
`myGlobal` should be declared using the `let` or `const` keywords
```js
assert(/var\s+myGlobal/.test(code));
assert(/(let|const)\s+myGlobal/.test(code));
```
`oopsGlobal` should be a global variable and have a value of `5`
@ -109,7 +109,7 @@ function fun2() {
# --solutions--
```js
var myGlobal = 10;
const myGlobal = 10;
function fun1() {
oopsGlobal = 5;

View File

@ -14,9 +14,10 @@ It is possible to have both <dfn>local</dfn> and <dfn>global</dfn> variables wit
In this example:
```js
var someVar = "Hat";
const someVar = "Hat";
function myFun() {
var someVar = "Head";
const someVar = "Head";
return someVar;
}
```
@ -53,13 +54,11 @@ assert(/return outerWear/.test(code));
```js
// Setup
var outerWear = "T-Shirt";
const outerWear = "T-Shirt";
function myOutfit() {
// Only change code below this line
// Only change code above this line
return outerWear;
}
@ -70,9 +69,9 @@ myOutfit();
# --solutions--
```js
var outerWear = "T-Shirt";
const outerWear = "T-Shirt";
function myOutfit() {
var outerWear = "sweater";
const outerWear = "sweater";
return outerWear;
}
```

View File

@ -90,7 +90,8 @@ assert(golfScore(5, 9) === 'Go Home!');
## --seed-contents--
```js
var names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"];
const names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"];
function golfScore(par, strokes) {
// Only change code below this line

View File

@ -39,7 +39,7 @@ You should not use the assignment operator.
```js
assert(
/var\s*myVar\s*=\s*87;\s*\/*.*\s*([+]{2}\s*myVar|myVar\s*[+]{2});/.test(code)
/let\s*myVar\s*=\s*87;\s*\/*.*\s*([+]{2}\s*myVar|myVar\s*[+]{2});/.test(code)
);
```
@ -52,7 +52,7 @@ assert(/[+]{2}\s*myVar|myVar\s*[+]{2}/.test(code));
You should not change code above the specified comment.
```js
assert(/var myVar = 87;/.test(code));
assert(/let myVar = 87;/.test(code));
```
# --seed--
@ -66,7 +66,7 @@ assert(/var myVar = 87;/.test(code));
## --seed-contents--
```js
var myVar = 87;
let myVar = 87;
// Only change code below this line
myVar = myVar + 1;
@ -75,6 +75,6 @@ myVar = myVar + 1;
# --solutions--
```js
var myVar = 87;
let myVar = 87;
myVar++;
```

View File

@ -64,7 +64,7 @@ assert(testElse(10) === 'Bigger than 5');
You should not change the code above or below the specified comments.
```js
assert(/var result = "";/.test(code) && /return result;/.test(code));
assert(/let result = "";/.test(code) && /return result;/.test(code));
```
# --seed--
@ -73,7 +73,7 @@ assert(/var result = "";/.test(code) && /return result;/.test(code));
```js
function testElse(val) {
var result = "";
let result = "";
// Only change code below this line
if (val > 5) {
@ -95,7 +95,7 @@ testElse(4);
```js
function testElse(val) {
var result = "";
let result = "";
if(val > 5) {
result = "Bigger than 5";
} else {

View File

@ -14,13 +14,14 @@ For loops don't have to iterate one at a time. By changing our `final-expression
We'll start at `i = 0` and loop while `i < 10`. We'll increment `i` by 2 each loop with `i += 2`.
```js
var ourArray = [];
for (var i = 0; i < 10; i += 2) {
const ourArray = [];
for (let i = 0; i < 10; i += 2) {
ourArray.push(i);
}
```
`ourArray` will now contain `[0,2,4,6,8]`. Let's change our `initialization` so we can count by odd numbers.
`ourArray` will now contain `[0, 2, 4, 6, 8]`. Let's change our `initialization` so we can count by odd numbers.
# --instructions--
@ -34,7 +35,7 @@ You should be using a `for` loop for this.
assert(/for\s*\([^)]+?\)/.test(code));
```
`myArray` should equal `[1,3,5,7,9]`.
`myArray` should equal `[1, 3, 5, 7, 9]`.
```js
assert.deepEqual(myArray, [1, 3, 5, 7, 9]);
@ -52,16 +53,17 @@ if(typeof myArray !== "undefined"){(function(){return myArray;})();}
```js
// Setup
var myArray = [];
const myArray = [];
// Only change code below this line
```
# --solutions--
```js
var myArray = [];
for (var i = 1; i < 10; i += 2) {
const myArray = [];
for (let i = 1; i < 10; i += 2) {
myArray.push(i);
}
```

View File

@ -12,8 +12,9 @@ dashedName: iterate-through-an-array-with-a-for-loop
A common task in JavaScript is to iterate through the contents of an array. One way to do that is with a `for` loop. This code will output each element of the array `arr` to the console:
```js
var arr = [10, 9, 8, 7, 6];
for (var i = 0; i < arr.length; i++) {
const arr = [10, 9, 8, 7, 6];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
```
@ -62,18 +63,19 @@ assert(!__helpers.removeWhiteSpace(code).match(/total[=+-]0*[1-9]+/gm));
```js
// Setup
var myArr = [ 2, 3, 4, 5, 6];
const myArr = [2, 3, 4, 5, 6];
// Only change code below this line
```
# --solutions--
```js
var myArr = [ 2, 3, 4, 5, 6];
var total = 0;
const myArr = [2, 3, 4, 5, 6];
let total = 0;
for (var i = 0; i < myArr.length; i++) {
for (let i = 0; i < myArr.length; i++) {
total += myArr[i];
}
```

View File

@ -12,8 +12,9 @@ dashedName: iterate-with-javascript-do---while-loops
The next type of loop you will learn is called a `do...while` loop. It is called a `do...while` loop because it will first `do` one pass of the code inside the loop no matter what, and then continue to run the loop `while` the specified condition evaluates to `true`.
```js
var ourArray = [];
var i = 0;
const ourArray = [];
let i = 0;
do {
ourArray.push(i);
i++;
@ -23,8 +24,9 @@ do {
The example above behaves similar to other types of loops, and the resulting array will look like `[0, 1, 2, 3, 4]`. However, what makes the `do...while` different from other loops is how it behaves when the condition fails on the first check. Let's see this in action: Here is a regular `while` loop that will run the code in the loop as long as `i < 5`:
```js
var ourArray = [];
var i = 5;
const ourArray = [];
let i = 5;
while (i < 5) {
ourArray.push(i);
i++;
@ -34,8 +36,9 @@ while (i < 5) {
In this example, we initialize the value of `ourArray` to an empty array and the value of `i` to 5. When we execute the `while` loop, the condition evaluates to `false` because `i` is not less than 5, so we do not execute the code inside the loop. The result is that `ourArray` will end up with no values added to it, and it will still look like `[]` when all of the code in the example above has completed running. Now, take a look at a `do...while` loop:
```js
var ourArray = [];
var i = 5;
const ourArray = [];
let i = 5;
do {
ourArray.push(i);
i++;
@ -80,8 +83,8 @@ if(typeof myArray !== "undefined"){(function(){return myArray;})();}
```js
// Setup
var myArray = [];
var i = 10;
const myArray = [];
let i = 10;
// Only change code below this line
while (i < 5) {
@ -93,8 +96,8 @@ while (i < 5) {
# --solutions--
```js
var myArray = [];
var i = 10;
const myArray = [];
let i = 10;
do {
myArray.push(i);
i++;

View File

@ -15,7 +15,7 @@ The most common type of JavaScript loop is called a `for` loop because it runs f
For loops are declared with three optional expressions separated by semicolons:
`for (a; b; c)`, where `a` is the intialization statement, `b` is the condition statement, and `c` is the final expression.
`for (a; b; c)`, where `a` is the initialization 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.
@ -26,13 +26,14 @@ The final expression is executed at the end of each loop iteration, prior to the
In the following example we initialize with `i = 0` and iterate while our condition `i < 5` is true. We'll increment `i` by `1` in each loop iteration with `i++` as our final expression.
```js
var ourArray = [];
for (var i = 0; i < 5; i++) {
const ourArray = [];
for (let i = 0; i < 5; i++) {
ourArray.push(i);
}
```
`ourArray` will now have the value `[0,1,2,3,4]`.
`ourArray` will now have the value `[0, 1, 2, 3, 4]`.
# --instructions--
@ -46,7 +47,7 @@ You should be using a `for` loop for this.
assert(/for\s*\([^)]+?\)/.test(code));
```
`myArray` should equal `[1,2,3,4,5]`.
`myArray` should equal `[1, 2, 3, 4, 5]`.
```js
assert.deepEqual(myArray, [1, 2, 3, 4, 5]);
@ -64,16 +65,17 @@ if (typeof myArray !== "undefined"){(function(){return myArray;})();}
```js
// Setup
var myArray = [];
const myArray = [];
// Only change code below this line
```
# --solutions--
```js
var myArray = [];
for (var i = 1; i < 6; i++) {
const myArray = [];
for (let i = 1; i < 6; i++) {
myArray.push(i);
}
```

View File

@ -14,9 +14,10 @@ You can run the same code multiple times by using a loop.
The first type of loop we will learn is called a `while` loop because it runs while a specified condition is true and stops once that condition is no longer true.
```js
var ourArray = [];
var i = 0;
while(i < 5) {
const ourArray = [];
let i = 0;
while (i < 5) {
ourArray.push(i);
i++;
}
@ -38,7 +39,7 @@ You should be using a `while` loop for this.
assert(code.match(/while/g));
```
`myArray` should equal `[5,4,3,2,1,0]`.
`myArray` should equal `[5, 4, 3, 2, 1, 0]`.
```js
assert.deepEqual(myArray, [5, 4, 3, 2, 1, 0]);
@ -56,17 +57,18 @@ if(typeof myArray !== "undefined"){(function(){return myArray;})();}
```js
// Setup
var myArray = [];
const myArray = [];
// Only change code below this line
```
# --solutions--
```js
var myArray = [];
var i = 5;
while(i >= 0) {
const myArray = [];
let i = 5;
while (i >= 0) {
myArray.push(i);
i--;
}

View File

@ -15,9 +15,10 @@ Here is a function `myTest` with a local variable called `loc`.
```js
function myTest() {
var loc = "foo";
const loc = "foo";
console.log(loc);
}
myTest();
console.log(loc);
```
@ -38,6 +39,7 @@ The code should not contain a global `myVar` variable.
function declared() {
myVar;
}
assert.throws(declared, ReferenceError);
```
@ -57,7 +59,6 @@ assert(
```js
function myLocalScope() {
// Only change code below this line
console.log('inside myLocalScope', myVar);
@ -73,9 +74,8 @@ console.log('outside myLocalScope', myVar);
```js
function myLocalScope() {
// Only change code below this line
var myVar;
let myVar;
console.log('inside myLocalScope', myVar);
}
myLocalScope();

View File

@ -16,8 +16,8 @@ Another way to change the data in an array is with the `.pop()` function.
Any type of entry can be popped off of an array - numbers, strings, even nested arrays.
```js
var threeArr = [1, 4, 6];
var oneDown = threeArr.pop();
const threeArr = [1, 4, 6];
const oneDown = threeArr.pop();
console.log(oneDown);
console.log(threeArr);
```
@ -26,7 +26,7 @@ The first `console.log` will display the value `6`, and the second will display
# --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` and assign the popped off value to a new variable, `removedFromMyArray`.
# --hints--
@ -69,22 +69,22 @@ assert(
## --after-user-code--
```js
(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);
if (typeof removedFromMyArray !== 'undefined') (function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);
```
## --seed-contents--
```js
// Setup
var myArray = [["John", 23], ["cat", 2]];
const myArray = [["John", 23], ["cat", 2]];
// Only change code below this line
var removedFromMyArray;
```
# --solutions--
```js
var myArray = [["John", 23], ["cat", 2]];
var removedFromMyArray = myArray.pop();
const myArray = [["John", 23], ["cat", 2]];
const removedFromMyArray = myArray.pop();
```

View File

@ -16,10 +16,10 @@ An easy way to append data to the end of an array is via the `push()` function.
Examples:
```js
var arr1 = [1,2,3];
const arr1 = [1, 2, 3];
arr1.push(4);
var arr2 = ["Stimpson", "J", "cat"];
const arr2 = ["Stimpson", "J", "cat"];
arr2.push(["happy", "joy"]);
```
@ -64,14 +64,15 @@ assert(
```js
// Setup
var myArray = [["John", 23], ["cat", 2]];
const myArray = [["John", 23], ["cat", 2]];
// Only change code below this line
```
# --solutions--
```js
var myArray = [["John", 23], ["cat", 2]];
const myArray = [["John", 23], ["cat", 2]];
myArray.push(["dog",3]);
```

View File

@ -16,15 +16,15 @@ That's where `.shift()` comes in. It works just like `.pop()`, except it removes
Example:
```js
var ourArray = ["Stimpson", "J", ["cat"]];
var removedFromOurArray = ourArray.shift();
const ourArray = ["Stimpson", "J", ["cat"]];
const removedFromOurArray = ourArray.shift();
```
`removedFromOurArray` would have a value of the string `Stimpson`, and `ourArray` would have `["J", ["cat"]]`.
# --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` and assign the "shifted off" value to a new variable, `removedFromMyArray`.
# --hints--
@ -65,24 +65,24 @@ assert(
## --after-user-code--
```js
(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);
if (typeof removedFromMyArray !== 'undefined') (function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);
```
## --seed-contents--
```js
// Setup
var myArray = [["John", 23], ["dog", 3]];
const myArray = [["John", 23], ["dog", 3]];
// Only change code below this line
var removedFromMyArray;
```
# --solutions--
```js
var myArray = [["John", 23], ["dog", 3]];
const myArray = [["John", 23], ["dog", 3]];
// Only change code below this line
var removedFromMyArray = myArray.shift();
const removedFromMyArray = myArray.shift();
```

View File

@ -16,7 +16,7 @@ Not only can you `shift` elements off of the beginning of an array, you can also
Example:
```js
var ourArray = ["Stimpson", "J", "cat"];
const ourArray = ["Stimpson", "J", "cat"];
ourArray.shift();
ourArray.unshift("Happy");
```
@ -25,7 +25,7 @@ After the `shift`, `ourArray` would have the value `["J", "cat"]`. After the `un
# --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()`.
# --hints--
@ -63,16 +63,17 @@ assert(
```js
// Setup
var myArray = [["John", 23], ["dog", 3]];
const myArray = [["John", 23], ["dog", 3]];
myArray.shift();
// Only change code below this line
```
# --solutions--
```js
var myArray = [["John", 23], ["dog", 3]];
const myArray = [["John", 23], ["dog", 3]];
myArray.shift();
myArray.unshift(["Paul", 35]);
```

View File

@ -14,7 +14,7 @@ Sometimes you may want to store data in a flexible <dfn>Data Structure</dfn>. A
Here's an example of a complex data structure:
```js
var ourMusic = [
const ourMusic = [
{
"artist": "Daft Punk",
"title": "Homework",
@ -135,7 +135,7 @@ myMusic.forEach(object => {
## --seed-contents--
```js
var myMusic = [
const myMusic = [
{
"artist": "Billy Joel",
"title": "Piano Man",
@ -153,7 +153,7 @@ var myMusic = [
# --solutions--
```js
var myMusic = [
const myMusic = [
{
"artist": "Billy Joel",
"title": "Piano Man",

View File

@ -9,12 +9,12 @@ dashedName: modify-array-data-with-indexes
# --description--
Unlike strings, the entries of arrays are <dfn>mutable</dfn> and can be changed freely.
Unlike strings, the entries of arrays are <dfn>mutable</dfn> and can be changed freely, even if the array was declared with `const`.
**Example**
```js
var ourArray = [50,40,30];
const ourArray = [50, 40, 30];
ourArray[0] = 15;
```
@ -28,7 +28,7 @@ Modify the data stored at index `0` of `myArray` to a value of `45`.
# --hints--
`myArray` should now be `[45,64,99]`.
`myArray` should now be `[45, 64, 99]`.
```js
assert(
@ -73,14 +73,15 @@ if(typeof myArray !== "undefined"){(function(){return myArray;})();}
```js
// Setup
var myArray = [18,64,99];
const myArray = [18, 64, 99];
// Only change code below this line
```
# --solutions--
```js
var myArray = [18,64,99];
const myArray = [18, 64, 99];
myArray[0] = 45;
```

View File

@ -12,7 +12,7 @@ dashedName: multiple-identical-options-in-switch-statements
If the `break` statement is omitted from a `switch` statement's `case`, the following `case` statement(s) are executed until a `break` is encountered. If you have multiple inputs with the same output, you can represent them in a `switch` statement like this:
```js
var result = "";
let result = "";
switch(val) {
case 1:
case 2:
@ -109,7 +109,7 @@ assert(code.match(/case/g).length === 9);
```js
function sequentialSizes(val) {
var answer = "";
let answer = "";
// Only change code below this line
@ -125,7 +125,7 @@ sequentialSizes(1);
```js
function sequentialSizes(val) {
var answer = "";
let answer = "";
switch(val) {
case 1:

View File

@ -42,11 +42,11 @@ assert(/\*/.test(code));
## --seed-contents--
```js
var product = 2.0 * 0.0;
const product = 2.0 * 0.0;
```
# --solutions--
```js
var product = 2.0 * 2.5;
const product = 2.0 * 2.5;
```

View File

@ -16,7 +16,7 @@ JavaScript uses the `*` symbol for multiplication of two numbers.
**Example**
```js
myVar = 13 * 13;
const myVar = 13 * 13;
```
`myVar` would have the value `169`.
@ -50,11 +50,11 @@ assert(/\*/.test(code));
## --seed-contents--
```js
var product = 8 * 0;
const product = 8 * 0;
```
# --solutions--
```js
var product = 8 * 10;
const product = 8 * 10;
```

View File

@ -12,7 +12,7 @@ dashedName: nest-one-array-within-another-array
You can also nest arrays within other arrays, like below:
```js
[["Bulls", 23], ["White Sox", 45]]
const teams = [["Bulls", 23], ["White Sox", 45]];
```
This is also called a <dfn>multi-dimensional array</dfn>.
@ -41,11 +41,11 @@ if(typeof myArray !== "undefined"){(function(){return myArray;})();}
```js
// Only change code below this line
var myArray = [];
const myArray = [];
```
# --solutions--
```js
var myArray = [[1,2,3]];
const myArray = [[1, 2, 3]];
```

View File

@ -12,11 +12,12 @@ dashedName: nesting-for-loops
If you have a multi-dimensional array, you can use the same logic as the prior waypoint to loop through both the array and any sub-arrays. Here is an example:
```js
var arr = [
[1,2], [3,4], [5,6]
const arr = [
[1, 2], [3, 4], [5, 6]
];
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
console.log(arr[i][j]);
}
}
@ -30,13 +31,13 @@ Modify function `multiplyAll` so that it returns the product of all the numbers
# --hints--
`multiplyAll([[1],[2],[3]])` should return `6`
`multiplyAll([[1], [2], [3]])` should return `6`
```js
assert(multiplyAll([[1], [2], [3]]) === 6);
```
`multiplyAll([[1,2],[3,4],[5,6,7]])` should return `5040`
`multiplyAll([[1, 2], [3, 4], [5, 6, 7]])` should return `5040`
```js
assert(
@ -48,7 +49,7 @@ assert(
);
```
`multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]])` should return `54`
`multiplyAll([[5, 1], [0.2, 4, 0.5], [3, 9]])` should return `54`
```js
assert(
@ -66,28 +67,26 @@ assert(
```js
function multiplyAll(arr) {
var product = 1;
let product = 1;
// Only change code below this line
// Only change code above this line
return product;
}
multiplyAll([[1,2],[3,4],[5,6,7]]);
multiplyAll([[1, 2], [3, 4], [5, 6, 7]]);
```
# --solutions--
```js
function multiplyAll(arr) {
var product = 1;
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
let product = 1;
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
product *= arr[i][j];
}
}
return product;
}
multiplyAll([[1,2],[3,4],[5,6,7]]);
```

View File

@ -68,34 +68,33 @@ assert(lookUpProfile('Akira', 'address') === 'No such property');
```js
// Setup
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Sherlock",
"lastName": "Holmes",
"number": "0487345643",
"likes": ["Intriguing Cases", "Violin"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["JavaScript", "Gaming", "Foxes"]
}
const contacts = [
{
firstName: "Akira",
lastName: "Laine",
number: "0543236543",
likes: ["Pizza", "Coding", "Brownie Points"],
},
{
firstName: "Harry",
lastName: "Potter",
number: "0994372684",
likes: ["Hogwarts", "Magic", "Hagrid"],
},
{
firstName: "Sherlock",
lastName: "Holmes",
number: "0487345643",
likes: ["Intriguing Cases", "Violin"],
},
{
firstName: "Kristian",
lastName: "Vos",
number: "unknown",
likes: ["JavaScript", "Gaming", "Foxes"],
},
];
function lookUpProfile(name, prop) {
// Only change code below this line
@ -108,44 +107,38 @@ lookUpProfile("Akira", "likes");
# --solutions--
```js
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Sherlock",
"lastName": "Holmes",
"number": "0487345643",
"likes": ["Intriguing Cases", "Violin"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["JavaScript", "Gaming", "Foxes"]
},
const contacts = [
{
firstName: "Akira",
lastName: "Laine",
number: "0543236543",
likes: ["Pizza", "Coding", "Brownie Points"],
},
{
firstName: "Harry",
lastName: "Potter",
number: "0994372684",
likes: ["Hogwarts", "Magic", "Hagrid"],
},
{
firstName: "Sherlock",
lastName: "Holmes",
number: "0487345643",
likes: ["Intriguing Cases", "Violin"],
},
{
firstName: "Kristian",
lastName: "Vos",
number: "unknown",
likes: ["JavaScript", "Gaming", "Foxes"],
},
];
//Write your function in between these comments
function lookUpProfile(name, prop){
for(var i in contacts){
if(contacts[i].firstName === name) {
return contacts[i][prop] || "No such property";
}
function lookUpProfile(name, prop) {
for (let i in contacts) {
if (contacts[i].firstName === name) {
return contacts[i][prop] || "No such property";
}
return "No such contact";
}
return "No such contact";
}
//Write your function in between these comments
lookUpProfile("Akira", "likes");
```

View File

@ -12,21 +12,21 @@ dashedName: quoting-strings-with-single-quotes
<dfn>String</dfn> values in JavaScript may be written with single or double quotes, as long as you start and end with the same type of quote. Unlike some other programming languages, single and double quotes work the same in JavaScript.
```js
doubleQuoteStr = "This is a string";
singleQuoteStr = 'This is also a string';
const doubleQuoteStr = "This is a string";
const singleQuoteStr = 'This is also a string';
```
The reason why you might want to use one type of quote over the other is if you want to use both in a string. This might happen if you want to save a conversation in a string and have the conversation in quotes. Another use for it would be saving an `<a>` tag with various attributes in quotes, all within a string.
```js
conversation = 'Finn exclaims to Jake, "Algebraic!"';
const conversation = 'Finn exclaims to Jake, "Algebraic!"';
```
However, this becomes a problem if you need to use the outermost quotes within it. Remember, a string has the same kind of quote at the beginning and end. But if you have that same quote somewhere in the middle, the string will stop early and throw an error.
```js
goodStr = 'Jake asks Finn, "Hey, let\'s go on an adventure?"';
badStr = 'Finn responds, "Let's go!"';
const goodStr = 'Jake asks Finn, "Hey, let\'s go on an adventure?"';
const badStr = 'Finn responds, "Let's go!"';
```
Here `badStr` will throw an error.
@ -71,11 +71,11 @@ assert(code.match(/"/g).length === 4 && code.match(/'/g).length === 2);
## --seed-contents--
```js
var myStr = "<a href=\"http://www.example.com\" target=\"_blank\">Link</a>";
const myStr = "<a href=\"http://www.example.com\" target=\"_blank\">Link</a>";
```
# --solutions--
```js
var myStr = '<a href="http://www.example.com" target="_blank">Link</a>';
const myStr = '<a href="http://www.example.com" target="_blank">Link</a>';
```

View File

@ -115,7 +115,7 @@ const _recordCollection = {
```js
// Setup
var recordCollection = {
const recordCollection = {
2548: {
albumTitle: 'Slippery When Wet',
artist: 'Bon Jovi',
@ -146,7 +146,7 @@ updateRecords(recordCollection, 5439, 'artist', 'ABBA');
# --solutions--
```js
var recordCollection = {
const recordCollection = {
2548: {
albumTitle: 'Slippery When Wet',
artist: 'Bon Jovi',

View File

@ -14,9 +14,9 @@ Recursion is the concept that a function can be expressed in terms of itself. To
```js
function multiply(arr, n) {
var product = 1;
for (var i = 0; i < n; i++) {
product *= arr[i];
let product = 1;
for (let i = 0; i < n; i++) {
product *= arr[i];
}
return product;
}

View File

@ -108,7 +108,7 @@ assert(chainToSwitch(156) === '');
```js
function chainToSwitch(val) {
var answer = "";
let answer = "";
// Only change code below this line
if (val === "bob") {
@ -134,7 +134,7 @@ chainToSwitch(7);
```js
function chainToSwitch(val) {
var answer = "";
let answer = "";
switch(val) {
case "bob":

View File

@ -17,7 +17,8 @@ We can pass values into a function with <dfn>arguments</dfn>. You can use a `ret
function plusThree(num) {
return num + 3;
}
var answer = plusThree(5);
const answer = plusThree(5);
```
`answer` has the value `8`.

View File

@ -33,43 +33,43 @@ Remember that [`undefined` is a keyword](https://www.freecodecamp.org/learn/java
# --hints--
`abTest(2,2)` should return a number
`abTest(2, 2)` should return a number
```js
assert(typeof abTest(2, 2) === 'number');
```
`abTest(2,2)` should return `8`
`abTest(2, 2)` should return `8`
```js
assert(abTest(2, 2) === 8);
```
`abTest(-2,2)` should return `undefined`
`abTest(-2, 2)` should return `undefined`
```js
assert(abTest(-2, 2) === undefined);
```
`abTest(2,-2)` should return `undefined`
`abTest(2, -2)` should return `undefined`
```js
assert(abTest(2, -2) === undefined);
```
`abTest(2,8)` should return `18`
`abTest(2, 8)` should return `18`
```js
assert(abTest(2, 8) === 18);
```
`abTest(3,3)` should return `12`
`abTest(3, 3)` should return `12`
```js
assert(abTest(3, 3) === 12);
```
`abTest(0,0)` should return `0`
`abTest(0, 0)` should return `0`
```js
assert(abTest(0, 0) === 0);

View File

@ -14,7 +14,7 @@ You may recall from [Comparison with the Equality Operator](/learn/javascript-al
Sometimes people use an `if/else` statement to do a comparison, like this:
```js
function isEqual(a,b) {
function isEqual(a, b) {
if (a === b) {
return true;
} else {
@ -26,7 +26,7 @@ function isEqual(a,b) {
But there's a better way to do this. Since `===` returns `true` or `false`, we can return the result of the comparison:
```js
function isEqual(a,b) {
function isEqual(a, b) {
return a === b;
}
```
@ -37,13 +37,13 @@ Fix the function `isLess` to remove the `if/else` statements.
# --hints--
`isLess(10,15)` should return `true`
`isLess(10, 15)` should return `true`
```js
assert(isLess(10, 15) === true);
```
`isLess(15,10)` should return `false`
`isLess(15, 10)` should return `false`
```js
assert(isLess(15, 10) === false);

View File

@ -78,7 +78,7 @@ assert(code.match(/break/g).length > 2);
```js
function caseInSwitch(val) {
var answer = "";
let answer = "";
// Only change code below this line
@ -94,7 +94,7 @@ caseInSwitch(1);
```js
function caseInSwitch(val) {
var answer = "";
let answer = "";
switch(val) {
case 1:

View File

@ -81,13 +81,13 @@ var hasNumber = false;
## --seed-contents--
```js
var myList = [];
const myList = [];
```
# --solutions--
```js
var myList = [
const myList = [
["Candy", 10],
["Potatoes", 12],
["Eggs", 12],

View File

@ -93,12 +93,10 @@ function nextInLine(arr, item) {
return item;
// Only change code above this line
}
// Setup
var testArr = [1,2,3,4,5];
const testArr = [1, 2, 3, 4, 5];
// Display code
console.log("Before: " + JSON.stringify(testArr));
@ -109,7 +107,7 @@ console.log("After: " + JSON.stringify(testArr));
# --solutions--
```js
var testArr = [ 1,2,3,4,5];
const testArr = [1, 2, 3, 4, 5];
function nextInLine(arr, item) {
arr.push(item);

View File

@ -14,7 +14,7 @@ With JavaScript `array` variables, we can store several pieces of data in one pl
You start an array declaration with an opening square bracket, end it with a closing square bracket, and put a comma between each entry, like this:
```js
var sandwich = ["peanut butter", "jelly", "bread"]
const sandwich = ["peanut butter", "jelly", "bread"];
```
# --instructions--
@ -53,11 +53,11 @@ assert(typeof myArray[1] !== 'undefined' && typeof myArray[1] == 'number');
```js
// Only change code below this line
var myArray = [];
const myArray = [];
```
# --solutions--
```js
var myArray = ["The Answer", 42];
const myArray = ["The Answer", 42];
```

View File

@ -16,7 +16,7 @@ JavaScript uses the `-` symbol for subtraction.
**Example**
```js
myVar = 12 - 6;
const myVar = 12 - 6;
```
`myVar` would have the value `6`.
@ -49,11 +49,11 @@ assert(/difference=45-33;?/.test(__helpers.removeWhiteSpace(code)));
## --seed-contents--
```js
var difference = 45 - 0;
const difference = 45 - 0;
```
# --solutions--
```js
var difference = 45 - 33;
const difference = 45 - 33;
```

View File

@ -13,10 +13,11 @@ Sometimes it is useful to check if the property of a given object exists or not.
**Example**
```js
var myObj = {
const myObj = {
top: "hat",
bottom: "pants"
};
myObj.hasOwnProperty("top");
myObj.hasOwnProperty("middle");
```

View File

@ -14,14 +14,14 @@ In JavaScript, `String` values are <dfn>immutable</dfn>, which means that they c
For example, the following code:
```js
var myStr = "Bob";
let myStr = "Bob";
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:
```js
var myStr = "Bob";
let myStr = "Bob";
myStr = "Job";
```
@ -55,7 +55,7 @@ assert(/myStr = "Jello World"/.test(code));
```js
// Setup
var myStr = "Jello World";
let myStr = "Jello World";
// Only change code below this line
myStr[0] = "H"; // Change this line
@ -65,6 +65,6 @@ myStr[0] = "H"; // Change this line
# --solutions--
```js
var myStr = "Jello World";
let myStr = "Jello World";
myStr = "Hello World";
```

View File

@ -43,7 +43,6 @@ welcomeToBooleans();
```js
function welcomeToBooleans() {
// Only change code below this line
return false; // Change this line

View File

@ -14,10 +14,12 @@ A function can include the `return` statement but it does not have to. In the ca
**Example**
```js
var sum = 0;
let sum = 0;
function addSum(num) {
sum = sum + num;
}
addSum(3);
```
@ -61,7 +63,7 @@ assert(
```js
// Setup
var sum = 0;
let sum = 0;
function addThree() {
sum = sum + 3;
@ -79,7 +81,7 @@ addFive();
# --solutions--
```js
var sum = 0;
let sum = 0;
function addThree() {
sum = sum + 3;

View File

@ -14,7 +14,7 @@ After you've created a JavaScript object, you can update its properties at any t
For example, let's look at `ourDog`:
```js
var ourDog = {
const ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
@ -54,7 +54,7 @@ assert(/"name": "Coder"/.test(code));
```js
// Setup
var myDog = {
const myDog = {
"name": "Coder",
"legs": 4,
"tails": 1,
@ -62,12 +62,13 @@ var myDog = {
};
// Only change code below this line
```
# --solutions--
```js
var myDog = {
const myDog = {
"name": "Coder",
"legs": 4,
"tails": 1,

View File

@ -13,13 +13,13 @@ dashedName: use-bracket-notation-to-find-the-first-character-in-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.
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 `const firstName = "Charles"`, you can get the value of the first letter of the string by using `firstName[0]`.
Example:
```js
var firstName = "Charles";
var firstLetter = firstName[0];
const firstName = "Charles";
const firstLetter = firstName[0];
```
`firstLetter` would have a value of the string `C`.
@ -56,8 +56,8 @@ assert(code.match(/firstLetterOfLastName\s*?=\s*?lastName\[.*?\]/));
```js
// Setup
var firstLetterOfLastName = "";
var lastName = "Lovelace";
let firstLetterOfLastName = "";
const lastName = "Lovelace";
// Only change code below this line
firstLetterOfLastName = lastName; // Change this line
@ -66,8 +66,8 @@ firstLetterOfLastName = lastName; // Change this line
# --solutions--
```js
var firstLetterOfLastName = "";
var lastName = "Lovelace";
let firstLetterOfLastName = "";
const lastName = "Lovelace";
// Only change code below this line
firstLetterOfLastName = lastName[0];

View File

@ -11,13 +11,13 @@ dashedName: use-bracket-notation-to-find-the-last-character-in-a-string
In order to get the last letter of a string, you can subtract one from the string's length.
For example, if `var firstName = "Ada"`, you can get the value of the last letter of the string by using `firstName[firstName.length - 1]`.
For example, if `const firstName = "Ada"`, you can get the value of the last letter of the string by using `firstName[firstName.length - 1]`.
Example:
```js
var firstName = "Ada";
var lastLetter = firstName[firstName.length - 1];
const firstName = "Ada";
const lastLetter = firstName[firstName.length - 1];
```
`lastLetter` would have a value of the string `a`.
@ -54,15 +54,15 @@ assert(code.match(/\.length/g).length > 0);
```js
// Setup
var lastName = "Lovelace";
const lastName = "Lovelace";
// Only change code below this line
var lastLetterOfLastName = lastName; // Change this line
const lastLetterOfLastName = lastName; // Change this line
```
# --solutions--
```js
var lastName = "Lovelace";
var lastLetterOfLastName = lastName[lastName.length - 1];
const lastName = "Lovelace";
const lastLetterOfLastName = lastName[lastName.length - 1];
```

View File

@ -16,8 +16,8 @@ Remember that computers start counting at `0`, so the first character is actuall
Example:
```js
var firstName = "Ada";
var secondLetterOfFirstName = firstName[1];
const firstName = "Ada";
const secondLetterOfFirstName = firstName[1];
```
`secondLetterOfFirstName` would have a value of the string `d`.
@ -54,15 +54,15 @@ assert(code.match(/thirdLetterOfLastName\s*?=\s*?lastName\[.*?\]/));
```js
// Setup
var lastName = "Lovelace";
const lastName = "Lovelace";
// Only change code below this line
var thirdLetterOfLastName = lastName; // Change this line
const thirdLetterOfLastName = lastName; // Change this line
```
# --solutions--
```js
var lastName = "Lovelace";
var thirdLetterOfLastName = lastName[2];
const lastName = "Lovelace";
const thirdLetterOfLastName = lastName[2];
```

View File

@ -11,13 +11,13 @@ dashedName: use-bracket-notation-to-find-the-nth-to-last-character-in-a-string
You can use the same principle we just used to retrieve the last character in a string to retrieve the Nth-to-last character.
For example, you can get the value of the third-to-last letter of the `var firstName = "Augusta"` string by using `firstName[firstName.length - 3]`
For example, you can get the value of the third-to-last letter of the `const firstName = "Augusta"` string by using `firstName[firstName.length - 3]`
Example:
```js
var firstName = "Augusta";
var thirdToLastLetter = firstName[firstName.length - 3];
const firstName = "Augusta";
const thirdToLastLetter = firstName[firstName.length - 3];
```
`thirdToLastLetter` would have a value of the string `s`.
@ -54,15 +54,15 @@ assert(code.match(/\.length/g).length > 0);
```js
// Setup
var lastName = "Lovelace";
const lastName = "Lovelace";
// Only change code below this line
var secondToLastLetterOfLastName = lastName; // Change this line
const secondToLastLetterOfLastName = lastName; // Change this line
```
# --solutions--
```js
var lastName = "Lovelace";
var secondToLastLetterOfLastName = lastName[lastName.length - 2];
const lastName = "Lovelace";
const secondToLastLetterOfLastName = lastName[lastName.length - 2];
```

View File

@ -9,7 +9,7 @@ dashedName: use-conditional-logic-with-if-statements
# --description--
`If` statements are used to make decisions in code. The keyword `if` tells JavaScript to execute the code in the curly braces under certain conditions, defined in the parentheses. These conditions are known as `Boolean` conditions and they may only be `true` or `false`.
`if` statements are used to make decisions in code. The keyword `if` tells JavaScript to execute the code in the curly braces under certain conditions, defined in the parentheses. These conditions are known as `Boolean` conditions and they may only be `true` or `false`.
When the condition evaluates to `true`, the program executes the statement inside the curly braces. When the Boolean condition evaluates to `false`, the statement inside the curly braces will not execute.
@ -22,10 +22,11 @@ When the condition evaluates to `true`, the program executes the statement insid
```js
function test (myCondition) {
if (myCondition) {
return "It was true";
return "It was true";
}
return "It was false";
}
test(true);
test(false);
```

View File

@ -73,7 +73,7 @@ function rangeOfNumbers(startNum, endNum) {
if (endNum - startNum === 0) {
return [startNum];
} else {
var numbers = rangeOfNumbers(startNum, endNum - 1);
const numbers = rangeOfNumbers(startNum, endNum - 1);
numbers.push(endNum);
return numbers;
}

View File

@ -20,7 +20,7 @@ parseInt(string, radix);
And here's an example:
```js
var a = parseInt("11", 2);
const a = parseInt("11", 2);
```
The radix variable says that `11` is in the binary system, or base 2. This example converts the string `11` to an integer `3`.

View File

@ -12,7 +12,7 @@ dashedName: use-the-parseint-function
The `parseInt()` function parses a string and returns an integer. Here's an example:
```js
var a = parseInt("007");
const a = parseInt("007");
```
The above function converts the string `007` to the integer `7`. If the first character in the string can't be converted into a number, then it returns `NaN`.

View File

@ -14,7 +14,7 @@ Objects can be thought of as a key/value storage, like a dictionary. If you have
Here is an example of a simple reverse alphabet lookup:
```js
var alpha = {
const alpha = {
1:"Z",
2:"Y",
3:"X",
@ -24,10 +24,11 @@ var alpha = {
25:"B",
26:"A"
};
alpha[2];
alpha[24];
var value = 2;
const value = 2;
alpha[value];
```
@ -102,7 +103,7 @@ assert(
```js
// Setup
function phoneticLookup(val) {
var result = "";
let result = "";
// Only change code below this line
switch(val) {
@ -136,9 +137,9 @@ phoneticLookup("charlie");
```js
function phoneticLookup(val) {
var result = "";
let result = "";
var lookup = {
const lookup = {
alpha: "Adams",
bravo: "Boston",
charlie: "Chicago",

View File

@ -16,7 +16,7 @@ In a "Mad Libs" game, you are provided sentences with some missing words, like n
Consider this sentence - It was really **\_\_\_\_**, and we **\_\_\_\_** ourselves **\_\_\_\_**. This sentence has three missing pieces- an adjective, a verb and an adverb, and we can add words of our choice to complete it. We can then assign the completed sentence to a variable as follows:
```js
var sentence = "It was really " + "hot" + ", and we " + "laughed" + " ourselves " + "silly" + ".";
const sentence = "It was really " + "hot" + ", and we " + "laughed" + " ourselves " + "silly" + ".";
```
# --instructions--
@ -84,24 +84,24 @@ const removeAssignments = str => str
## --seed-contents--
```js
var myNoun = "dog";
var myAdjective = "big";
var myVerb = "ran";
var myAdverb = "quickly";
const myNoun = "dog";
const myAdjective = "big";
const myVerb = "ran";
const myAdverb = "quickly";
// Only change code below this line
var wordBlanks = ""; // Change this line
const wordBlanks = ""; // Change this line
// Only change code above this line
```
# --solutions--
```js
var myNoun = "dog";
var myAdjective = "big";
var myVerb = "ran";
var myAdverb = "quickly";
const myNoun = "dog";
const myAdjective = "big";
const myVerb = "ran";
const myAdverb = "quickly";
var wordBlanks = "Once there was a " + myNoun + " which was very " + myAdjective + ". ";
let wordBlanks = "Once there was a " + myNoun + " which was very " + myAdjective + ". ";
wordBlanks += "It " + myVerb + " " + myAdverb + " around the yard.";
```

View File

@ -8,6 +8,8 @@ dashedName: compare-scopes-of-the-var-and-let-keywords
# --description--
If you are unfamiliar with `let`, check out [this challenge](/learn/javascript-algorithms-and-data-structures/basic-javascript/explore-differences-between-the-var-and-let-keywords).
When you declare a variable with the `var` keyword, it is declared globally, or locally if declared inside a function.
The `let` keyword behaves similarly, but with some extra features. When you declare a variable with the `let` keyword inside a block, statement, or expression, its scope is limited to that block, statement, or expression.

View File

@ -1,89 +0,0 @@
---
id: 587d7b87367417b2b2512b41
title: Declare a Read-Only Variable with the const Keyword
challengeType: 1
forumTopicId: 301201
dashedName: declare-a-read-only-variable-with-the-const-keyword
---
# --description--
The keyword `let` is not the only new way to declare variables. In ES6, you can also declare variables using the `const` keyword.
`const` has all the awesome features that `let` has, with the added bonus that variables declared using `const` are read-only. They are a constant value, which means that once a variable is assigned with `const`, it cannot be reassigned.
```js
const FAV_PET = "Cats";
FAV_PET = "Dogs";
```
The console will display an error due to reassigning the value of `FAV_PET`.
As you can see, trying to reassign a variable declared with `const` will throw an error. You should always name variables you don't want to reassign using the `const` keyword. This helps when you accidentally attempt to reassign a variable that is meant to stay constant. A common practice when naming constants is to use all uppercase letters, with words separated by an underscore.
**Note:** It is common for developers to use uppercase variable identifiers for immutable values and lowercase or camelCase for mutable values (objects and arrays). In a later challenge you will see an example of a lowercase variable identifier being used for an array.
# --instructions--
Change the code so that all variables are declared using `let` or `const`. Use `let` when you want the variable to change, and `const` when you want the variable to remain constant. Also, rename variables declared with `const` to conform to common practices, meaning constants should be in all caps.
# --hints--
`var` should not exist in your code.
```js
(getUserInput) => assert(!getUserInput('index').match(/var/g));
```
`SENTENCE` should be a constant variable declared with `const`.
```js
(getUserInput) => assert(getUserInput('index').match(/(const SENTENCE)/g));
```
`i` should be declared with `let`.
```js
(getUserInput) => assert(getUserInput('index').match(/(let i)/g));
```
`console.log` should be changed to print the `SENTENCE` variable.
```js
(getUserInput) =>
assert(getUserInput('index').match(/console\.log\(\s*SENTENCE\s*\)\s*;?/g));
```
# --seed--
## --seed-contents--
```js
function printManyTimes(str) {
// Only change code below this line
var sentence = str + " is cool!";
for (var i = 0; i < str.length; i+=2) {
console.log(sentence);
}
// Only change code above this line
}
printManyTimes("freeCodeCamp");
```
# --solutions--
```js
function printManyTimes(str) {
const SENTENCE = str + " is cool!";
for (let i = 0; i < str.length; i+=2) {
console.log(SENTENCE);
}
}
printManyTimes("freeCodeCamp");
```

View File

@ -1,91 +0,0 @@
---
id: 587d7b87367417b2b2512b3f
title: Explore Differences Between the var and let Keywords
challengeType: 1
forumTopicId: 301202
dashedName: explore-differences-between-the-var-and-let-keywords
---
# --description--
One of the biggest problems with declaring variables with the `var` keyword is that you can overwrite variable declarations without an error.
```js
var camper = 'James';
var camper = 'David';
console.log(camper);
```
Here the console will display the string `David`.
As you can see in the code above, the `camper` variable is originally declared as `James` and then overridden to be `David`. In a small application, you might not run into this type of problem, but when your code becomes larger, you might accidentally overwrite a variable that you did not intend to overwrite. Because this behavior does not throw an error, searching and fixing bugs becomes more difficult.
A new keyword called `let` was introduced in ES6 to solve this potential issue with the `var` keyword. If you were to replace `var` with `let` in the variable declarations of the code above, the result would be an error.
```js
let camper = 'James';
let camper = 'David';
```
This error can be seen in the console of your browser. So unlike `var`, when using `let`, a variable with the same name can only be declared once. Note the `"use strict"`. This enables Strict Mode, which catches common coding mistakes and "unsafe" actions. For instance:
```js
"use strict";
x = 3.14;
```
This will display an error that `x is not defined`.
# --instructions--
Update the code so it only uses the `let` keyword.
# --hints--
`var` should not exist in the code.
```js
(getUserInput) => assert(!getUserInput('index').match(/var/g));
```
`catName` should be the string `Oliver`.
```js
assert(catName === 'Oliver');
```
`quote` should be the string `Oliver says Meow!`
```js
assert(quote === 'Oliver says Meow!');
```
# --seed--
## --seed-contents--
```js
var catName;
var quote;
function catTalk() {
"use strict";
catName = "Oliver";
quote = catName + " says Meow!";
}
catTalk();
```
# --solutions--
```js
let catName;
let quote;
function catTalk() {
'use strict';
catName = 'Oliver';
quote = catName + ' says Meow!';
}
catTalk();
```

View File

@ -8,6 +8,8 @@ dashedName: mutate-an-array-declared-with-const
# --description--
If you are unfamiliar with `const`, check out [this challenge](/learn/javascript-algorithms-and-data-structures/basic-javascript/declare-a-read-only-variable-with-the-const-keyword).
The `const` declaration has many use cases in modern JavaScript.
Some developers prefer to assign all their variables using `const` by default, unless they know they will need to reassign the value. Only in that case, they use `let`.

View File

@ -13,7 +13,7 @@ Functional programming is all about creating and using non-mutating functions.
The last challenge introduced the `concat` method as a way to combine arrays into a new one without mutating the original arrays. Compare `concat` to the `push` method. `push` adds an item to the end of the same array it is called on, which mutates that array. Here's an example:
```js
var arr = [1, 2, 3];
const arr = [1, 2, 3];
arr.push([4, 5, 6]);
```
@ -71,8 +71,9 @@ function nonMutatingPush(original, newItem) {
// Only change code above this line
}
var first = [1, 2, 3];
var second = [4, 5];
const first = [1, 2, 3];
const second = [4, 5];
nonMutatingPush(first, second);
```
@ -82,7 +83,6 @@ nonMutatingPush(first, second);
function nonMutatingPush(original, newItem) {
return original.concat(newItem);
}
var first = [1, 2, 3];
var second = [4, 5];
nonMutatingPush(first, second);
const first = [1, 2, 3];
const second = [4, 5];
```

View File

@ -77,7 +77,6 @@ function urlSlug(title) {
# --solutions--
```js
// Only change code below this line
function urlSlug(title) {
return title.trim().split(/\s+/).join("-").toLowerCase();
}

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