chore(i8n,learn): processed translations
This commit is contained in:
committed by
Mrugesh Mohapatra
parent
15047f2d90
commit
e5c44a3ae5
@ -0,0 +1,89 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392ca
|
||||
title: Access Array Data with Indexes
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cBZQbTz'
|
||||
forumTopicId: 16158
|
||||
dashedName: access-array-data-with-indexes
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
We can access the data inside arrays using <dfn>indexes</dfn>.
|
||||
|
||||
Array indexes are written in the same bracket notation that strings use, except that instead of specifying a character, they are specifying an entry in the array. Like strings, arrays use <dfn>zero-based</dfn> indexing, so the first element in an array has an index of `0`.
|
||||
|
||||
<br>
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
var array = [50,60,70];
|
||||
array[0]; // equals 50
|
||||
var data = array[1]; // equals 60
|
||||
```
|
||||
|
||||
**Note**
|
||||
There shouldn't be any spaces between the array name and the square brackets, like `array [0]`. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a variable called `myData` and set it to equal the first value of `myArray` using bracket notation.
|
||||
|
||||
# --hints--
|
||||
|
||||
The variable `myData` should equal the first value of `myArray`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
if (
|
||||
typeof myArray !== 'undefined' &&
|
||||
typeof myData !== 'undefined' &&
|
||||
myArray[0] === myData
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
The data in variable `myArray` should be accessed using bracket notation.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
if (code.match(/\s*=\s*myArray\[0\]/g)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myArray !== "undefined" && typeof myData !== "undefined"){(function(y,z){return 'myArray = ' + JSON.stringify(y) + ', myData = ' + JSON.stringify(z);})(myArray, myData);}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [50,60,70];
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [50,60,70];
|
||||
var myData = myArray[0];
|
||||
```
|
@ -0,0 +1,72 @@
|
||||
---
|
||||
id: 56592a60ddddeae28f7aa8e1
|
||||
title: Access Multi-Dimensional Arrays With Indexes
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ckND4Cq'
|
||||
forumTopicId: 16159
|
||||
dashedName: access-multi-dimensional-arrays-with-indexes
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
One way to think of a <dfn>multi-dimensional</dfn> array, is as an *array of arrays*. When you use brackets to access your array, the first set of brackets refers to the entries in the outer-most (the first level) array, and each additional pair of brackets refers to the next level of entries inside.
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
var arr = [
|
||||
[1,2,3],
|
||||
[4,5,6],
|
||||
[7,8,9],
|
||||
[[10,11,12], 13, 14]
|
||||
];
|
||||
arr[3]; // equals [[10,11,12], 13, 14]
|
||||
arr[3][0]; // equals [10,11,12]
|
||||
arr[3][0][1]; // equals 11
|
||||
```
|
||||
|
||||
**Note**
|
||||
There shouldn't be any spaces between the array name and the square brackets, like `array [0][0]` and even this `array [0] [0]` is not allowed. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Using bracket notation select an element from `myArray` such that `myData` is equal to `8`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myData` should be equal to `8`.
|
||||
|
||||
```js
|
||||
assert(myData === 8);
|
||||
```
|
||||
|
||||
You should be using bracket notation to read the correct value from `myArray`.
|
||||
|
||||
```js
|
||||
assert(/myData=myArray\[2\]\[1\]/.test(__helpers.removeWhiteSpace(code)));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myArray !== "undefined"){(function(){return "myData: " + myData + " myArray: " + JSON.stringify(myArray);})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [[1,2,3], [4,5,6], [7,8,9], [[10,11,12], 13, 14]];
|
||||
|
||||
// Only change code below this line
|
||||
var myData = myArray[0][0];
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [[1,2,3],[4,5,6], [7,8,9], [[10,11,12], 13, 14]];
|
||||
var myData = myArray[2][1];
|
||||
```
|
@ -0,0 +1,123 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244cd
|
||||
title: Accessing Nested Arrays
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cLeGDtZ'
|
||||
forumTopicId: 16160
|
||||
dashedName: accessing-nested-arrays
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
As we have seen in earlier examples, objects can contain both nested objects and nested arrays. Similar to accessing nested objects, Array bracket notation can be chained to access nested arrays.
|
||||
|
||||
Here is an example of how to access a nested array:
|
||||
|
||||
```js
|
||||
var ourPets = [
|
||||
{
|
||||
animalType: "cat",
|
||||
names: [
|
||||
"Meowzer",
|
||||
"Fluffy",
|
||||
"Kit-Cat"
|
||||
]
|
||||
},
|
||||
{
|
||||
animalType: "dog",
|
||||
names: [
|
||||
"Spot",
|
||||
"Bowser",
|
||||
"Frankie"
|
||||
]
|
||||
}
|
||||
];
|
||||
ourPets[0].names[1]; // "Fluffy"
|
||||
ourPets[1].names[0]; // "Spot"
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Retrieve the second tree from the variable `myPlants` using object dot and array bracket notation.
|
||||
|
||||
# --hints--
|
||||
|
||||
`secondTree` should equal "pine".
|
||||
|
||||
```js
|
||||
assert(secondTree === 'pine');
|
||||
```
|
||||
|
||||
Your code should use dot and bracket notation to access `myPlants`.
|
||||
|
||||
```js
|
||||
assert(/=\s*myPlants\[1\].list\[1\]/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(x) {
|
||||
if(typeof x != 'undefined') {
|
||||
return "secondTree = " + x;
|
||||
}
|
||||
return "secondTree is undefined";
|
||||
})(secondTree);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myPlants = [
|
||||
{
|
||||
type: "flowers",
|
||||
list: [
|
||||
"rose",
|
||||
"tulip",
|
||||
"dandelion"
|
||||
]
|
||||
},
|
||||
{
|
||||
type: "trees",
|
||||
list: [
|
||||
"fir",
|
||||
"pine",
|
||||
"birch"
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var secondTree = ""; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myPlants = [
|
||||
{
|
||||
type: "flowers",
|
||||
list: [
|
||||
"rose",
|
||||
"tulip",
|
||||
"dandelion"
|
||||
]
|
||||
},
|
||||
{
|
||||
type: "trees",
|
||||
list: [
|
||||
"fir",
|
||||
"pine",
|
||||
"birch"
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var secondTree = myPlants[1].list[1];
|
||||
```
|
@ -0,0 +1,98 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244cc
|
||||
title: Accessing Nested Objects
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cRnRnfa'
|
||||
forumTopicId: 16161
|
||||
dashedName: accessing-nested-objects
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The sub-properties of objects can be accessed by chaining together the dot or bracket notation.
|
||||
|
||||
Here is a nested object:
|
||||
|
||||
```js
|
||||
var ourStorage = {
|
||||
"desk": {
|
||||
"drawer": "stapler"
|
||||
},
|
||||
"cabinet": {
|
||||
"top drawer": {
|
||||
"folder1": "a file",
|
||||
"folder2": "secrets"
|
||||
},
|
||||
"bottom drawer": "soda"
|
||||
}
|
||||
};
|
||||
ourStorage.cabinet["top drawer"].folder2; // "secrets"
|
||||
ourStorage.desk.drawer; // "stapler"
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Access the `myStorage` object and assign the contents of the `glove box` property to the `gloveBoxContents` variable. Use dot notation for all properties where possible, otherwise use bracket notation.
|
||||
|
||||
# --hints--
|
||||
|
||||
`gloveBoxContents` should equal "maps".
|
||||
|
||||
```js
|
||||
assert(gloveBoxContents === 'maps');
|
||||
```
|
||||
|
||||
Your code should use dot and bracket notation to access `myStorage`.
|
||||
|
||||
```js
|
||||
assert(/=\s*myStorage\.car\.inside\[\s*("|')glove box\1\s*\]/g.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(x) {
|
||||
if(typeof x != 'undefined') {
|
||||
return "gloveBoxContents = " + x;
|
||||
}
|
||||
return "gloveBoxContents is undefined";
|
||||
})(gloveBoxContents);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myStorage = {
|
||||
"car": {
|
||||
"inside": {
|
||||
"glove box": "maps",
|
||||
"passenger seat": "crumbs"
|
||||
},
|
||||
"outside": {
|
||||
"trunk": "jack"
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
var gloveBoxContents = undefined; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myStorage = {
|
||||
"car":{
|
||||
"inside":{
|
||||
"glove box":"maps",
|
||||
"passenger seat":"crumbs"
|
||||
},
|
||||
"outside":{
|
||||
"trunk":"jack"
|
||||
}
|
||||
}
|
||||
};
|
||||
var gloveBoxContents = myStorage.car.inside["glove box"];
|
||||
```
|
@ -0,0 +1,101 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c8
|
||||
title: Accessing Object Properties with Bracket Notation
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cBvmEHP'
|
||||
forumTopicId: 16163
|
||||
dashedName: accessing-object-properties-with-bracket-notation
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The second way to access the properties of an object is bracket notation (`[]`). If the property of the object you are trying to access has a space in its name, you will need to use bracket notation.
|
||||
|
||||
However, you can still use bracket notation on object properties without spaces.
|
||||
|
||||
Here is a sample of using bracket notation to read an object's property:
|
||||
|
||||
```js
|
||||
var myObj = {
|
||||
"Space Name": "Kirk",
|
||||
"More Space": "Spock",
|
||||
"NoSpace": "USS Enterprise"
|
||||
};
|
||||
myObj["Space Name"]; // Kirk
|
||||
myObj['More Space']; // Spock
|
||||
myObj["NoSpace"]; // USS Enterprise
|
||||
```
|
||||
|
||||
Note that property names with spaces in them must be in quotes (single or double).
|
||||
|
||||
# --instructions--
|
||||
|
||||
Read the values of the properties `"an entree"` and `"the drink"` of `testObj` using bracket notation and assign them to `entreeValue` and `drinkValue` respectively.
|
||||
|
||||
# --hints--
|
||||
|
||||
`entreeValue` should be a string
|
||||
|
||||
```js
|
||||
assert(typeof entreeValue === 'string');
|
||||
```
|
||||
|
||||
The value of `entreeValue` should be `"hamburger"`
|
||||
|
||||
```js
|
||||
assert(entreeValue === 'hamburger');
|
||||
```
|
||||
|
||||
`drinkValue` should be a string
|
||||
|
||||
```js
|
||||
assert(typeof drinkValue === 'string');
|
||||
```
|
||||
|
||||
The value of `drinkValue` should be `"water"`
|
||||
|
||||
```js
|
||||
assert(drinkValue === 'water');
|
||||
```
|
||||
|
||||
You should use bracket notation twice
|
||||
|
||||
```js
|
||||
assert(code.match(/testObj\s*?\[('|")[^'"]+\1\]/g).length > 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a,b) { return "entreeValue = '" + a + "', drinkValue = '" + b + "'"; })(entreeValue,drinkValue);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var testObj = {
|
||||
"an entree": "hamburger",
|
||||
"my side": "veggies",
|
||||
"the drink": "water"
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var entreeValue = testObj; // Change this line
|
||||
var drinkValue = testObj; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var testObj = {
|
||||
"an entree": "hamburger",
|
||||
"my side": "veggies",
|
||||
"the drink": "water"
|
||||
};
|
||||
var entreeValue = testObj["an entree"];
|
||||
var drinkValue = testObj['the drink'];
|
||||
```
|
@ -0,0 +1,98 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c7
|
||||
title: Accessing Object Properties with Dot Notation
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cGryJs8'
|
||||
forumTopicId: 16164
|
||||
dashedName: accessing-object-properties-with-dot-notation
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
There are two ways to access the properties of an object: dot notation (`.`) and bracket notation (`[]`), similar to an array.
|
||||
|
||||
Dot notation is what you use when you know the name of the property you're trying to access ahead of time.
|
||||
|
||||
Here is a sample of using dot notation (`.`) to read an object's property:
|
||||
|
||||
```js
|
||||
var myObj = {
|
||||
prop1: "val1",
|
||||
prop2: "val2"
|
||||
};
|
||||
var prop1val = myObj.prop1; // val1
|
||||
var prop2val = myObj.prop2; // val2
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Read in the property values of `testObj` using dot notation. Set the variable `hatValue` equal to the object's property `hat` and set the variable `shirtValue` equal to the object's property `shirt`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`hatValue` should be a string
|
||||
|
||||
```js
|
||||
assert(typeof hatValue === 'string');
|
||||
```
|
||||
|
||||
The value of `hatValue` should be `"ballcap"`
|
||||
|
||||
```js
|
||||
assert(hatValue === 'ballcap');
|
||||
```
|
||||
|
||||
`shirtValue` should be a string
|
||||
|
||||
```js
|
||||
assert(typeof shirtValue === 'string');
|
||||
```
|
||||
|
||||
The value of `shirtValue` should be `"jersey"`
|
||||
|
||||
```js
|
||||
assert(shirtValue === 'jersey');
|
||||
```
|
||||
|
||||
You should use dot notation twice
|
||||
|
||||
```js
|
||||
assert(code.match(/testObj\.\w+/g).length > 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a,b) { return "hatValue = '" + a + "', shirtValue = '" + b + "'"; })(hatValue,shirtValue);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var testObj = {
|
||||
"hat": "ballcap",
|
||||
"shirt": "jersey",
|
||||
"shoes": "cleats"
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var hatValue = testObj; // Change this line
|
||||
var shirtValue = testObj; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var testObj = {
|
||||
"hat": "ballcap",
|
||||
"shirt": "jersey",
|
||||
"shoes": "cleats"
|
||||
};
|
||||
|
||||
var hatValue = testObj.hat;
|
||||
var shirtValue = testObj.shirt;
|
||||
```
|
@ -0,0 +1,117 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c9
|
||||
title: Accessing Object Properties with Variables
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cnQyKur'
|
||||
forumTopicId: 16165
|
||||
dashedName: accessing-object-properties-with-variables
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Another use of bracket notation on objects is to access a property which is stored as the value of a variable. This can be very useful for iterating through an object's properties or when accessing a lookup table.
|
||||
|
||||
Here is an example of using a variable to access a property:
|
||||
|
||||
```js
|
||||
var dogs = {
|
||||
Fido: "Mutt", Hunter: "Doberman", Snoopie: "Beagle"
|
||||
};
|
||||
var myDog = "Hunter";
|
||||
var myBreed = dogs[myDog];
|
||||
console.log(myBreed); // "Doberman"
|
||||
```
|
||||
|
||||
Another way you can use this concept is when the property's name is collected dynamically during the program execution, as follows:
|
||||
|
||||
```js
|
||||
var someObj = {
|
||||
propName: "John"
|
||||
};
|
||||
function propPrefix(str) {
|
||||
var s = "prop";
|
||||
return s + str;
|
||||
}
|
||||
var someProp = propPrefix("Name"); // someProp now holds the value 'propName'
|
||||
console.log(someObj[someProp]); // "John"
|
||||
```
|
||||
|
||||
Note that we do *not* use quotes around the variable name when using it to access the property because we are using the *value* of the variable, not the *name*.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Set the `playerNumber` variable to `16`. Then, use the variable to look up the player's name and assign it to `player`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`playerNumber` should be a number
|
||||
|
||||
```js
|
||||
assert(typeof playerNumber === 'number');
|
||||
```
|
||||
|
||||
The variable `player` should be a string
|
||||
|
||||
```js
|
||||
assert(typeof player === 'string');
|
||||
```
|
||||
|
||||
The value of `player` should be "Montana"
|
||||
|
||||
```js
|
||||
assert(player === 'Montana');
|
||||
```
|
||||
|
||||
You should use bracket notation to access `testObj`
|
||||
|
||||
```js
|
||||
assert(/testObj\s*?\[.*?\]/.test(code));
|
||||
```
|
||||
|
||||
You should not assign the value `Montana` to the variable `player` directly.
|
||||
|
||||
```js
|
||||
assert(!code.match(/player\s*=\s*"|\'\s*Montana\s*"|\'\s*;/gi));
|
||||
```
|
||||
|
||||
You should be using the variable `playerNumber` in your bracket notation
|
||||
|
||||
```js
|
||||
assert(/testObj\s*?\[\s*playerNumber\s*\]/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof player !== "undefined"){(function(v){return v;})(player);}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var testObj = {
|
||||
12: "Namath",
|
||||
16: "Montana",
|
||||
19: "Unitas"
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var playerNumber; // Change this line
|
||||
var player = testObj; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var testObj = {
|
||||
12: "Namath",
|
||||
16: "Montana",
|
||||
19: "Unitas"
|
||||
};
|
||||
var playerNumber = 16;
|
||||
var player = testObj[playerNumber];
|
||||
```
|
@ -0,0 +1,87 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392d2
|
||||
title: Add New Properties to a JavaScript Object
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cQe38UD'
|
||||
forumTopicId: 301169
|
||||
dashedName: add-new-properties-to-a-javascript-object
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
You can add new properties to existing JavaScript objects the same way you would modify them.
|
||||
|
||||
Here's how we would add a `"bark"` property to `ourDog`:
|
||||
|
||||
`ourDog.bark = "bow-wow";`
|
||||
|
||||
or
|
||||
|
||||
`ourDog["bark"] = "bow-wow";`
|
||||
|
||||
Now when we evaluate `ourDog.bark`, we'll get his bark, "bow-wow".
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
var ourDog = {
|
||||
"name": "Camper",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["everything!"]
|
||||
};
|
||||
|
||||
ourDog.bark = "bow-wow";
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add a `"bark"` property to `myDog` and set it to a dog sound, such as "woof". You may use either dot or bracket notation.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should add the property `"bark"` to `myDog`.
|
||||
|
||||
```js
|
||||
assert(myDog.bark !== undefined);
|
||||
```
|
||||
|
||||
You should not add `"bark"` to the setup section.
|
||||
|
||||
```js
|
||||
assert(!/bark[^\n]:/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return z;})(myDog);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myDog = {
|
||||
"name": "Happy Coder",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["freeCodeCamp Campers"]
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myDog = {
|
||||
"name": "Happy Coder",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["freeCodeCamp Campers"]
|
||||
};
|
||||
myDog.bark = "Woof Woof";
|
||||
```
|
@ -0,0 +1,60 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb3bdef
|
||||
title: Add Two Numbers with JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cM2KBAG'
|
||||
forumTopicId: 16650
|
||||
dashedName: add-two-numbers-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`Number` is a data type in JavaScript which represents numeric data.
|
||||
|
||||
Now let's try to add two numbers using JavaScript.
|
||||
|
||||
JavaScript uses the `+` symbol as an addition operator when placed between two numbers.
|
||||
|
||||
**Example:**
|
||||
|
||||
```js
|
||||
myVar = 5 + 10; // assigned 15
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the `0` so that sum will equal `20`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sum` should equal `20`.
|
||||
|
||||
```js
|
||||
assert(sum === 20);
|
||||
```
|
||||
|
||||
You should use the `+` operator.
|
||||
|
||||
```js
|
||||
assert(/\+/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return 'sum = '+z;})(sum);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var sum = 10 + 0;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var sum = 10 + 10;
|
||||
```
|
@ -0,0 +1,128 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244de
|
||||
title: Adding a Default Option in Switch Statements
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c3JvVfg'
|
||||
forumTopicId: 16653
|
||||
dashedName: adding-a-default-option-in-switch-statements
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In a `switch` statement you may not be able to specify all possible values as `case` statements. Instead, you can add the `default` statement which will be executed if no matching `case` statements are found. Think of it like the final `else` statement in an `if/else` chain.
|
||||
|
||||
A `default` statement should be the last case.
|
||||
|
||||
```js
|
||||
switch (num) {
|
||||
case value1:
|
||||
statement1;
|
||||
break;
|
||||
case value2:
|
||||
statement2;
|
||||
break;
|
||||
...
|
||||
default:
|
||||
defaultStatement;
|
||||
break;
|
||||
}
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a switch statement to set `answer` for the following conditions:
|
||||
`"a"` - "apple"
|
||||
`"b"` - "bird"
|
||||
`"c"` - "cat"
|
||||
`default` - "stuff"
|
||||
|
||||
# --hints--
|
||||
|
||||
`switchOfStuff("a")` should have a value of "apple"
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('a') === 'apple');
|
||||
```
|
||||
|
||||
`switchOfStuff("b")` should have a value of "bird"
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('b') === 'bird');
|
||||
```
|
||||
|
||||
`switchOfStuff("c")` should have a value of "cat"
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('c') === 'cat');
|
||||
```
|
||||
|
||||
`switchOfStuff("d")` should have a value of "stuff"
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('d') === 'stuff');
|
||||
```
|
||||
|
||||
`switchOfStuff(4)` should have a value of "stuff"
|
||||
|
||||
```js
|
||||
assert(switchOfStuff(4) === 'stuff');
|
||||
```
|
||||
|
||||
You should not use any `if` or `else` statements
|
||||
|
||||
```js
|
||||
assert(!/else/g.test(code) || !/if/g.test(code));
|
||||
```
|
||||
|
||||
You should use a `default` statement
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('string-to-trigger-default-case') === 'stuff');
|
||||
```
|
||||
|
||||
You should have at least 3 `break` statements
|
||||
|
||||
```js
|
||||
assert(code.match(/break/g).length > 2);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function switchOfStuff(val) {
|
||||
var answer = "";
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
return answer;
|
||||
}
|
||||
|
||||
switchOfStuff(1);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function switchOfStuff(val) {
|
||||
var answer = "";
|
||||
|
||||
switch(val) {
|
||||
case "a":
|
||||
answer = "apple";
|
||||
break;
|
||||
case "b":
|
||||
answer = "bird";
|
||||
break;
|
||||
case "c":
|
||||
answer = "cat";
|
||||
break;
|
||||
default:
|
||||
answer = "stuff";
|
||||
}
|
||||
return answer;
|
||||
}
|
||||
```
|
@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ed
|
||||
title: Appending Variables to Strings
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cbQmZfa'
|
||||
forumTopicId: 16656
|
||||
dashedName: appending-variables-to-strings
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Just as we can build a string over multiple lines out of string <dfn>literals</dfn>, we can also append variables to a string using the plus equals (`+=`) operator.
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
var anAdjective = "awesome!";
|
||||
var ourStr = "freeCodeCamp is ";
|
||||
ourStr += anAdjective;
|
||||
// ourStr is now "freeCodeCamp is awesome!"
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Set `someAdjective` to a string of at least 3 characters and append it to `myStr` using the `+=` operator.
|
||||
|
||||
# --hints--
|
||||
|
||||
`someAdjective` should be set to a string at least 3 characters long.
|
||||
|
||||
```js
|
||||
assert(typeof someAdjective !== 'undefined' && someAdjective.length > 2);
|
||||
```
|
||||
|
||||
You should append `someAdjective` to `myStr` using the `+=` operator.
|
||||
|
||||
```js
|
||||
assert(code.match(/myStr\s*\+=\s*someAdjective\s*/).length > 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){
|
||||
var output = [];
|
||||
if(typeof someAdjective === 'string') {
|
||||
output.push('someAdjective = "' + someAdjective + '"');
|
||||
} else {
|
||||
output.push('someAdjective is not a string');
|
||||
}
|
||||
if(typeof myStr === 'string') {
|
||||
output.push('myStr = "' + myStr + '"');
|
||||
} else {
|
||||
output.push('myStr is not a string');
|
||||
}
|
||||
return output.join('\n');
|
||||
})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Change code below this line
|
||||
|
||||
var someAdjective;
|
||||
var myStr = "Learning to code is ";
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var someAdjective = "neat";
|
||||
var myStr = "Learning to code is ";
|
||||
myStr += someAdjective;
|
||||
```
|
@ -0,0 +1,86 @@
|
||||
---
|
||||
id: 5ee127a03c3b35dd45426493
|
||||
title: Assigning the Value of One Variable to Another
|
||||
challengeType: 1
|
||||
videoUrl: ''
|
||||
forumTopicId: 418265
|
||||
dashedName: assigning-the-value-of-one-variable-to-another
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
After a value is assigned to a variable using the <dfn>assignment</dfn> operator, you can assign the value of that variable to another variable using the <dfn>assignment</dfn> operator.
|
||||
|
||||
```js
|
||||
var myVar;
|
||||
myVar = 5;
|
||||
var myNum;
|
||||
myNum = myVar;
|
||||
```
|
||||
|
||||
The above declares a `myVar` variable with no value, then assigns it the value `5`. Next, a variable named `myNum` is declared with no value. Then, the contents of `myVar` (which is `5`) is assigned to the variable `myNum`. Now, `myNum` also has the value of `5`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Assign the contents of `a` to variable `b`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should not change code above the specified comment.
|
||||
|
||||
```js
|
||||
assert(/var a;/.test(code) && /a = 7;/.test(code) && /var b;/.test(code));
|
||||
```
|
||||
|
||||
`b` should have a value of 7.
|
||||
|
||||
```js
|
||||
assert(typeof b === 'number' && b === 7);
|
||||
```
|
||||
|
||||
`a` should be assigned to `b` with `=`.
|
||||
|
||||
```js
|
||||
assert(/b\s*=\s*a\s*/g.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --before-user-code--
|
||||
|
||||
```js
|
||||
if (typeof a != 'undefined') {
|
||||
a = undefined;
|
||||
}
|
||||
if (typeof b != 'undefined') {
|
||||
b = undefined;
|
||||
}
|
||||
```
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a, b) {
|
||||
return 'a = ' + a + ', b = ' + b;
|
||||
})(a, b);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var a;
|
||||
a = 7;
|
||||
var b;
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var a;
|
||||
a = 7;
|
||||
var b;
|
||||
b = a;
|
||||
```
|
@ -0,0 +1,69 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c3
|
||||
title: Assignment with a Returned Value
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ce2pEtB'
|
||||
forumTopicId: 16658
|
||||
dashedName: assignment-with-a-returned-value
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
If you'll recall from our discussion of [Storing Values with the Assignment Operator](/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator), everything to the right of the equal sign is resolved before the value is assigned. This means we can take the return value of a function and assign it to a variable.
|
||||
|
||||
Assume we have pre-defined a function `sum` which adds two numbers together, then:
|
||||
|
||||
`ourSum = sum(5, 12);`
|
||||
|
||||
will call `sum` function, which returns a value of `17` and assigns it to `ourSum` variable.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Call the `processArg` function with an argument of `7` and assign its return value to the variable `processed`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`processed` should have a value of `2`
|
||||
|
||||
```js
|
||||
assert(processed === 2);
|
||||
```
|
||||
|
||||
You should assign `processArg` to `processed`
|
||||
|
||||
```js
|
||||
assert(/processed\s*=\s*processArg\(\s*7\s*\)/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){return "processed = " + processed})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var processed = 0;
|
||||
|
||||
function processArg(num) {
|
||||
return (num + 3) / 5;
|
||||
}
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var processed = 0;
|
||||
|
||||
function processArg(num) {
|
||||
return (num + 3) / 5;
|
||||
}
|
||||
|
||||
processed = processArg(7);
|
||||
```
|
@ -0,0 +1,159 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392d0
|
||||
title: Build JavaScript Objects
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cWGkbtd'
|
||||
forumTopicId: 16769
|
||||
dashedName: build-javascript-objects
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
You may have heard the term `object` before.
|
||||
|
||||
Objects are similar to `arrays`, except that instead of using indexes to access and modify their data, you access the data in objects through what are called `properties`.
|
||||
|
||||
Objects are useful for storing data in a structured way, and can represent real world objects, like a cat.
|
||||
|
||||
Here's a sample cat object:
|
||||
|
||||
```js
|
||||
var cat = {
|
||||
"name": "Whiskers",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"enemies": ["Water", "Dogs"]
|
||||
};
|
||||
```
|
||||
|
||||
In this example, all the properties are stored as strings, such as - `"name"`, `"legs"`, and `"tails"`. However, you can also use numbers as properties. You can even omit the quotes for single-word string properties, as follows:
|
||||
|
||||
```js
|
||||
var anotherObject = {
|
||||
make: "Ford",
|
||||
5: "five",
|
||||
"model": "focus"
|
||||
};
|
||||
```
|
||||
|
||||
However, if your object has any non-string properties, JavaScript will automatically typecast them as strings.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Make an object that represents a dog called `myDog` which contains the properties `"name"` (a string), `"legs"`, `"tails"` and `"friends"`.
|
||||
|
||||
You can set these object properties to whatever values you want, as long as `"name"` is a string, `"legs"` and `"tails"` are numbers, and `"friends"` is an array.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myDog` should contain the property `name` and it should be a `string`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (z) {
|
||||
if (
|
||||
z.hasOwnProperty('name') &&
|
||||
z.name !== undefined &&
|
||||
typeof z.name === 'string'
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(myDog)
|
||||
);
|
||||
```
|
||||
|
||||
`myDog` should contain the property `legs` and it should be a `number`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (z) {
|
||||
if (
|
||||
z.hasOwnProperty('legs') &&
|
||||
z.legs !== undefined &&
|
||||
typeof z.legs === 'number'
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(myDog)
|
||||
);
|
||||
```
|
||||
|
||||
`myDog` should contain the property `tails` and it should be a `number`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (z) {
|
||||
if (
|
||||
z.hasOwnProperty('tails') &&
|
||||
z.tails !== undefined &&
|
||||
typeof z.tails === 'number'
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(myDog)
|
||||
);
|
||||
```
|
||||
|
||||
`myDog` should contain the property `friends` and it should be an `array`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (z) {
|
||||
if (
|
||||
z.hasOwnProperty('friends') &&
|
||||
z.friends !== undefined &&
|
||||
Array.isArray(z.friends)
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(myDog)
|
||||
);
|
||||
```
|
||||
|
||||
`myDog` should only contain all the given properties.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (z) {
|
||||
return Object.keys(z).length === 4;
|
||||
})(myDog)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return z;})(myDog);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myDog = {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
};
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myDog = {
|
||||
"name": "Camper",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["everything!"]
|
||||
};
|
||||
```
|
@ -0,0 +1,149 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244dc
|
||||
title: Chaining If Else Statements
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/caeJgsw'
|
||||
forumTopicId: 16772
|
||||
dashedName: chaining-if-else-statements
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`if/else` statements can be chained together for complex logic. Here is <dfn>pseudocode</dfn> of multiple chained `if` / `else if` statements:
|
||||
|
||||
```js
|
||||
if (condition1) {
|
||||
statement1
|
||||
} else if (condition2) {
|
||||
statement2
|
||||
} else if (condition3) {
|
||||
statement3
|
||||
. . .
|
||||
} else {
|
||||
statementN
|
||||
}
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write chained `if`/`else if` statements to fulfill the following conditions:
|
||||
|
||||
`num < 5` - return "Tiny"
|
||||
`num < 10` - return "Small"
|
||||
`num < 15` - return "Medium"
|
||||
`num < 20` - return "Large"
|
||||
`num >= 20` - return "Huge"
|
||||
|
||||
# --hints--
|
||||
|
||||
You should have at least four `else` statements
|
||||
|
||||
```js
|
||||
assert(code.match(/else/g).length > 3);
|
||||
```
|
||||
|
||||
You should have at least four `if` statements
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length > 3);
|
||||
```
|
||||
|
||||
You should have at least one `return` statement
|
||||
|
||||
```js
|
||||
assert(code.match(/return/g).length >= 1);
|
||||
```
|
||||
|
||||
`testSize(0)` should return "Tiny"
|
||||
|
||||
```js
|
||||
assert(testSize(0) === 'Tiny');
|
||||
```
|
||||
|
||||
`testSize(4)` should return "Tiny"
|
||||
|
||||
```js
|
||||
assert(testSize(4) === 'Tiny');
|
||||
```
|
||||
|
||||
`testSize(5)` should return "Small"
|
||||
|
||||
```js
|
||||
assert(testSize(5) === 'Small');
|
||||
```
|
||||
|
||||
`testSize(8)` should return "Small"
|
||||
|
||||
```js
|
||||
assert(testSize(8) === 'Small');
|
||||
```
|
||||
|
||||
`testSize(10)` should return "Medium"
|
||||
|
||||
```js
|
||||
assert(testSize(10) === 'Medium');
|
||||
```
|
||||
|
||||
`testSize(14)` should return "Medium"
|
||||
|
||||
```js
|
||||
assert(testSize(14) === 'Medium');
|
||||
```
|
||||
|
||||
`testSize(15)` should return "Large"
|
||||
|
||||
```js
|
||||
assert(testSize(15) === 'Large');
|
||||
```
|
||||
|
||||
`testSize(17)` should return "Large"
|
||||
|
||||
```js
|
||||
assert(testSize(17) === 'Large');
|
||||
```
|
||||
|
||||
`testSize(20)` should return "Huge"
|
||||
|
||||
```js
|
||||
assert(testSize(20) === 'Huge');
|
||||
```
|
||||
|
||||
`testSize(25)` should return "Huge"
|
||||
|
||||
```js
|
||||
assert(testSize(25) === 'Huge');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testSize(num) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
return "Change Me";
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
testSize(7);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testSize(num) {
|
||||
if (num < 5) {
|
||||
return "Tiny";
|
||||
} else if (num < 10) {
|
||||
return "Small";
|
||||
} else if (num < 15) {
|
||||
return "Medium";
|
||||
} else if (num < 20) {
|
||||
return "Large";
|
||||
} else {
|
||||
return "Huge";
|
||||
}
|
||||
}
|
||||
```
|
@ -0,0 +1,61 @@
|
||||
---
|
||||
id: bd7123c9c441eddfaeb4bdef
|
||||
title: Comment Your JavaScript Code
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c7ynnTp'
|
||||
forumTopicId: 16783
|
||||
dashedName: comment-your-javascript-code
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Comments are lines of code that JavaScript will intentionally ignore. Comments are a great way to leave notes to yourself and to other people who will later need to figure out what that code does.
|
||||
|
||||
There are two ways to write comments in JavaScript:
|
||||
|
||||
Using `//` will tell JavaScript to ignore the remainder of the text on the current line:
|
||||
|
||||
```js
|
||||
// This is an in-line comment.
|
||||
```
|
||||
|
||||
You can make a multi-line comment beginning with `/*` and ending with `*/`:
|
||||
|
||||
```js
|
||||
/* This is a
|
||||
multi-line comment */
|
||||
```
|
||||
|
||||
**Best Practice**
|
||||
As you write code, you should regularly add comments to clarify the function of parts of your code. Good commenting can help communicate the intent of your code—both for others *and* for your future self.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Try creating one of each type of comment.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should create a `//` style comment that contains at least five letters.
|
||||
|
||||
```js
|
||||
assert(code.match(/(\/\/)...../g));
|
||||
```
|
||||
|
||||
You should create a `/* */` style comment that contains at least five letters.
|
||||
|
||||
```js
|
||||
assert(code.match(/(\/\*)([^\/]{5,})(?=\*\/)/gm));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
```js
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// Fake Comment
|
||||
/* Another Comment */
|
||||
```
|
@ -0,0 +1,89 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d0
|
||||
title: Comparison with the Equality Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cKyVMAL'
|
||||
forumTopicId: 16784
|
||||
dashedName: comparison-with-the-equality-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
There are many <dfn>comparison operators</dfn> in JavaScript. All of these operators return a boolean `true` or `false` value.
|
||||
|
||||
The most basic operator is the equality operator `==`. The equality operator compares two values and returns `true` if they're equivalent or `false` if they are not. Note that equality is different from assignment (`=`), which assigns the value on the right of the operator to a variable on the left.
|
||||
|
||||
```js
|
||||
function equalityTest(myVal) {
|
||||
if (myVal == 10) {
|
||||
return "Equal";
|
||||
}
|
||||
return "Not Equal";
|
||||
}
|
||||
```
|
||||
|
||||
If `myVal` is equal to `10`, the equality operator returns `true`, so the code in the curly braces will execute, and the function will return `"Equal"`. Otherwise, the function will return `"Not Equal"`. In order for JavaScript to compare two different <dfn>data types</dfn> (for example, `numbers` and `strings`), it must convert one type to another. This is known as "Type Coercion". Once it does, however, it can compare terms as follows:
|
||||
|
||||
```js
|
||||
1 == 1 // true
|
||||
1 == 2 // false
|
||||
1 == '1' // true
|
||||
"3" == 3 // true
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the equality operator to the indicated line so that the function will return "Equal" when `val` is equivalent to `12`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`testEqual(10)` should return "Not Equal"
|
||||
|
||||
```js
|
||||
assert(testEqual(10) === 'Not Equal');
|
||||
```
|
||||
|
||||
`testEqual(12)` should return "Equal"
|
||||
|
||||
```js
|
||||
assert(testEqual(12) === 'Equal');
|
||||
```
|
||||
|
||||
`testEqual("12")` should return "Equal"
|
||||
|
||||
```js
|
||||
assert(testEqual('12') === 'Equal');
|
||||
```
|
||||
|
||||
You should use the `==` operator
|
||||
|
||||
```js
|
||||
assert(code.match(/==/g) && !code.match(/===/g));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
function testEqual(val) {
|
||||
if (val) { // Change this line
|
||||
return "Equal";
|
||||
}
|
||||
return "Not Equal";
|
||||
}
|
||||
|
||||
testEqual(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testEqual(val) {
|
||||
if (val == 12) {
|
||||
return "Equal";
|
||||
}
|
||||
return "Not Equal";
|
||||
}
|
||||
```
|
@ -0,0 +1,111 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d4
|
||||
title: Comparison with the Greater Than Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cp6GbH4'
|
||||
forumTopicId: 16786
|
||||
dashedName: comparison-with-the-greater-than-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The greater than operator (`>`) compares the values of two numbers. If the number to the left is greater than the number to the right, it returns `true`. Otherwise, it returns `false`.
|
||||
|
||||
Like the equality operator, greater than operator will convert data types of values while comparing.
|
||||
|
||||
**Examples**
|
||||
|
||||
```js
|
||||
5 > 3 // true
|
||||
7 > '3' // true
|
||||
2 > 3 // false
|
||||
'1' > 9 // false
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the greater than operator to the indicated lines so that the return statements make sense.
|
||||
|
||||
# --hints--
|
||||
|
||||
`testGreaterThan(0)` should return "10 or Under"
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(0) === '10 or Under');
|
||||
```
|
||||
|
||||
`testGreaterThan(10)` should return "10 or Under"
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(10) === '10 or Under');
|
||||
```
|
||||
|
||||
`testGreaterThan(11)` should return "Over 10"
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(11) === 'Over 10');
|
||||
```
|
||||
|
||||
`testGreaterThan(99)` should return "Over 10"
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(99) === 'Over 10');
|
||||
```
|
||||
|
||||
`testGreaterThan(100)` should return "Over 10"
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(100) === 'Over 10');
|
||||
```
|
||||
|
||||
`testGreaterThan(101)` should return "Over 100"
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(101) === 'Over 100');
|
||||
```
|
||||
|
||||
`testGreaterThan(150)` should return "Over 100"
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(150) === 'Over 100');
|
||||
```
|
||||
|
||||
You should use the `>` operator at least twice
|
||||
|
||||
```js
|
||||
assert(code.match(/val\s*>\s*('|")*\d+('|")*/g).length > 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testGreaterThan(val) {
|
||||
if (val) { // Change this line
|
||||
return "Over 100";
|
||||
}
|
||||
|
||||
if (val) { // Change this line
|
||||
return "Over 10";
|
||||
}
|
||||
|
||||
return "10 or Under";
|
||||
}
|
||||
|
||||
testGreaterThan(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testGreaterThan(val) {
|
||||
if (val > 100) { // Change this line
|
||||
return "Over 100";
|
||||
}
|
||||
if (val > 10) { // Change this line
|
||||
return "Over 10";
|
||||
}
|
||||
return "10 or Under";
|
||||
}
|
||||
```
|
@ -0,0 +1,113 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d5
|
||||
title: Comparison with the Greater Than Or Equal To Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c6KBqtV'
|
||||
forumTopicId: 16785
|
||||
dashedName: comparison-with-the-greater-than-or-equal-to-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The greater than or equal to operator (`>=`) compares the values of two numbers. If the number to the left is greater than or equal to the number to the right, it returns `true`. Otherwise, it returns `false`.
|
||||
|
||||
Like the equality operator, `greater than or equal to` operator will convert data types while comparing.
|
||||
|
||||
**Examples**
|
||||
|
||||
```js
|
||||
6 >= 6 // true
|
||||
7 >= '3' // true
|
||||
2 >= 3 // false
|
||||
'7' >= 9 // false
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the greater than or equal to operator to the indicated lines so that the return statements make sense.
|
||||
|
||||
# --hints--
|
||||
|
||||
`testGreaterOrEqual(0)` should return "Less than 10"
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(0) === 'Less than 10');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(9)` should return "Less than 10"
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(9) === 'Less than 10');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(10)` should return "10 or Over"
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(10) === '10 or Over');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(11)` should return "10 or Over"
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(11) === '10 or Over');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(19)` should return "10 or Over"
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(19) === '10 or Over');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(100)` should return "20 or Over"
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(100) === '20 or Over');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(21)` should return "20 or Over"
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(21) === '20 or Over');
|
||||
```
|
||||
|
||||
You should use the `>=` operator at least twice
|
||||
|
||||
```js
|
||||
assert(code.match(/val\s*>=\s*('|")*\d+('|")*/g).length > 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testGreaterOrEqual(val) {
|
||||
if (val) { // Change this line
|
||||
return "20 or Over";
|
||||
}
|
||||
|
||||
if (val) { // Change this line
|
||||
return "10 or Over";
|
||||
}
|
||||
|
||||
return "Less than 10";
|
||||
}
|
||||
|
||||
testGreaterOrEqual(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testGreaterOrEqual(val) {
|
||||
if (val >= 20) { // Change this line
|
||||
return "20 or Over";
|
||||
}
|
||||
|
||||
if (val >= 10) { // Change this line
|
||||
return "10 or Over";
|
||||
}
|
||||
|
||||
return "Less than 10";
|
||||
}
|
||||
```
|
@ -0,0 +1,91 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d2
|
||||
title: Comparison with the Inequality Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cdBm9Sr'
|
||||
forumTopicId: 16787
|
||||
dashedName: comparison-with-the-inequality-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The inequality operator (`!=`) is the opposite of the equality operator. It means "Not Equal" and returns `false` where equality would return `true` and *vice versa*. Like the equality operator, the inequality operator will convert data types of values while comparing.
|
||||
|
||||
**Examples**
|
||||
|
||||
```js
|
||||
1 != 2 // true
|
||||
1 != "1" // false
|
||||
1 != '1' // false
|
||||
1 != true // false
|
||||
0 != false // false
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the inequality operator `!=` in the `if` statement so that the function will return "Not Equal" when `val` is not equivalent to `99`
|
||||
|
||||
# --hints--
|
||||
|
||||
`testNotEqual(99)` should return "Equal"
|
||||
|
||||
```js
|
||||
assert(testNotEqual(99) === 'Equal');
|
||||
```
|
||||
|
||||
`testNotEqual("99")` should return "Equal"
|
||||
|
||||
```js
|
||||
assert(testNotEqual('99') === 'Equal');
|
||||
```
|
||||
|
||||
`testNotEqual(12)` should return "Not Equal"
|
||||
|
||||
```js
|
||||
assert(testNotEqual(12) === 'Not Equal');
|
||||
```
|
||||
|
||||
`testNotEqual("12")` should return "Not Equal"
|
||||
|
||||
```js
|
||||
assert(testNotEqual('12') === 'Not Equal');
|
||||
```
|
||||
|
||||
`testNotEqual("bob")` should return "Not Equal"
|
||||
|
||||
```js
|
||||
assert(testNotEqual('bob') === 'Not Equal');
|
||||
```
|
||||
|
||||
You should use the `!=` operator
|
||||
|
||||
```js
|
||||
assert(code.match(/(?!!==)!=/));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
function testNotEqual(val) {
|
||||
if (val) { // Change this line
|
||||
return "Not Equal";
|
||||
}
|
||||
return "Equal";
|
||||
}
|
||||
|
||||
testNotEqual(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testNotEqual(val) {
|
||||
if (val != 99) {
|
||||
return "Not Equal";
|
||||
}
|
||||
return "Equal";
|
||||
}
|
||||
```
|
@ -0,0 +1,106 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d6
|
||||
title: Comparison with the Less Than Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cNVRWtB'
|
||||
forumTopicId: 16789
|
||||
dashedName: comparison-with-the-less-than-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The <dfn>less than</dfn> operator (`<`) compares the values of two numbers. If the number to the left is less than the number to the right, it returns `true`. Otherwise, it returns `false`. Like the equality operator, <dfn>less than</dfn> operator converts data types while comparing.
|
||||
|
||||
**Examples**
|
||||
|
||||
```js
|
||||
2 < 5 // true
|
||||
'3' < 7 // true
|
||||
5 < 5 // false
|
||||
3 < 2 // false
|
||||
'8' < 4 // false
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the less than operator to the indicated lines so that the return statements make sense.
|
||||
|
||||
# --hints--
|
||||
|
||||
`testLessThan(0)` should return "Under 25"
|
||||
|
||||
```js
|
||||
assert(testLessThan(0) === 'Under 25');
|
||||
```
|
||||
|
||||
`testLessThan(24)` should return "Under 25"
|
||||
|
||||
```js
|
||||
assert(testLessThan(24) === 'Under 25');
|
||||
```
|
||||
|
||||
`testLessThan(25)` should return "Under 55"
|
||||
|
||||
```js
|
||||
assert(testLessThan(25) === 'Under 55');
|
||||
```
|
||||
|
||||
`testLessThan(54)` should return "Under 55"
|
||||
|
||||
```js
|
||||
assert(testLessThan(54) === 'Under 55');
|
||||
```
|
||||
|
||||
`testLessThan(55)` should return "55 or Over"
|
||||
|
||||
```js
|
||||
assert(testLessThan(55) === '55 or Over');
|
||||
```
|
||||
|
||||
`testLessThan(99)` should return "55 or Over"
|
||||
|
||||
```js
|
||||
assert(testLessThan(99) === '55 or Over');
|
||||
```
|
||||
|
||||
You should use the `<` operator at least twice
|
||||
|
||||
```js
|
||||
assert(code.match(/val\s*<\s*('|")*\d+('|")*/g).length > 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testLessThan(val) {
|
||||
if (val) { // Change this line
|
||||
return "Under 25";
|
||||
}
|
||||
|
||||
if (val) { // Change this line
|
||||
return "Under 55";
|
||||
}
|
||||
|
||||
return "55 or Over";
|
||||
}
|
||||
|
||||
testLessThan(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testLessThan(val) {
|
||||
if (val < 25) { // Change this line
|
||||
return "Under 25";
|
||||
}
|
||||
|
||||
if (val < 55) { // Change this line
|
||||
return "Under 55";
|
||||
}
|
||||
|
||||
return "55 or Over";
|
||||
}
|
||||
```
|
@ -0,0 +1,112 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d7
|
||||
title: Comparison with the Less Than Or Equal To Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cNVR7Am'
|
||||
forumTopicId: 16788
|
||||
dashedName: comparison-with-the-less-than-or-equal-to-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The less than or equal to operator (`<=`) compares the values of two numbers. If the number to the left is less than or equal to the number to the right, it returns `true`. If the number on the left is greater than the number on the right, it returns `false`. Like the equality operator, `less than or equal to` converts data types.
|
||||
|
||||
**Examples**
|
||||
|
||||
```js
|
||||
4 <= 5 // true
|
||||
'7' <= 7 // true
|
||||
5 <= 5 // true
|
||||
3 <= 2 // false
|
||||
'8' <= 4 // false
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the less than or equal to operator to the indicated lines so that the return statements make sense.
|
||||
|
||||
# --hints--
|
||||
|
||||
`testLessOrEqual(0)` should return "Smaller Than or Equal to 12"
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(0) === 'Smaller Than or Equal to 12');
|
||||
```
|
||||
|
||||
`testLessOrEqual(11)` should return "Smaller Than or Equal to 12"
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(11) === 'Smaller Than or Equal to 12');
|
||||
```
|
||||
|
||||
`testLessOrEqual(12)` should return "Smaller Than or Equal to 12"
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(12) === 'Smaller Than or Equal to 12');
|
||||
```
|
||||
|
||||
`testLessOrEqual(23)` should return "Smaller Than or Equal to 24"
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(23) === 'Smaller Than or Equal to 24');
|
||||
```
|
||||
|
||||
`testLessOrEqual(24)` should return "Smaller Than or Equal to 24"
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(24) === 'Smaller Than or Equal to 24');
|
||||
```
|
||||
|
||||
`testLessOrEqual(25)` should return "More Than 24"
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(25) === 'More Than 24');
|
||||
```
|
||||
|
||||
`testLessOrEqual(55)` should return "More Than 24"
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(55) === 'More Than 24');
|
||||
```
|
||||
|
||||
You should use the `<=` operator at least twice
|
||||
|
||||
```js
|
||||
assert(code.match(/val\s*<=\s*('|")*\d+('|")*/g).length > 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testLessOrEqual(val) {
|
||||
if (val) { // Change this line
|
||||
return "Smaller Than or Equal to 12";
|
||||
}
|
||||
|
||||
if (val) { // Change this line
|
||||
return "Smaller Than or Equal to 24";
|
||||
}
|
||||
|
||||
return "More Than 24";
|
||||
}
|
||||
|
||||
testLessOrEqual(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testLessOrEqual(val) {
|
||||
if (val <= 12) { // Change this line
|
||||
return "Smaller Than or Equal to 12";
|
||||
}
|
||||
|
||||
if (val <= 24) { // Change this line
|
||||
return "Smaller Than or Equal to 24";
|
||||
}
|
||||
|
||||
return "More Than 24";
|
||||
}
|
||||
```
|
@ -0,0 +1,80 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d1
|
||||
title: Comparison with the Strict Equality Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cy87atr'
|
||||
forumTopicId: 16790
|
||||
dashedName: comparison-with-the-strict-equality-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Strict equality (`===`) is the counterpart to the equality operator (`==`). However, unlike the equality operator, which attempts to convert both values being compared to a common type, the strict equality operator does not perform a type conversion.
|
||||
|
||||
If the values being compared have different types, they are considered unequal, and the strict equality operator will return false.
|
||||
|
||||
**Examples**
|
||||
|
||||
```js
|
||||
3 === 3 // true
|
||||
3 === '3' // false
|
||||
```
|
||||
|
||||
In the second example, `3` is a `Number` type and `'3'` is a `String` type.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the strict equality operator in the `if` statement so the function will return "Equal" when `val` is strictly equal to `7`
|
||||
|
||||
# --hints--
|
||||
|
||||
`testStrict(10)` should return "Not Equal"
|
||||
|
||||
```js
|
||||
assert(testStrict(10) === 'Not Equal');
|
||||
```
|
||||
|
||||
`testStrict(7)` should return "Equal"
|
||||
|
||||
```js
|
||||
assert(testStrict(7) === 'Equal');
|
||||
```
|
||||
|
||||
`testStrict("7")` should return "Not Equal"
|
||||
|
||||
```js
|
||||
assert(testStrict('7') === 'Not Equal');
|
||||
```
|
||||
|
||||
You should use the `===` operator
|
||||
|
||||
```js
|
||||
assert(code.match(/(val\s*===\s*\d+)|(\d+\s*===\s*val)/g).length > 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
function testStrict(val) {
|
||||
if (val) { // Change this line
|
||||
return "Equal";
|
||||
}
|
||||
return "Not Equal";
|
||||
}
|
||||
|
||||
testStrict(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testStrict(val) {
|
||||
if (val === 7) {
|
||||
return "Equal";
|
||||
}
|
||||
return "Not Equal";
|
||||
}
|
||||
```
|
@ -0,0 +1,83 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d3
|
||||
title: Comparison with the Strict Inequality Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cKekkUy'
|
||||
forumTopicId: 16791
|
||||
dashedName: comparison-with-the-strict-inequality-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The strict inequality operator (`!==`) is the logical opposite of the strict equality operator. It means "Strictly Not Equal" and returns `false` where strict equality would return `true` and *vice versa*. Strict inequality will not convert data types.
|
||||
|
||||
**Examples**
|
||||
|
||||
```js
|
||||
3 !== 3 // false
|
||||
3 !== '3' // true
|
||||
4 !== 3 // true
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the strict inequality operator to the `if` statement so the function will return "Not Equal" when `val` is not strictly equal to `17`
|
||||
|
||||
# --hints--
|
||||
|
||||
`testStrictNotEqual(17)` should return "Equal"
|
||||
|
||||
```js
|
||||
assert(testStrictNotEqual(17) === 'Equal');
|
||||
```
|
||||
|
||||
`testStrictNotEqual("17")` should return "Not Equal"
|
||||
|
||||
```js
|
||||
assert(testStrictNotEqual('17') === 'Not Equal');
|
||||
```
|
||||
|
||||
`testStrictNotEqual(12)` should return "Not Equal"
|
||||
|
||||
```js
|
||||
assert(testStrictNotEqual(12) === 'Not Equal');
|
||||
```
|
||||
|
||||
`testStrictNotEqual("bob")` should return "Not Equal"
|
||||
|
||||
```js
|
||||
assert(testStrictNotEqual('bob') === 'Not Equal');
|
||||
```
|
||||
|
||||
You should use the `!==` operator
|
||||
|
||||
```js
|
||||
assert(code.match(/(val\s*!==\s*\d+)|(\d+\s*!==\s*val)/g).length > 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
function testStrictNotEqual(val) {
|
||||
if (val) { // Change this line
|
||||
return "Not Equal";
|
||||
}
|
||||
return "Equal";
|
||||
}
|
||||
|
||||
testStrictNotEqual(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testStrictNotEqual(val) {
|
||||
if (val !== 17) {
|
||||
return "Not Equal";
|
||||
}
|
||||
return "Equal";
|
||||
}
|
||||
```
|
@ -0,0 +1,130 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d8
|
||||
title: Comparisons with the Logical And Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cvbRVtr'
|
||||
forumTopicId: 16799
|
||||
dashedName: comparisons-with-the-logical-and-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Sometimes you will need to test more than one thing at a time. The <dfn>logical and</dfn> operator (`&&`) returns `true` if and only if the <dfn>operands</dfn> to the left and right of it are true.
|
||||
|
||||
The same effect could be achieved by nesting an if statement inside another if:
|
||||
|
||||
```js
|
||||
if (num > 5) {
|
||||
if (num < 10) {
|
||||
return "Yes";
|
||||
}
|
||||
}
|
||||
return "No";
|
||||
```
|
||||
|
||||
will only return "Yes" if `num` is greater than `5` and less than `10`. The same logic can be written as:
|
||||
|
||||
```js
|
||||
if (num > 5 && num < 10) {
|
||||
return "Yes";
|
||||
}
|
||||
return "No";
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Replace the two if statements with one statement, using the && operator, which will return `"Yes"` if `val` is less than or equal to `50` and greater than or equal to `25`. Otherwise, will return `"No"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should use the `&&` operator once
|
||||
|
||||
```js
|
||||
assert(code.match(/&&/g).length === 1);
|
||||
```
|
||||
|
||||
You should only have one `if` statement
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length === 1);
|
||||
```
|
||||
|
||||
`testLogicalAnd(0)` should return "No"
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(0) === 'No');
|
||||
```
|
||||
|
||||
`testLogicalAnd(24)` should return "No"
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(24) === 'No');
|
||||
```
|
||||
|
||||
`testLogicalAnd(25)` should return "Yes"
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(25) === 'Yes');
|
||||
```
|
||||
|
||||
`testLogicalAnd(30)` should return "Yes"
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(30) === 'Yes');
|
||||
```
|
||||
|
||||
`testLogicalAnd(50)` should return "Yes"
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(50) === 'Yes');
|
||||
```
|
||||
|
||||
`testLogicalAnd(51)` should return "No"
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(51) === 'No');
|
||||
```
|
||||
|
||||
`testLogicalAnd(75)` should return "No"
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(75) === 'No');
|
||||
```
|
||||
|
||||
`testLogicalAnd(80)` should return "No"
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(80) === 'No');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testLogicalAnd(val) {
|
||||
// Only change code below this line
|
||||
|
||||
if (val) {
|
||||
if (val) {
|
||||
return "Yes";
|
||||
}
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
return "No";
|
||||
}
|
||||
|
||||
testLogicalAnd(10);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testLogicalAnd(val) {
|
||||
if (val >= 25 && val <= 50) {
|
||||
return "Yes";
|
||||
}
|
||||
return "No";
|
||||
}
|
||||
```
|
@ -0,0 +1,135 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d9
|
||||
title: Comparisons with the Logical Or Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cEPrGTN'
|
||||
forumTopicId: 16800
|
||||
dashedName: comparisons-with-the-logical-or-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The <dfn>logical or</dfn> operator (`||`) returns `true` if either of the <dfn>operands</dfn> is `true`. Otherwise, it returns `false`.
|
||||
|
||||
The <dfn>logical or</dfn> operator is composed of two pipe symbols: (`||`). This can typically be found between your Backspace and Enter keys.
|
||||
|
||||
The pattern below should look familiar from prior waypoints:
|
||||
|
||||
```js
|
||||
if (num > 10) {
|
||||
return "No";
|
||||
}
|
||||
if (num < 5) {
|
||||
return "No";
|
||||
}
|
||||
return "Yes";
|
||||
```
|
||||
|
||||
will return "Yes" only if `num` is between `5` and `10` (5 and 10 included). The same logic can be written as:
|
||||
|
||||
```js
|
||||
if (num > 10 || num < 5) {
|
||||
return "No";
|
||||
}
|
||||
return "Yes";
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Combine the two `if` statements into one statement which returns `"Outside"` if `val` is not between `10` and `20`, inclusive. Otherwise, return `"Inside"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should use the `||` operator once
|
||||
|
||||
```js
|
||||
assert(code.match(/\|\|/g).length === 1);
|
||||
```
|
||||
|
||||
You should only have one `if` statement
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length === 1);
|
||||
```
|
||||
|
||||
`testLogicalOr(0)` should return "Outside"
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(0) === 'Outside');
|
||||
```
|
||||
|
||||
`testLogicalOr(9)` should return "Outside"
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(9) === 'Outside');
|
||||
```
|
||||
|
||||
`testLogicalOr(10)` should return "Inside"
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(10) === 'Inside');
|
||||
```
|
||||
|
||||
`testLogicalOr(15)` should return "Inside"
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(15) === 'Inside');
|
||||
```
|
||||
|
||||
`testLogicalOr(19)` should return "Inside"
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(19) === 'Inside');
|
||||
```
|
||||
|
||||
`testLogicalOr(20)` should return "Inside"
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(20) === 'Inside');
|
||||
```
|
||||
|
||||
`testLogicalOr(21)` should return "Outside"
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(21) === 'Outside');
|
||||
```
|
||||
|
||||
`testLogicalOr(25)` should return "Outside"
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(25) === 'Outside');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testLogicalOr(val) {
|
||||
// Only change code below this line
|
||||
|
||||
if (val) {
|
||||
return "Outside";
|
||||
}
|
||||
|
||||
if (val) {
|
||||
return "Outside";
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
return "Inside";
|
||||
}
|
||||
|
||||
testLogicalOr(15);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testLogicalOr(val) {
|
||||
if (val < 10 || val > 20) {
|
||||
return "Outside";
|
||||
}
|
||||
return "Inside";
|
||||
}
|
||||
```
|
@ -0,0 +1,97 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244af
|
||||
title: Compound Assignment With Augmented Addition
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cDR6LCb'
|
||||
forumTopicId: 16661
|
||||
dashedName: compound-assignment-with-augmented-addition
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In programming, it is common to use assignments to modify the contents of a variable. Remember that everything to the right of the equals sign is evaluated first, so we can say:
|
||||
|
||||
`myVar = myVar + 5;`
|
||||
|
||||
to add `5` to `myVar`. Since this is such a common pattern, there are operators which do both a mathematical operation and assignment in one step.
|
||||
|
||||
One such operator is the `+=` operator.
|
||||
|
||||
```js
|
||||
var myVar = 1;
|
||||
myVar += 5;
|
||||
console.log(myVar); // Returns 6
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Convert the assignments for `a`, `b`, and `c` to use the `+=` operator.
|
||||
|
||||
# --hints--
|
||||
|
||||
`a` should equal `15`.
|
||||
|
||||
```js
|
||||
assert(a === 15);
|
||||
```
|
||||
|
||||
`b` should equal `26`.
|
||||
|
||||
```js
|
||||
assert(b === 26);
|
||||
```
|
||||
|
||||
`c` should equal `19`.
|
||||
|
||||
```js
|
||||
assert(c === 19);
|
||||
```
|
||||
|
||||
You should use the `+=` operator for each variable.
|
||||
|
||||
```js
|
||||
assert(code.match(/\+=/g).length === 3);
|
||||
```
|
||||
|
||||
You should not modify the code above the specified comment.
|
||||
|
||||
```js
|
||||
assert(
|
||||
/var a = 3;/.test(code) &&
|
||||
/var b = 17;/.test(code) &&
|
||||
/var c = 12;/.test(code)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a,b,c){ return "a = " + a + ", b = " + b + ", c = " + c; })(a,b,c);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var a = 3;
|
||||
var b = 17;
|
||||
var c = 12;
|
||||
|
||||
// Only change code below this line
|
||||
a = a + 12;
|
||||
b = 9 + b;
|
||||
c = c + 7;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var a = 3;
|
||||
var b = 17;
|
||||
var c = 12;
|
||||
|
||||
a += 12;
|
||||
b += 9;
|
||||
c += 7;
|
||||
```
|
@ -0,0 +1,91 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b2
|
||||
title: Compound Assignment With Augmented Division
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2QvKT2'
|
||||
forumTopicId: 16659
|
||||
dashedName: compound-assignment-with-augmented-division
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The `/=` operator divides a variable by another number.
|
||||
|
||||
`myVar = myVar / 5;`
|
||||
|
||||
Will divide `myVar` by `5`. This can be rewritten as:
|
||||
|
||||
`myVar /= 5;`
|
||||
|
||||
# --instructions--
|
||||
|
||||
Convert the assignments for `a`, `b`, and `c` to use the `/=` operator.
|
||||
|
||||
# --hints--
|
||||
|
||||
`a` should equal `4`.
|
||||
|
||||
```js
|
||||
assert(a === 4);
|
||||
```
|
||||
|
||||
`b` should equal `27`.
|
||||
|
||||
```js
|
||||
assert(b === 27);
|
||||
```
|
||||
|
||||
`c` should equal `3`.
|
||||
|
||||
```js
|
||||
assert(c === 3);
|
||||
```
|
||||
|
||||
You should use the `/=` operator for each variable.
|
||||
|
||||
```js
|
||||
assert(code.match(/\/=/g).length === 3);
|
||||
```
|
||||
|
||||
You should not modify the code above the specified comment.
|
||||
|
||||
```js
|
||||
assert(
|
||||
/var a = 48;/.test(code) &&
|
||||
/var b = 108;/.test(code) &&
|
||||
/var c = 33;/.test(code)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a,b,c){ return "a = " + a + ", b = " + b + ", c = " + c; })(a,b,c);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var a = 48;
|
||||
var b = 108;
|
||||
var c = 33;
|
||||
|
||||
// Only change code below this line
|
||||
a = a / 12;
|
||||
b = b / 4;
|
||||
c = c / 11;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var a = 48;
|
||||
var b = 108;
|
||||
var c = 33;
|
||||
|
||||
a /= 12;
|
||||
b /= 4;
|
||||
c /= 11;
|
||||
```
|
@ -0,0 +1,91 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b1
|
||||
title: Compound Assignment With Augmented Multiplication
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c83vrfa'
|
||||
forumTopicId: 16662
|
||||
dashedName: compound-assignment-with-augmented-multiplication
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The `*=` operator multiplies a variable by a number.
|
||||
|
||||
`myVar = myVar * 5;`
|
||||
|
||||
will multiply `myVar` by `5`. This can be rewritten as:
|
||||
|
||||
`myVar *= 5;`
|
||||
|
||||
# --instructions--
|
||||
|
||||
Convert the assignments for `a`, `b`, and `c` to use the `*=` operator.
|
||||
|
||||
# --hints--
|
||||
|
||||
`a` should equal `25`.
|
||||
|
||||
```js
|
||||
assert(a === 25);
|
||||
```
|
||||
|
||||
`b` should equal `36`.
|
||||
|
||||
```js
|
||||
assert(b === 36);
|
||||
```
|
||||
|
||||
`c` should equal `46`.
|
||||
|
||||
```js
|
||||
assert(c === 46);
|
||||
```
|
||||
|
||||
You should use the `*=` operator for each variable.
|
||||
|
||||
```js
|
||||
assert(code.match(/\*=/g).length === 3);
|
||||
```
|
||||
|
||||
You should not modify the code above the specified comment.
|
||||
|
||||
```js
|
||||
assert(
|
||||
/var a = 5;/.test(code) &&
|
||||
/var b = 12;/.test(code) &&
|
||||
/var c = 4\.6;/.test(code)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a,b,c){ return "a = " + a + ", b = " + b + ", c = " + c; })(a,b,c);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var a = 5;
|
||||
var b = 12;
|
||||
var c = 4.6;
|
||||
|
||||
// Only change code below this line
|
||||
a = a * 5;
|
||||
b = 3 * b;
|
||||
c = c * 10;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var a = 5;
|
||||
var b = 12;
|
||||
var c = 4.6;
|
||||
|
||||
a *= 5;
|
||||
b *= 3;
|
||||
c *= 10;
|
||||
```
|
@ -0,0 +1,89 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b0
|
||||
title: Compound Assignment With Augmented Subtraction
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2Qv7AV'
|
||||
forumTopicId: 16660
|
||||
dashedName: compound-assignment-with-augmented-subtraction
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Like the `+=` operator, `-=` subtracts a number from a variable.
|
||||
|
||||
`myVar = myVar - 5;`
|
||||
|
||||
will subtract `5` from `myVar`. This can be rewritten as:
|
||||
|
||||
`myVar -= 5;`
|
||||
|
||||
# --instructions--
|
||||
|
||||
Convert the assignments for `a`, `b`, and `c` to use the `-=` operator.
|
||||
|
||||
# --hints--
|
||||
|
||||
`a` should equal `5`.
|
||||
|
||||
```js
|
||||
assert(a === 5);
|
||||
```
|
||||
|
||||
`b` should equal `-6`.
|
||||
|
||||
```js
|
||||
assert(b === -6);
|
||||
```
|
||||
|
||||
`c` should equal `2`.
|
||||
|
||||
```js
|
||||
assert(c === 2);
|
||||
```
|
||||
|
||||
You should use the `-=` operator for each variable.
|
||||
|
||||
```js
|
||||
assert(code.match(/-=/g).length === 3);
|
||||
```
|
||||
|
||||
You should not modify the code above the specified comment.
|
||||
|
||||
```js
|
||||
assert(
|
||||
/var a = 11;/.test(code) && /var b = 9;/.test(code) && /var c = 3;/.test(code)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a,b,c){ return "a = " + a + ", b = " + b + ", c = " + c; })(a,b,c);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var a = 11;
|
||||
var b = 9;
|
||||
var c = 3;
|
||||
|
||||
// Only change code below this line
|
||||
a = a - 6;
|
||||
b = b - 15;
|
||||
c = c - 1;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var a = 11;
|
||||
var b = 9;
|
||||
var c = 3;
|
||||
|
||||
a -= 6;
|
||||
b -= 15;
|
||||
c -= 1;
|
||||
```
|
@ -0,0 +1,84 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b7
|
||||
title: Concatenating Strings with Plus Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cNpM8AN'
|
||||
forumTopicId: 16802
|
||||
dashedName: concatenating-strings-with-plus-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In JavaScript, when the `+` operator is used with a `String` value, it is called the <dfn>concatenation</dfn> operator. You can build a new string out of other strings by <dfn>concatenating</dfn> them together.
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
'My name is Alan,' + ' I concatenate.'
|
||||
```
|
||||
|
||||
**Note**
|
||||
Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
var ourStr = "I come first. " + "I come second.";
|
||||
// ourStr is "I come first. I come second."
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Build `myStr` from the strings `"This is the start. "` and `"This is the end."` using the `+` operator.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myStr` should have a value of `This is the start. This is the end.`
|
||||
|
||||
```js
|
||||
assert(myStr === 'This is the start. This is the end.');
|
||||
```
|
||||
|
||||
You should use the `+` operator to build `myStr`.
|
||||
|
||||
```js
|
||||
assert(code.match(/(["']).*\1\s*\+\s*(["']).*\2/g));
|
||||
```
|
||||
|
||||
`myStr` should be created using the `var` keyword.
|
||||
|
||||
```js
|
||||
assert(/var\s+myStr/.test(code));
|
||||
```
|
||||
|
||||
You should assign the result to the `myStr` variable.
|
||||
|
||||
```js
|
||||
assert(/myStr\s*=/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){
|
||||
if(typeof myStr === 'string') {
|
||||
return 'myStr = "' + myStr + '"';
|
||||
} else {
|
||||
return 'myStr is not a string';
|
||||
}
|
||||
})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myStr; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myStr = "This is the start. " + "This is the end.";
|
||||
```
|
@ -0,0 +1,70 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b8
|
||||
title: Concatenating Strings with the Plus Equals Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cbQmmC4'
|
||||
forumTopicId: 16803
|
||||
dashedName: concatenating-strings-with-the-plus-equals-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
We can also use the `+=` operator to <dfn>concatenate</dfn> a string onto the end of an existing string variable. This can be very helpful to break a long string over several lines.
|
||||
|
||||
**Note**
|
||||
Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
var ourStr = "I come first. ";
|
||||
ourStr += "I come second.";
|
||||
// ourStr is now "I come first. I come second."
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Build `myStr` over several lines by concatenating these two strings: `"This is the first sentence. "` and `"This is the second sentence."` using the `+=` operator. Use the `+=` operator similar to how it is shown in the editor. Start by assigning the first string to `myStr`, then add on the second string.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myStr` should have a value of `This is the first sentence. This is the second sentence.`
|
||||
|
||||
```js
|
||||
assert(myStr === 'This is the first sentence. This is the second sentence.');
|
||||
```
|
||||
|
||||
You should use the `+=` operator to build `myStr`.
|
||||
|
||||
```js
|
||||
assert(code.match(/myStr\s*\+=\s*(["']).*\1/g));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){
|
||||
if(typeof myStr === 'string') {
|
||||
return 'myStr = "' + myStr + '"';
|
||||
} else {
|
||||
return 'myStr is not a string';
|
||||
}
|
||||
})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Only change code below this line
|
||||
|
||||
var myStr;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myStr = "This is the first sentence. ";
|
||||
myStr += "This is the second sentence.";
|
||||
```
|
@ -0,0 +1,74 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b9
|
||||
title: Constructing Strings with Variables
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cqk8rf4'
|
||||
forumTopicId: 16805
|
||||
dashedName: constructing-strings-with-variables
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Sometimes you will need to build a string, [Mad Libs](https://en.wikipedia.org/wiki/Mad_Libs) style. By using the concatenation operator (`+`), you can insert one or more variables into a string you're building.
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
var ourName = "freeCodeCamp";
|
||||
var ourStr = "Hello, our name is " + ourName + ", how are you?";
|
||||
// ourStr is now "Hello, our name is freeCodeCamp, how are you?"
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Set `myName` to a string equal to your name and build `myStr` with `myName` between the strings `"My name is "` and `" and I am well!"`
|
||||
|
||||
# --hints--
|
||||
|
||||
`myName` should be set to a string at least 3 characters long.
|
||||
|
||||
```js
|
||||
assert(typeof myName !== 'undefined' && myName.length > 2);
|
||||
```
|
||||
|
||||
You should use two `+` operators to build `myStr` with `myName` inside it.
|
||||
|
||||
```js
|
||||
assert(code.match(/["']\s*\+\s*myName\s*\+\s*["']/g).length > 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){
|
||||
var output = [];
|
||||
if(typeof myName === 'string') {
|
||||
output.push('myName = "' + myName + '"');
|
||||
} else {
|
||||
output.push('myName is not a string');
|
||||
}
|
||||
if(typeof myStr === 'string') {
|
||||
output.push('myStr = "' + myStr + '"');
|
||||
} else {
|
||||
output.push('myStr is not a string');
|
||||
}
|
||||
return output.join('\n');
|
||||
})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Only change code below this line
|
||||
var myName;
|
||||
var myStr;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myName = "Bob";
|
||||
var myStr = "My name is " + myName + " and I am well!";
|
||||
```
|
@ -0,0 +1,75 @@
|
||||
---
|
||||
id: 56105e7b514f539506016a5e
|
||||
title: Count Backwards With a For Loop
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2R6BHa'
|
||||
forumTopicId: 16808
|
||||
dashedName: count-backwards-with-a-for-loop
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
A for loop can also count backwards, so long as we can define the right conditions.
|
||||
|
||||
In order to decrement by two each iteration, we'll need to change our `initialization`, `condition`, and `final-expression`.
|
||||
|
||||
We'll start at `i = 10` and loop while `i > 0`. We'll decrement `i` by 2 each loop with `i -= 2`.
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
for (var i = 10; i > 0; i -= 2) {
|
||||
ourArray.push(i);
|
||||
}
|
||||
```
|
||||
|
||||
`ourArray` will now contain `[10,8,6,4,2]`. Let's change our `initialization` and `final-expression` so we can count backward by twos by odd numbers.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Push the odd numbers from 9 through 1 to `myArray` using a `for` loop.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should be using a `for` loop for this.
|
||||
|
||||
```js
|
||||
assert(/for\s*\([^)]+?\)/.test(code));
|
||||
```
|
||||
|
||||
You should be using the array method `push`.
|
||||
|
||||
```js
|
||||
assert(code.match(/myArray.push/));
|
||||
```
|
||||
|
||||
`myArray` should equal `[9,7,5,3,1]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [9, 7, 5, 3, 1]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
for (var i = 9; i > 0; i -= 2) {
|
||||
myArray.push(i);
|
||||
}
|
||||
```
|
@ -0,0 +1,203 @@
|
||||
---
|
||||
id: 565bbe00e9cc8ac0725390f4
|
||||
title: Counting Cards
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c6KE7ty'
|
||||
forumTopicId: 16809
|
||||
dashedName: counting-cards
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In the casino game Blackjack, a player can gain an advantage over the house by keeping track of the relative number of high and low cards remaining in the deck. This is called [Card Counting](https://en.wikipedia.org/wiki/Card_counting).
|
||||
|
||||
Having more high cards remaining in the deck favors the player. Each card is assigned a value according to the table below. When the count is positive, the player should bet high. When the count is zero or negative, the player should bet low.
|
||||
|
||||
<table class='table table-striped'><thead><tr><th>Count Change</th><th>Cards</th></tr></thead><tbody><tr><td>+1</td><td>2, 3, 4, 5, 6</td></tr><tr><td>0</td><td>7, 8, 9</td></tr><tr><td>-1</td><td>10, 'J', 'Q', 'K', 'A'</td></tr></tbody></table>
|
||||
|
||||
You will write a card counting function. It will receive a `card` parameter, which can be a number or a string, and increment or decrement the global `count` variable according to the card's value (see table). The function will then return a string with the current count and the string `Bet` if the count is positive, or `Hold` if the count is zero or negative. The current count and the player's decision (`Bet` or `Hold`) should be separated by a single space.
|
||||
|
||||
**Example Output**
|
||||
`-3 Hold`
|
||||
`5 Bet`
|
||||
|
||||
**Hint**
|
||||
Do NOT reset `count` to 0 when value is 7, 8, or 9. Do NOT return an array.
|
||||
Do NOT include quotes (single or double) in the output.
|
||||
|
||||
# --hints--
|
||||
|
||||
Cards Sequence 2, 3, 4, 5, 6 should return `5 Bet`
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
count = 0;
|
||||
cc(2);
|
||||
cc(3);
|
||||
cc(4);
|
||||
cc(5);
|
||||
var out = cc(6);
|
||||
if (out === '5 Bet') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
Cards Sequence 7, 8, 9 should return `0 Hold`
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
count = 0;
|
||||
cc(7);
|
||||
cc(8);
|
||||
var out = cc(9);
|
||||
if (out === '0 Hold') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
Cards Sequence 10, J, Q, K, A should return `-5 Hold`
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
count = 0;
|
||||
cc(10);
|
||||
cc('J');
|
||||
cc('Q');
|
||||
cc('K');
|
||||
var out = cc('A');
|
||||
if (out === '-5 Hold') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
Cards Sequence 3, 7, Q, 8, A should return `-1 Hold`
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
count = 0;
|
||||
cc(3);
|
||||
cc(7);
|
||||
cc('Q');
|
||||
cc(8);
|
||||
var out = cc('A');
|
||||
if (out === '-1 Hold') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
Cards Sequence 2, J, 9, 2, 7 should return `1 Bet`
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
count = 0;
|
||||
cc(2);
|
||||
cc('J');
|
||||
cc(9);
|
||||
cc(2);
|
||||
var out = cc(7);
|
||||
if (out === '1 Bet') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
Cards Sequence 2, 2, 10 should return `1 Bet`
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
count = 0;
|
||||
cc(2);
|
||||
cc(2);
|
||||
var out = cc(10);
|
||||
if (out === '1 Bet') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
Cards Sequence 3, 2, A, 10, K should return `-1 Hold`
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
count = 0;
|
||||
cc(3);
|
||||
cc(2);
|
||||
cc('A');
|
||||
cc(10);
|
||||
var out = cc('K');
|
||||
if (out === '-1 Hold') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var count = 0;
|
||||
|
||||
function cc(card) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
return "Change Me";
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
cc(2); cc(3); cc(7); cc('K'); cc('A');
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var count = 0;
|
||||
function cc(card) {
|
||||
switch(card) {
|
||||
case 2:
|
||||
case 3:
|
||||
case 4:
|
||||
case 5:
|
||||
case 6:
|
||||
count++;
|
||||
break;
|
||||
case 10:
|
||||
case 'J':
|
||||
case 'Q':
|
||||
case 'K':
|
||||
case 'A':
|
||||
count--;
|
||||
}
|
||||
if(count > 0) {
|
||||
return count + " Bet";
|
||||
} else {
|
||||
return count + " Hold";
|
||||
}
|
||||
}
|
||||
```
|
@ -0,0 +1,55 @@
|
||||
---
|
||||
id: cf1391c1c11feddfaeb4bdef
|
||||
title: Create Decimal Numbers with JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ca8GEuW'
|
||||
forumTopicId: 16826
|
||||
dashedName: create-decimal-numbers-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
We can store decimal numbers in variables too. Decimal numbers are sometimes referred to as <dfn>floating point</dfn> numbers or <dfn>floats</dfn>.
|
||||
|
||||
**Note**
|
||||
Not all real numbers can accurately be represented in <dfn>floating point</dfn>. This can lead to rounding errors. [Details Here](https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems).
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a variable `myDecimal` and give it a decimal value with a fractional part (e.g. `5.7`).
|
||||
|
||||
# --hints--
|
||||
|
||||
`myDecimal` should be a number.
|
||||
|
||||
```js
|
||||
assert(typeof myDecimal === 'number');
|
||||
```
|
||||
|
||||
`myDecimal` should have a decimal point
|
||||
|
||||
```js
|
||||
assert(myDecimal % 1 != 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){if(typeof myDecimal !== "undefined"){return myDecimal;}})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var ourDecimal = 5.7;
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myDecimal = 9.9;
|
||||
```
|
@ -0,0 +1,59 @@
|
||||
---
|
||||
id: bd7123c9c443eddfaeb5bdef
|
||||
title: Declare JavaScript Variables
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cNanrHq'
|
||||
forumTopicId: 17556
|
||||
dashedName: declare-javascript-variables
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In computer science, <dfn>data</dfn> is anything that is meaningful to the computer. JavaScript provides eight different <dfn>data types</dfn> which are `undefined`, `null`, `boolean`, `string`, `symbol`, `bigint`, `number`, and `object`.
|
||||
|
||||
For example, computers distinguish between numbers, such as the number `12`, and `strings`, such as `"12"`, `"dog"`, or `"123 cats"`, which are collections of characters. Computers can perform mathematical operations on a number, but not on a string.
|
||||
|
||||
<dfn>Variables</dfn> allow computers to store and manipulate data in a dynamic fashion. They do this by using a "label" to point to the data rather than using the data itself. Any of the eight data types may be stored in a variable.
|
||||
|
||||
`Variables` are similar to the x and y variables you use in mathematics, which means they're a simple name to represent the data we want to refer to. Computer `variables` differ from mathematical variables in that they can store different values at different times.
|
||||
|
||||
We tell JavaScript to create or <dfn>declare</dfn> a variable by putting the keyword `var` in front of it, like so:
|
||||
|
||||
```js
|
||||
var ourName;
|
||||
```
|
||||
|
||||
creates a `variable` called `ourName`. In JavaScript we end statements with semicolons. `Variable` names can be made up of numbers, letters, and `$` or `_`, but may not contain spaces or start with a number.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `var` keyword to create a variable called `myName`.
|
||||
|
||||
**Hint**
|
||||
Look at the `ourName` example above if you get stuck.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should declare `myName` with the `var` keyword, ending with a semicolon
|
||||
|
||||
```js
|
||||
assert(/var\s+myName\s*;/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myName !== "undefined"){(function(v){return v;})(myName);}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
```js
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myName;
|
||||
```
|
@ -0,0 +1,77 @@
|
||||
---
|
||||
id: bd7123c9c444eddfaeb5bdef
|
||||
title: Declare String Variables
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2QvWU6'
|
||||
forumTopicId: 17557
|
||||
dashedName: declare-string-variables
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Previously we have used the code
|
||||
|
||||
`var myName = "your name";`
|
||||
|
||||
`"your name"` is called a <dfn>string</dfn> <dfn>literal</dfn>. It is a string because it is a series of zero or more characters enclosed in single or double quotes.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create two new `string` variables: `myFirstName` and `myLastName` and assign them the values of your first and last name, respectively.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myFirstName` should be a string with at least one character in it.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
if (
|
||||
typeof myFirstName !== 'undefined' &&
|
||||
typeof myFirstName === 'string' &&
|
||||
myFirstName.length > 0
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
`myLastName` should be a string with at least one character in it.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
if (
|
||||
typeof myLastName !== 'undefined' &&
|
||||
typeof myLastName === 'string' &&
|
||||
myLastName.length > 0
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myFirstName !== "undefined" && typeof myLastName !== "undefined"){(function(){return myFirstName + ', ' + myLastName;})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
```js
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myFirstName = "Alan";
|
||||
var myLastName = "Turing";
|
||||
```
|
@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ad
|
||||
title: Decrement a Number with JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cM2KeS2'
|
||||
forumTopicId: 17558
|
||||
dashedName: decrement-a-number-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
You can easily <dfn>decrement</dfn> or decrease a variable by one with the `--` operator.
|
||||
|
||||
`i--;`
|
||||
|
||||
is the equivalent of
|
||||
|
||||
`i = i - 1;`
|
||||
|
||||
**Note**
|
||||
The entire line becomes `i--;`, eliminating the need for the equal sign.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the code to use the `--` operator on `myVar`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myVar` should equal `10`.
|
||||
|
||||
```js
|
||||
assert(myVar === 10);
|
||||
```
|
||||
|
||||
`myVar = myVar - 1;` should be changed.
|
||||
|
||||
```js
|
||||
assert(
|
||||
/var\s*myVar\s*=\s*11;\s*\/*.*\s*([-]{2}\s*myVar|myVar\s*[-]{2});/.test(code)
|
||||
);
|
||||
```
|
||||
|
||||
You should use the `--` operator on `myVar`.
|
||||
|
||||
```js
|
||||
assert(/[-]{2}\s*myVar|myVar\s*[-]{2}/.test(code));
|
||||
```
|
||||
|
||||
You should not change code above the specified comment.
|
||||
|
||||
```js
|
||||
assert(/var myVar = 11;/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return 'myVar = ' + z;})(myVar);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myVar = 11;
|
||||
|
||||
// Only change code below this line
|
||||
myVar = myVar - 1;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myVar = 11;
|
||||
myVar--;
|
||||
```
|
@ -0,0 +1,93 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392d3
|
||||
title: Delete Properties from a JavaScript Object
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cDqKdTv'
|
||||
forumTopicId: 17560
|
||||
dashedName: delete-properties-from-a-javascript-object
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
We can also delete properties from objects like this:
|
||||
|
||||
`delete ourDog.bark;`
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
var ourDog = {
|
||||
"name": "Camper",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["everything!"],
|
||||
"bark": "bow-wow"
|
||||
};
|
||||
|
||||
delete ourDog.bark;
|
||||
```
|
||||
|
||||
After the last line shown above, `ourDog` looks like:
|
||||
|
||||
```js
|
||||
{
|
||||
"name": "Camper",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["everything!"]
|
||||
}
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Delete the `"tails"` property from `myDog`. You may use either dot or bracket notation.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should delete the property `"tails"` from `myDog`.
|
||||
|
||||
```js
|
||||
assert(typeof myDog === 'object' && myDog.tails === undefined);
|
||||
```
|
||||
|
||||
You should not modify the `myDog` setup.
|
||||
|
||||
```js
|
||||
assert(code.match(/"tails": 1/g).length > 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return z;})(myDog);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myDog = {
|
||||
"name": "Happy Coder",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["freeCodeCamp Campers"],
|
||||
"bark": "woof"
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myDog = {
|
||||
"name": "Happy Coder",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["freeCodeCamp Campers"],
|
||||
"bark": "woof"
|
||||
};
|
||||
delete myDog.tails;
|
||||
```
|
@ -0,0 +1,56 @@
|
||||
---
|
||||
id: bd7993c9ca9feddfaeb7bdef
|
||||
title: Divide One Decimal by Another with JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cBZe9AW'
|
||||
forumTopicId: 18255
|
||||
dashedName: divide-one-decimal-by-another-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Now let's divide one decimal by another.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the `0.0` so that `quotient` will equal to `2.2`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The variable `quotient` should equal `2.2`
|
||||
|
||||
```js
|
||||
assert(quotient === 2.2);
|
||||
```
|
||||
|
||||
You should use the `/` operator to divide 4.4 by 2
|
||||
|
||||
```js
|
||||
assert(/4\.40*\s*\/\s*2\.*0*/.test(code));
|
||||
```
|
||||
|
||||
The quotient variable should only be assigned once
|
||||
|
||||
```js
|
||||
assert(code.match(/quotient/g).length === 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(y){return 'quotient = '+y;})(quotient);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var quotient = 0.0 / 2.0; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var quotient = 4.4 / 2.0;
|
||||
```
|
@ -0,0 +1,58 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb6bdef
|
||||
title: Divide One Number by Another with JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cqkbdAr'
|
||||
forumTopicId: 17566
|
||||
dashedName: divide-one-number-by-another-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
We can also divide one number by another.
|
||||
|
||||
JavaScript uses the `/` symbol for division.
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
myVar = 16 / 2; // assigned 8
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the `0` so that the `quotient` is equal to `2`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The variable `quotient` should be equal to 2.
|
||||
|
||||
```js
|
||||
assert(quotient === 2);
|
||||
```
|
||||
|
||||
You should use the `/` operator.
|
||||
|
||||
```js
|
||||
assert(/\d+\s*\/\s*\d+/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return 'quotient = '+z;})(quotient);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var quotient = 66 / 0;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var quotient = 66 / 33;
|
||||
```
|
@ -0,0 +1,99 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b6
|
||||
title: Escape Sequences in Strings
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cvmqRh6'
|
||||
forumTopicId: 17567
|
||||
dashedName: escape-sequences-in-strings
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Quotes are not the only characters that can be <dfn>escaped</dfn> inside a string. There are two reasons to use escaping characters:
|
||||
|
||||
1. To allow you to use characters you may not otherwise be able to type out, such as a carriage return.
|
||||
2. To allow you to represent multiple quotes in a string without JavaScript misinterpreting what you mean.
|
||||
|
||||
We learned this in the previous challenge.
|
||||
|
||||
<table class='table table-striped'><thead><tr><th>Code</th><th>Output</th></tr></thead><tbody><tr><td><code>\'</code></td><td>single quote</td></tr><tr><td><code>\"</code></td><td>double quote</td></tr><tr><td><code>\\</code></td><td>backslash</td></tr><tr><td><code>\n</code></td><td>newline</td></tr><tr><td><code>\r</code></td><td>carriage return</td></tr><tr><td><code>\t</code></td><td>tab</td></tr><tr><td><code>\b</code></td><td>word boundary</td></tr><tr><td><code>\f</code></td><td>form feed</td></tr></tbody></table>
|
||||
|
||||
*Note that the backslash itself must be escaped in order to display as a backslash.*
|
||||
|
||||
# --instructions--
|
||||
|
||||
Assign the following three lines of text into the single variable `myStr` using escape sequences.
|
||||
|
||||
<blockquote>FirstLine<br> \SecondLine<br>ThirdLine</blockquote>
|
||||
|
||||
You will need to use escape sequences to insert special characters correctly. You will also need to follow the spacing as it looks above, with no spaces between escape sequences or words.
|
||||
|
||||
**Note:** The indentation for `SecondLine` is achieved with the tab escape character, not spaces.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myStr` should not contain any spaces
|
||||
|
||||
```js
|
||||
assert(!/ /.test(myStr));
|
||||
```
|
||||
|
||||
`myStr` should contain the strings `FirstLine`, `SecondLine` and `ThirdLine` (remember case sensitivity)
|
||||
|
||||
```js
|
||||
assert(
|
||||
/FirstLine/.test(myStr) && /SecondLine/.test(myStr) && /ThirdLine/.test(myStr)
|
||||
);
|
||||
```
|
||||
|
||||
`FirstLine` should be followed by the newline character `\n`
|
||||
|
||||
```js
|
||||
assert(/FirstLine\n/.test(myStr));
|
||||
```
|
||||
|
||||
`myStr` should contain a tab character `\t` which follows a newline character
|
||||
|
||||
```js
|
||||
assert(/\n\t/.test(myStr));
|
||||
```
|
||||
|
||||
`SecondLine` should be preceded by the backslash character <code>\\</code>
|
||||
|
||||
```js
|
||||
assert(/\\SecondLine/.test(myStr));
|
||||
```
|
||||
|
||||
There should be a newline character between `SecondLine` and `ThirdLine`
|
||||
|
||||
```js
|
||||
assert(/SecondLine\nThirdLine/.test(myStr));
|
||||
```
|
||||
|
||||
`myStr` should only contain characters shown in the instructions
|
||||
|
||||
```js
|
||||
assert(myStr === 'FirstLine\n\t\\SecondLine\nThirdLine');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){
|
||||
if (myStr !== undefined){
|
||||
console.log('myStr:\n' + myStr);}})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myStr; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myStr = "FirstLine\n\t\\SecondLine\nThirdLine";
|
||||
```
|
@ -0,0 +1,66 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b5
|
||||
title: Escaping Literal Quotes in Strings
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2QvgSr'
|
||||
forumTopicId: 17568
|
||||
dashedName: escaping-literal-quotes-in-strings
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
When you are defining a string you must start and end with a single or double quote. What happens when you need a literal quote: `"` or `'` inside of your string?
|
||||
|
||||
In JavaScript, you can <dfn>escape</dfn> a quote from considering it as an end of string quote by placing a <dfn>backslash</dfn> (<code>\\</code>) in front of the quote.
|
||||
|
||||
`var sampleStr = "Alan said, \"Peter is learning JavaScript\".";`
|
||||
|
||||
This signals to JavaScript that the following quote is not the end of the string, but should instead appear inside the string. So if you were to print this to the console, you would get:
|
||||
|
||||
`Alan said, "Peter is learning JavaScript".`
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use <dfn>backslashes</dfn> to assign a string to the `myStr` variable so that if you were to print it to the console, you would see:
|
||||
|
||||
`I am a "double quoted" string inside "double quotes".`
|
||||
|
||||
# --hints--
|
||||
|
||||
You should use two double quotes (`"`) and four escaped double quotes (`\"`).
|
||||
|
||||
```js
|
||||
assert(code.match(/\\"/g).length === 4 && code.match(/[^\\]"/g).length === 2);
|
||||
```
|
||||
|
||||
Variable myStr should contain the string: `I am a "double quoted" string inside "double quotes".`
|
||||
|
||||
```js
|
||||
assert(/I am a "double quoted" string inside "double quotes(\."|"\.)$/.test(myStr));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){
|
||||
if(typeof myStr === 'string') {
|
||||
console.log("myStr = \"" + myStr + "\"");
|
||||
} else {
|
||||
console.log("myStr is undefined");
|
||||
}
|
||||
})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myStr = ""; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myStr = "I am a \"double quoted\" string inside \"double quotes\".";
|
||||
```
|
@ -0,0 +1,65 @@
|
||||
---
|
||||
id: bd7123c9c448eddfaeb5bdef
|
||||
title: Find the Length of a String
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cvmqEAd'
|
||||
forumTopicId: 18182
|
||||
dashedName: find-the-length-of-a-string
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
You can find the length of a `String` value by writing `.length` after the string variable or string literal.
|
||||
|
||||
`"Alan Peter".length; // 10`
|
||||
|
||||
For example, if we created a variable `var firstName = "Charles"`, we could find out how long the string `"Charles"` is by using the `firstName.length` property.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `.length` property to count the number of characters in the `lastName` variable and assign it to `lastNameLength`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should not change the variable declarations in the `// Setup` section.
|
||||
|
||||
```js
|
||||
assert(
|
||||
code.match(/var lastNameLength = 0;/) &&
|
||||
code.match(/var lastName = "Lovelace";/)
|
||||
);
|
||||
```
|
||||
|
||||
`lastNameLength` should be equal to eight.
|
||||
|
||||
```js
|
||||
assert(typeof lastNameLength !== 'undefined' && lastNameLength === 8);
|
||||
```
|
||||
|
||||
You should be getting the length of `lastName` by using `.length` like this: `lastName.length`.
|
||||
|
||||
```js
|
||||
assert(code.match(/=\s*lastName\.length/g) && !code.match(/lastName\s*=\s*8/));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var lastNameLength = 0;
|
||||
var lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
lastNameLength = lastName;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var lastNameLength = 0;
|
||||
var lastName = "Lovelace";
|
||||
lastNameLength = lastName.length;
|
||||
```
|
@ -0,0 +1,70 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ae
|
||||
title: Finding a Remainder in JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cWP24Ub'
|
||||
forumTopicId: 18184
|
||||
dashedName: finding-a-remainder-in-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The <dfn>remainder</dfn> operator `%` gives the remainder of the division of two numbers.
|
||||
|
||||
**Example**
|
||||
|
||||
<blockquote>5 % 2 = 1 because<br>Math.floor(5 / 2) = 2 (Quotient)<br>2 * 2 = 4<br>5 - 4 = 1 (Remainder)</blockquote>
|
||||
|
||||
**Usage**
|
||||
In mathematics, a number can be checked to be even or odd by checking the remainder of the division of the number by `2`.
|
||||
|
||||
<blockquote>17 % 2 = 1 (17 is Odd)<br>48 % 2 = 0 (48 is Even)</blockquote>
|
||||
|
||||
**Note**
|
||||
The <dfn>remainder</dfn> operator is sometimes incorrectly referred to as the "modulus" operator. It is very similar to modulus, but does not work properly with negative numbers.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Set `remainder` equal to the remainder of `11` divided by `3` using the <dfn>remainder</dfn> (`%`) operator.
|
||||
|
||||
# --hints--
|
||||
|
||||
The variable `remainder` should be initialized
|
||||
|
||||
```js
|
||||
assert(/var\s+?remainder/.test(code));
|
||||
```
|
||||
|
||||
The value of `remainder` should be `2`
|
||||
|
||||
```js
|
||||
assert(remainder === 2);
|
||||
```
|
||||
|
||||
You should use the `%` operator
|
||||
|
||||
```js
|
||||
assert(/\s+?remainder\s*?=\s*?.*%.*;?/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(y){return 'remainder = '+y;})(remainder);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Only change code below this line
|
||||
|
||||
var remainder;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var remainder = 11 % 3;
|
||||
```
|
@ -0,0 +1,70 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb9bdef
|
||||
title: Generate Random Fractions with JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cyWJJs3'
|
||||
forumTopicId: 18185
|
||||
dashedName: generate-random-fractions-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Random numbers are useful for creating random behavior.
|
||||
|
||||
JavaScript has a `Math.random()` function that generates a random decimal number between `0` (inclusive) and not quite up to `1` (exclusive). Thus `Math.random()` can return a `0` but never quite return a `1`
|
||||
|
||||
**Note**
|
||||
Like [Storing Values with the Equal Operator](/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator), all function calls will be resolved before the `return` executes, so we can `return` the value of the `Math.random()` function.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change `randomFraction` to return a random number instead of returning `0`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`randomFraction` should return a random number.
|
||||
|
||||
```js
|
||||
assert(typeof randomFraction() === 'number');
|
||||
```
|
||||
|
||||
The number returned by `randomFraction` should be a decimal.
|
||||
|
||||
```js
|
||||
assert((randomFraction() + '').match(/\./g));
|
||||
```
|
||||
|
||||
You should be using `Math.random` to generate the random decimal number.
|
||||
|
||||
```js
|
||||
assert(code.match(/Math\.random/g).length >= 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){return randomFraction();})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function randomFraction() {
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
return 0;
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function randomFraction() {
|
||||
return Math.random();
|
||||
}
|
||||
```
|
@ -0,0 +1,88 @@
|
||||
---
|
||||
id: cf1111c1c12feddfaeb1bdef
|
||||
title: Generate Random Whole Numbers with JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cRn6bfr'
|
||||
forumTopicId: 18186
|
||||
dashedName: generate-random-whole-numbers-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
It's great that we can generate random decimal numbers, but it's even more useful if we use it to generate random whole numbers.
|
||||
|
||||
<ol><li>Use <code>Math.random()</code> to generate a random decimal.</li><li>Multiply that random decimal by <code>20</code>.</li><li>Use another function, <code>Math.floor()</code> to round the number down to its nearest whole number.</li></ol>
|
||||
|
||||
Remember that `Math.random()` can never quite return a `1` and, because we're rounding down, it's impossible to actually get `20`. This technique will give us a whole number between `0` and `19`.
|
||||
|
||||
Putting everything together, this is what our code looks like:
|
||||
|
||||
`Math.floor(Math.random() * 20);`
|
||||
|
||||
We are calling `Math.random()`, multiplying the result by 20, then passing the value to `Math.floor()` function to round the value down to the nearest whole number.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use this technique to generate and return a random whole number between `0` and `9`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The result of `randomWholeNum` should be a whole number.
|
||||
|
||||
```js
|
||||
assert(
|
||||
typeof randomWholeNum() === 'number' &&
|
||||
(function () {
|
||||
var r = randomWholeNum();
|
||||
return Math.floor(r) === r;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
You should use `Math.random` to generate a random number.
|
||||
|
||||
```js
|
||||
assert(code.match(/Math.random/g).length >= 1);
|
||||
```
|
||||
|
||||
You should have multiplied the result of `Math.random` by 10 to make it a number that is between zero and nine.
|
||||
|
||||
```js
|
||||
assert(
|
||||
code.match(/\s*?Math.random\s*?\(\s*?\)\s*?\*\s*?10[\D]\s*?/g) ||
|
||||
code.match(/\s*?10\s*?\*\s*?Math.random\s*?\(\s*?\)\s*?/g)
|
||||
);
|
||||
```
|
||||
|
||||
You should use `Math.floor` to remove the decimal part of the number.
|
||||
|
||||
```js
|
||||
assert(code.match(/Math.floor/g).length >= 1);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){return randomWholeNum();})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function randomWholeNum() {
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
return Math.random();
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function randomWholeNum() {
|
||||
return Math.floor(Math.random() * 10);
|
||||
}
|
||||
```
|
@ -0,0 +1,100 @@
|
||||
---
|
||||
id: cf1111c1c12feddfaeb2bdef
|
||||
title: Generate Random Whole Numbers within a Range
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cm83yu6'
|
||||
forumTopicId: 18187
|
||||
dashedName: generate-random-whole-numbers-within-a-range
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Instead of generating a random whole number between zero and a given number like we did before, we can generate a random whole number that falls within a range of two specific numbers.
|
||||
|
||||
To do this, we'll define a minimum number `min` and a maximum number `max`.
|
||||
|
||||
Here's the formula we'll use. Take a moment to read it and try to understand what this code is doing:
|
||||
|
||||
`Math.floor(Math.random() * (max - min + 1)) + min`
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a function called `randomRange` that takes a range `myMin` and `myMax` and returns a random whole number that's greater than or equal to `myMin`, and is less than or equal to `myMax`, inclusive.
|
||||
|
||||
# --hints--
|
||||
|
||||
The lowest random number that can be generated by `randomRange` should be equal to your minimum number, `myMin`.
|
||||
|
||||
```js
|
||||
assert(calcMin === 5);
|
||||
```
|
||||
|
||||
The highest random number that can be generated by `randomRange` should be equal to your maximum number, `myMax`.
|
||||
|
||||
```js
|
||||
assert(calcMax === 15);
|
||||
```
|
||||
|
||||
The random number generated by `randomRange` should be an integer, not a decimal.
|
||||
|
||||
```js
|
||||
assert(randomRange(0, 1) % 1 === 0);
|
||||
```
|
||||
|
||||
`randomRange` should use both `myMax` and `myMin`, and return a random number in your range.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
if (
|
||||
code.match(/myMax/g).length > 1 &&
|
||||
code.match(/myMin/g).length > 2 &&
|
||||
code.match(/Math.floor/g) &&
|
||||
code.match(/Math.random/g)
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
var calcMin = 100;
|
||||
var calcMax = -100;
|
||||
for(var i = 0; i < 100; i++) {
|
||||
var result = randomRange(5,15);
|
||||
calcMin = Math.min(calcMin, result);
|
||||
calcMax = Math.max(calcMax, result);
|
||||
}
|
||||
(function(){
|
||||
if(typeof myRandom === 'number') {
|
||||
return "myRandom = " + myRandom;
|
||||
} else {
|
||||
return "myRandom undefined";
|
||||
}
|
||||
})()
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function randomRange(myMin, myMax) {
|
||||
// Only change code below this line
|
||||
return 0;
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function randomRange(myMin, myMax) {
|
||||
return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
|
||||
}
|
||||
```
|
@ -0,0 +1,128 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244be
|
||||
title: Global Scope and Functions
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cQM7mCN'
|
||||
forumTopicId: 18193
|
||||
dashedName: global-scope-and-functions
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In JavaScript, <dfn>scope</dfn> refers to the visibility of variables. Variables which are defined outside of a function block have <dfn>Global</dfn> scope. This means, they can be seen everywhere in your JavaScript code.
|
||||
|
||||
Variables which are used without the `var` keyword are automatically created in the `global` scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with `var`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Using `var`, declare a global variable named `myGlobal` outside of any function. Initialize it with a value of `10`.
|
||||
|
||||
Inside function `fun1`, assign `5` to `oopsGlobal` ***without*** using the `var` keyword.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myGlobal` should be defined
|
||||
|
||||
```js
|
||||
assert(typeof myGlobal != 'undefined');
|
||||
```
|
||||
|
||||
`myGlobal` should have a value of `10`
|
||||
|
||||
```js
|
||||
assert(myGlobal === 10);
|
||||
```
|
||||
|
||||
`myGlobal` should be declared using the `var` keyword
|
||||
|
||||
```js
|
||||
assert(/var\s+myGlobal/.test(code));
|
||||
```
|
||||
|
||||
`oopsGlobal` should be a global variable and have a value of `5`
|
||||
|
||||
```js
|
||||
assert(typeof oopsGlobal != 'undefined' && oopsGlobal === 5);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --before-user-code--
|
||||
|
||||
```js
|
||||
var logOutput = "";
|
||||
var originalConsole = console
|
||||
function capture() {
|
||||
var nativeLog = console.log;
|
||||
console.log = function (message) {
|
||||
logOutput = message;
|
||||
if(nativeLog.apply) {
|
||||
nativeLog.apply(originalConsole, arguments);
|
||||
} else {
|
||||
var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');
|
||||
nativeLog(nativeMsg);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function uncapture() {
|
||||
console.log = originalConsole.log;
|
||||
}
|
||||
var oopsGlobal;
|
||||
capture();
|
||||
```
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
fun1();
|
||||
fun2();
|
||||
uncapture();
|
||||
(function() { return logOutput || "console.log never called"; })();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Declare the myGlobal variable below this line
|
||||
|
||||
|
||||
function fun1() {
|
||||
// Assign 5 to oopsGlobal Here
|
||||
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
function fun2() {
|
||||
var output = "";
|
||||
if (typeof myGlobal != "undefined") {
|
||||
output += "myGlobal: " + myGlobal;
|
||||
}
|
||||
if (typeof oopsGlobal != "undefined") {
|
||||
output += " oopsGlobal: " + oopsGlobal;
|
||||
}
|
||||
console.log(output);
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myGlobal = 10;
|
||||
|
||||
function fun1() {
|
||||
oopsGlobal = 5;
|
||||
}
|
||||
|
||||
function fun2() {
|
||||
var output = "";
|
||||
if(typeof myGlobal != "undefined") {
|
||||
output += "myGlobal: " + myGlobal;
|
||||
}
|
||||
if(typeof oopsGlobal != "undefined") {
|
||||
output += " oopsGlobal: " + oopsGlobal;
|
||||
}
|
||||
console.log(output);
|
||||
}
|
||||
```
|
@ -0,0 +1,78 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c0
|
||||
title: Global vs. Local Scope in Functions
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2QwKH2'
|
||||
forumTopicId: 18194
|
||||
dashedName: global-vs--local-scope-in-functions
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
It is possible to have both <dfn>local</dfn> and <dfn>global</dfn> variables with the same name. When you do this, the `local` variable takes precedence over the `global` variable.
|
||||
|
||||
In this example:
|
||||
|
||||
```js
|
||||
var someVar = "Hat";
|
||||
function myFun() {
|
||||
var someVar = "Head";
|
||||
return someVar;
|
||||
}
|
||||
```
|
||||
|
||||
The function `myFun` will return `"Head"` because the `local` version of the variable is present.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add a local variable to `myOutfit` function to override the value of `outerWear` with `"sweater"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should not change the value of the global `outerWear`.
|
||||
|
||||
```js
|
||||
assert(outerWear === 'T-Shirt');
|
||||
```
|
||||
|
||||
`myOutfit` should return `"sweater"`.
|
||||
|
||||
```js
|
||||
assert(myOutfit() === 'sweater');
|
||||
```
|
||||
|
||||
You should not change the return statement.
|
||||
|
||||
```js
|
||||
assert(/return outerWear/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var outerWear = "T-Shirt";
|
||||
|
||||
function myOutfit() {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
return outerWear;
|
||||
}
|
||||
|
||||
myOutfit();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var outerWear = "T-Shirt";
|
||||
function myOutfit() {
|
||||
var outerWear = "sweater";
|
||||
return outerWear;
|
||||
}
|
||||
```
|
@ -0,0 +1,135 @@
|
||||
---
|
||||
id: 5664820f61c48e80c9fa476c
|
||||
title: Golf Code
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c9ykNUR'
|
||||
forumTopicId: 18195
|
||||
dashedName: golf-code
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In the game of [golf](https://en.wikipedia.org/wiki/Golf) each hole has a `par` meaning the average number of `strokes` a golfer is expected to make in order to sink the ball in a hole to complete the play. Depending on how far above or below `par` your `strokes` are, there is a different nickname.
|
||||
|
||||
Your function will be passed `par` and `strokes` arguments. Return the correct string according to this table which lists the strokes in order of priority; top (highest) to bottom (lowest):
|
||||
|
||||
<table class='table table-striped'><thead><tr><th>Strokes</th><th>Return</th></tr></thead><tbody><tr><td>1</td><td>"Hole-in-one!"</td></tr><tr><td><= par - 2</td><td>"Eagle"</td></tr><tr><td>par - 1</td><td>"Birdie"</td></tr><tr><td>par</td><td>"Par"</td></tr><tr><td>par + 1</td><td>"Bogey"</td></tr><tr><td>par + 2</td><td>"Double Bogey"</td></tr><tr><td>>= par + 3</td><td>"Go Home!"</td></tr></tbody></table>
|
||||
|
||||
`par` and `strokes` will always be numeric and positive. We have added an array of all the names for your convenience.
|
||||
|
||||
# --hints--
|
||||
|
||||
`golfScore(4, 1)` should return "Hole-in-one!"
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 1) === 'Hole-in-one!');
|
||||
```
|
||||
|
||||
`golfScore(4, 2)` should return "Eagle"
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 2) === 'Eagle');
|
||||
```
|
||||
|
||||
`golfScore(5, 2)` should return "Eagle"
|
||||
|
||||
```js
|
||||
assert(golfScore(5, 2) === 'Eagle');
|
||||
```
|
||||
|
||||
`golfScore(4, 3)` should return "Birdie"
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 3) === 'Birdie');
|
||||
```
|
||||
|
||||
`golfScore(4, 4)` should return "Par"
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 4) === 'Par');
|
||||
```
|
||||
|
||||
`golfScore(1, 1)` should return "Hole-in-one!"
|
||||
|
||||
```js
|
||||
assert(golfScore(1, 1) === 'Hole-in-one!');
|
||||
```
|
||||
|
||||
`golfScore(5, 5)` should return "Par"
|
||||
|
||||
```js
|
||||
assert(golfScore(5, 5) === 'Par');
|
||||
```
|
||||
|
||||
`golfScore(4, 5)` should return "Bogey"
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 5) === 'Bogey');
|
||||
```
|
||||
|
||||
`golfScore(4, 6)` should return "Double Bogey"
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 6) === 'Double Bogey');
|
||||
```
|
||||
|
||||
`golfScore(4, 7)` should return "Go Home!"
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 7) === 'Go Home!');
|
||||
```
|
||||
|
||||
`golfScore(5, 9)` should return "Go Home!"
|
||||
|
||||
```js
|
||||
assert(golfScore(5, 9) === 'Go Home!');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"];
|
||||
function golfScore(par, strokes) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
return "Change Me";
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
golfScore(5, 4);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function golfScore(par, strokes) {
|
||||
if (strokes === 1) {
|
||||
return "Hole-in-one!";
|
||||
}
|
||||
|
||||
if (strokes <= par - 2) {
|
||||
return "Eagle";
|
||||
}
|
||||
|
||||
if (strokes === par - 1) {
|
||||
return "Birdie";
|
||||
}
|
||||
|
||||
if (strokes === par) {
|
||||
return "Par";
|
||||
}
|
||||
|
||||
if (strokes === par + 1) {
|
||||
return "Bogey";
|
||||
}
|
||||
|
||||
if(strokes === par + 2) {
|
||||
return "Double Bogey";
|
||||
}
|
||||
|
||||
return "Go Home!";
|
||||
}
|
||||
```
|
@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ac
|
||||
title: Increment a Number with JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ca8GLT9'
|
||||
forumTopicId: 18201
|
||||
dashedName: increment-a-number-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
You can easily <dfn>increment</dfn> or add one to a variable with the `++` operator.
|
||||
|
||||
`i++;`
|
||||
|
||||
is the equivalent of
|
||||
|
||||
`i = i + 1;`
|
||||
|
||||
**Note**
|
||||
The entire line becomes `i++;`, eliminating the need for the equal sign.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the code to use the `++` operator on `myVar`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myVar` should equal `88`.
|
||||
|
||||
```js
|
||||
assert(myVar === 88);
|
||||
```
|
||||
|
||||
You should not use the assignment operator.
|
||||
|
||||
```js
|
||||
assert(
|
||||
/var\s*myVar\s*=\s*87;\s*\/*.*\s*([+]{2}\s*myVar|myVar\s*[+]{2});/.test(code)
|
||||
);
|
||||
```
|
||||
|
||||
You should use the `++` operator.
|
||||
|
||||
```js
|
||||
assert(/[+]{2}\s*myVar|myVar\s*[+]{2}/.test(code));
|
||||
```
|
||||
|
||||
You should not change code above the specified comment.
|
||||
|
||||
```js
|
||||
assert(/var myVar = 87;/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return 'myVar = ' + z;})(myVar);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myVar = 87;
|
||||
|
||||
// Only change code below this line
|
||||
myVar = myVar + 1;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myVar = 87;
|
||||
myVar++;
|
||||
```
|
@ -0,0 +1,46 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244a9
|
||||
title: Initializing Variables with the Assignment Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cWJ4Bfb'
|
||||
forumTopicId: 301171
|
||||
dashedName: initializing-variables-with-the-assignment-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
It is common to <dfn>initialize</dfn> a variable to an initial value in the same line as it is declared.
|
||||
|
||||
`var myVar = 0;`
|
||||
|
||||
Creates a new variable called `myVar` and assigns it an initial value of `0`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Define a variable `a` with `var` and initialize it to a value of `9`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should initialize `a` to a value of `9`.
|
||||
|
||||
```js
|
||||
assert(/var\s+a\s*=\s*9(\s*;?\s*)$/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof a !== 'undefined') {(function(a){return "a = " + a;})(a);} else { (function() {return 'a is undefined';})(); }
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
```js
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var a = 9;
|
||||
```
|
@ -0,0 +1,114 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244db
|
||||
title: Introducing Else If Statements
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/caeJ2hm'
|
||||
forumTopicId: 18206
|
||||
dashedName: introducing-else-if-statements
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
If you have multiple conditions that need to be addressed, you can chain `if` statements together with `else if` statements.
|
||||
|
||||
```js
|
||||
if (num > 15) {
|
||||
return "Bigger than 15";
|
||||
} else if (num < 5) {
|
||||
return "Smaller than 5";
|
||||
} else {
|
||||
return "Between 5 and 15";
|
||||
}
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Convert the logic to use `else if` statements.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should have at least two `else` statements
|
||||
|
||||
```js
|
||||
assert(code.match(/else/g).length > 1);
|
||||
```
|
||||
|
||||
You should have at least two `if` statements
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length > 1);
|
||||
```
|
||||
|
||||
You should have closing and opening curly braces for each `if else` code block.
|
||||
|
||||
```js
|
||||
assert(
|
||||
code.match(
|
||||
/if\s*\((.+)\)\s*\{[\s\S]+\}\s*else\s+if\s*\((.+)\)\s*\{[\s\S]+\}\s*else\s*\{[\s\S]+\s*\}/
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
`testElseIf(0)` should return "Smaller than 5"
|
||||
|
||||
```js
|
||||
assert(testElseIf(0) === 'Smaller than 5');
|
||||
```
|
||||
|
||||
`testElseIf(5)` should return "Between 5 and 10"
|
||||
|
||||
```js
|
||||
assert(testElseIf(5) === 'Between 5 and 10');
|
||||
```
|
||||
|
||||
`testElseIf(7)` should return "Between 5 and 10"
|
||||
|
||||
```js
|
||||
assert(testElseIf(7) === 'Between 5 and 10');
|
||||
```
|
||||
|
||||
`testElseIf(10)` should return "Between 5 and 10"
|
||||
|
||||
```js
|
||||
assert(testElseIf(10) === 'Between 5 and 10');
|
||||
```
|
||||
|
||||
`testElseIf(12)` should return "Greater than 10"
|
||||
|
||||
```js
|
||||
assert(testElseIf(12) === 'Greater than 10');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testElseIf(val) {
|
||||
if (val > 10) {
|
||||
return "Greater than 10";
|
||||
}
|
||||
|
||||
if (val < 5) {
|
||||
return "Smaller than 5";
|
||||
}
|
||||
|
||||
return "Between 5 and 10";
|
||||
}
|
||||
|
||||
testElseIf(7);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testElseIf(val) {
|
||||
if(val > 10) {
|
||||
return "Greater than 10";
|
||||
} else if(val < 5) {
|
||||
return "Smaller than 5";
|
||||
} else {
|
||||
return "Between 5 and 10";
|
||||
}
|
||||
}
|
||||
```
|
@ -0,0 +1,106 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244da
|
||||
title: Introducing Else Statements
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cek4Efq'
|
||||
forumTopicId: 18207
|
||||
dashedName: introducing-else-statements
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
When a condition for an `if` statement is true, the block of code following it is executed. What about when that condition is false? Normally nothing would happen. With an `else` statement, an alternate block of code can be executed.
|
||||
|
||||
```js
|
||||
if (num > 10) {
|
||||
return "Bigger than 10";
|
||||
} else {
|
||||
return "10 or Less";
|
||||
}
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Combine the `if` statements into a single `if/else` statement.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should only have one `if` statement in the editor
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length === 1);
|
||||
```
|
||||
|
||||
You should use an `else` statement
|
||||
|
||||
```js
|
||||
assert(/else/g.test(code));
|
||||
```
|
||||
|
||||
`testElse(4)` should return "5 or Smaller"
|
||||
|
||||
```js
|
||||
assert(testElse(4) === '5 or Smaller');
|
||||
```
|
||||
|
||||
`testElse(5)` should return "5 or Smaller"
|
||||
|
||||
```js
|
||||
assert(testElse(5) === '5 or Smaller');
|
||||
```
|
||||
|
||||
`testElse(6)` should return "Bigger than 5"
|
||||
|
||||
```js
|
||||
assert(testElse(6) === 'Bigger than 5');
|
||||
```
|
||||
|
||||
`testElse(10)` should return "Bigger than 5".
|
||||
|
||||
```js
|
||||
assert(testElse(10) === 'Bigger than 5');
|
||||
```
|
||||
|
||||
You should not change the code above or below the specified comments.
|
||||
|
||||
```js
|
||||
assert(/var result = "";/.test(code) && /return result;/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function testElse(val) {
|
||||
var result = "";
|
||||
// Only change code below this line
|
||||
|
||||
if (val > 5) {
|
||||
result = "Bigger than 5";
|
||||
}
|
||||
|
||||
if (val <= 5) {
|
||||
result = "5 or Smaller";
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
return result;
|
||||
}
|
||||
|
||||
testElse(4);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function testElse(val) {
|
||||
var result = "";
|
||||
if(val > 5) {
|
||||
result = "Bigger than 5";
|
||||
} else {
|
||||
result = "5 or Smaller";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
```
|
@ -0,0 +1,67 @@
|
||||
---
|
||||
id: 56104e9e514f539506016a5c
|
||||
title: Iterate Odd Numbers With a For Loop
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cm8n7T9'
|
||||
forumTopicId: 18212
|
||||
dashedName: iterate-odd-numbers-with-a-for-loop
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
For loops don't have to iterate one at a time. By changing our `final-expression`, we can count by even numbers.
|
||||
|
||||
We'll start at `i = 0` and loop while `i < 10`. We'll increment `i` by 2 each loop with `i += 2`.
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
for (var i = 0; i < 10; i += 2) {
|
||||
ourArray.push(i);
|
||||
}
|
||||
```
|
||||
|
||||
`ourArray` will now contain `[0,2,4,6,8]`. Let's change our `initialization` so we can count by odd numbers.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Push the odd numbers from 1 through 9 to `myArray` using a `for` loop.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should be using a `for` loop for this.
|
||||
|
||||
```js
|
||||
assert(/for\s*\([^)]+?\)/.test(code));
|
||||
```
|
||||
|
||||
`myArray` should equal `[1,3,5,7,9]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [1, 3, 5, 7, 9]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
for (var i = 1; i < 10; i += 2) {
|
||||
myArray.push(i);
|
||||
}
|
||||
```
|
@ -0,0 +1,79 @@
|
||||
---
|
||||
id: 5675e877dbd60be8ad28edc6
|
||||
title: Iterate Through an Array with a For Loop
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/caeR3HB'
|
||||
forumTopicId: 18216
|
||||
dashedName: iterate-through-an-array-with-a-for-loop
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
A common task in JavaScript is to iterate through the contents of an array. One way to do that is with a `for` loop. This code will output each element of the array `arr` to the console:
|
||||
|
||||
```js
|
||||
var arr = [10, 9, 8, 7, 6];
|
||||
for (var i = 0; i < arr.length; i++) {
|
||||
console.log(arr[i]);
|
||||
}
|
||||
```
|
||||
|
||||
Remember that arrays have zero-based indexing, which means the last index of the array is `length - 1`. Our condition for this loop is `i < arr.length`, which stops the loop when `i` is equal to `length`. In this case the last iteration is `i === 4` i.e. when `i` becomes equal to `arr.length` and outputs `6` to the console.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Declare and initialize a variable `total` to `0`. Use a `for` loop to add the value of each element of the `myArr` array to `total`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`total` should be declared and initialized to 0.
|
||||
|
||||
```js
|
||||
assert(code.match(/(var|let|const)\s*?total\s*=\s*0.*?;?/));
|
||||
```
|
||||
|
||||
`total` should equal 20.
|
||||
|
||||
```js
|
||||
assert(total === 20);
|
||||
```
|
||||
|
||||
You should use a `for` loop to iterate through `myArr`.
|
||||
|
||||
```js
|
||||
assert(/for\s*\(/g.test(code) && /myArr\s*\[/g.test(code));
|
||||
```
|
||||
|
||||
You should not attempt to directly assign the value 20 to `total`.
|
||||
|
||||
```js
|
||||
assert(!__helpers.removeWhiteSpace(code).match(/total[=+-]0*[1-9]+/gm));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(){if(typeof total !== 'undefined') { return "total = " + total; } else { return "total is undefined";}})()
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArr = [ 2, 3, 4, 5, 6];
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArr = [ 2, 3, 4, 5, 6];
|
||||
var total = 0;
|
||||
|
||||
for (var i = 0; i < myArr.length; i++) {
|
||||
total += myArr[i];
|
||||
}
|
||||
```
|
@ -0,0 +1,102 @@
|
||||
---
|
||||
id: 5a2efd662fb457916e1fe604
|
||||
title: Iterate with JavaScript Do...While Loops
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cDqWGcp'
|
||||
forumTopicId: 301172
|
||||
dashedName: iterate-with-javascript-do---while-loops
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The next type of loop you will learn is called a `do...while` loop. It is called a `do...while` loop because it will first `do` one pass of the code inside the loop no matter what, and then continue to run the loop `while` the specified condition evaluates to `true`.
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
var i = 0;
|
||||
do {
|
||||
ourArray.push(i);
|
||||
i++;
|
||||
} while (i < 5);
|
||||
```
|
||||
|
||||
The example above behaves similar to other types of loops, and the resulting array will look like `[0, 1, 2, 3, 4]`. However, what makes the `do...while` different from other loops is how it behaves when the condition fails on the first check. Let's see this in action: Here is a regular `while` loop that will run the code in the loop as long as `i < 5`:
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
var i = 5;
|
||||
while (i < 5) {
|
||||
ourArray.push(i);
|
||||
i++;
|
||||
}
|
||||
```
|
||||
|
||||
In this example, we initialize the value of `ourArray` to an empty array and the value of `i` to 5. When we execute the `while` loop, the condition evaluates to `false` because `i` is not less than 5, so we do not execute the code inside the loop. The result is that `ourArray` will end up with no values added to it, and it will still look like `[]` when all of the code in the example above has completed running. Now, take a look at a `do...while` loop:
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
var i = 5;
|
||||
do {
|
||||
ourArray.push(i);
|
||||
i++;
|
||||
} while (i < 5);
|
||||
```
|
||||
|
||||
In this case, we initialize the value of `i` to 5, just like we did with the `while` loop. When we get to the next line, there is no condition to evaluate, so we go to the code inside the curly braces and execute it. We will add a single element to the array and then increment `i` before we get to the condition check. When we finally evaluate the condition `i < 5` on the last line, we see that `i` is now 6, which fails the conditional check, so we exit the loop and are done. At the end of the above example, the value of `ourArray` is `[5]`. Essentially, a `do...while` loop ensures that the code inside the loop will run at least once. Let's try getting a `do...while` loop to work by pushing values to an array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the `while` loop in the code to a `do...while` loop so the loop will push only the number `10` to `myArray`, and `i` will be equal to `11` when your code has finished running.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should be using a `do...while` loop for this exercise.
|
||||
|
||||
```js
|
||||
assert(code.match(/do/g));
|
||||
```
|
||||
|
||||
`myArray` should equal `[10]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [10]);
|
||||
```
|
||||
|
||||
`i` should equal `11`
|
||||
|
||||
```js
|
||||
assert.equal(i, 11);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
var i = 10;
|
||||
|
||||
// Only change code below this line
|
||||
while (i < 5) {
|
||||
myArray.push(i);
|
||||
i++;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
var i = 10;
|
||||
do {
|
||||
myArray.push(i);
|
||||
i++;
|
||||
} while (i < 5)
|
||||
```
|
@ -0,0 +1,79 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb5bdef
|
||||
title: Iterate with JavaScript For Loops
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c9yNVCe'
|
||||
forumTopicId: 18219
|
||||
dashedName: iterate-with-javascript-for-loops
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
You can run the same code multiple times by using a loop.
|
||||
|
||||
The most common type of JavaScript loop is called a `for` loop because it runs "for" a specific number of times.
|
||||
|
||||
For loops are declared with three optional expressions separated by semicolons:
|
||||
|
||||
`for ([initialization]; [condition]; [final-expression])`
|
||||
|
||||
The `initialization` statement is executed one time only before the loop starts. It is typically used to define and setup your loop variable.
|
||||
|
||||
The `condition` statement is evaluated at the beginning of every loop iteration and will continue as long as it evaluates to `true`. When `condition` is `false` at the start of the iteration, the loop will stop executing. This means if `condition` starts as `false`, your loop will never execute.
|
||||
|
||||
The `final-expression` is executed at the end of each loop iteration, prior to the next `condition` check and is usually used to increment or decrement your loop counter.
|
||||
|
||||
In the following example we initialize with `i = 0` and iterate while our condition `i < 5` is true. We'll increment `i` by `1` in each loop iteration with `i++` as our `final-expression`.
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
for (var i = 0; i < 5; i++) {
|
||||
ourArray.push(i);
|
||||
}
|
||||
```
|
||||
|
||||
`ourArray` will now contain `[0,1,2,3,4]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use a `for` loop to work to push the values 1 through 5 onto `myArray`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should be using a `for` loop for this.
|
||||
|
||||
```js
|
||||
assert(/for\s*\([^)]+?\)/.test(code));
|
||||
```
|
||||
|
||||
`myArray` should equal `[1,2,3,4,5]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [1, 2, 3, 4, 5]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if (typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
for (var i = 1; i < 6; i++) {
|
||||
myArray.push(i);
|
||||
}
|
||||
```
|
@ -0,0 +1,73 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb1bdef
|
||||
title: Iterate with JavaScript While Loops
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c8QbnCM'
|
||||
forumTopicId: 18220
|
||||
dashedName: iterate-with-javascript-while-loops
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
You can run the same code multiple times by using a loop.
|
||||
|
||||
The first type of loop we will learn is called a `while` loop because it runs "while" a specified condition is true and stops once that condition is no longer true.
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
var i = 0;
|
||||
while(i < 5) {
|
||||
ourArray.push(i);
|
||||
i++;
|
||||
}
|
||||
```
|
||||
|
||||
In the code example above, the `while` loop will execute 5 times and append the numbers 0 through 4 to `ourArray`.
|
||||
|
||||
Let's try getting a while loop to work by pushing values to an array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the numbers 5 through 0 (inclusive) in descending order to `myArray` using a `while` loop.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should be using a `while` loop for this.
|
||||
|
||||
```js
|
||||
assert(code.match(/while/g));
|
||||
```
|
||||
|
||||
`myArray` should equal `[5,4,3,2,1,0]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [5, 4, 3, 2, 1, 0]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
var i = 5;
|
||||
while(i >= 0) {
|
||||
myArray.push(i);
|
||||
i--;
|
||||
}
|
||||
```
|
@ -0,0 +1,86 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244bf
|
||||
title: Local Scope and Functions
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cd62NhM'
|
||||
forumTopicId: 18227
|
||||
dashedName: local-scope-and-functions
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Variables which are declared within a function, as well as the function parameters have <dfn>local</dfn> scope. That means, they are only visible within that function.
|
||||
|
||||
Here is a function `myTest` with a local variable called `loc`.
|
||||
|
||||
```js
|
||||
function myTest() {
|
||||
var loc = "foo";
|
||||
console.log(loc);
|
||||
}
|
||||
myTest(); // logs "foo"
|
||||
console.log(loc); // loc is not defined
|
||||
```
|
||||
|
||||
`loc` is not defined outside of the function.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The editor has two `console.log`s to help you see what is happening. Check the console as you code to see how it changes. Declare a local variable `myVar` inside `myLocalScope` and run the tests.
|
||||
|
||||
**Note:** The console will still have 'ReferenceError: myVar is not defined', but this will not cause the tests to fail.
|
||||
|
||||
# --hints--
|
||||
|
||||
The code should not contain a global `myVar` variable.
|
||||
|
||||
```js
|
||||
function declared() {
|
||||
myVar;
|
||||
}
|
||||
assert.throws(declared, ReferenceError);
|
||||
```
|
||||
|
||||
You should add a local `myVar` variable.
|
||||
|
||||
```js
|
||||
assert(
|
||||
/functionmyLocalScope\(\)\{.+(var|let|const)myVar[\s\S]*}/.test(
|
||||
__helpers.removeWhiteSpace(code)
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function myLocalScope() {
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
console.log('inside myLocalScope', myVar);
|
||||
}
|
||||
myLocalScope();
|
||||
|
||||
// Run and check the console
|
||||
// myVar is not defined outside of myLocalScope
|
||||
console.log('outside myLocalScope', myVar);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function myLocalScope() {
|
||||
|
||||
// Only change code below this line
|
||||
var myVar;
|
||||
console.log('inside myLocalScope', myVar);
|
||||
}
|
||||
myLocalScope();
|
||||
|
||||
// Run and check the console
|
||||
// myVar is not defined outside of myLocalScope
|
||||
console.log('outside myLocalScope', myVar);
|
||||
```
|
@ -0,0 +1,107 @@
|
||||
---
|
||||
id: 5690307fddb111c6084545d7
|
||||
title: Logical Order in If Else Statements
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cwNvMUV'
|
||||
forumTopicId: 18228
|
||||
dashedName: logical-order-in-if-else-statements
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Order is important in `if`, `else if` statements.
|
||||
|
||||
The function is executed from top to bottom so you will want to be careful of what statement comes first.
|
||||
|
||||
Take these two functions as an example.
|
||||
|
||||
Here's the first:
|
||||
|
||||
```js
|
||||
function foo(x) {
|
||||
if (x < 1) {
|
||||
return "Less than one";
|
||||
} else if (x < 2) {
|
||||
return "Less than two";
|
||||
} else {
|
||||
return "Greater than or equal to two";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And the second just switches the order of the statements:
|
||||
|
||||
```js
|
||||
function bar(x) {
|
||||
if (x < 2) {
|
||||
return "Less than two";
|
||||
} else if (x < 1) {
|
||||
return "Less than one";
|
||||
} else {
|
||||
return "Greater than or equal to two";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
While these two functions look nearly identical if we pass a number to both we get different outputs.
|
||||
|
||||
```js
|
||||
foo(0) // "Less than one"
|
||||
bar(0) // "Less than two"
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the order of logic in the function so that it will return the correct statements in all cases.
|
||||
|
||||
# --hints--
|
||||
|
||||
`orderMyLogic(4)` should return "Less than 5"
|
||||
|
||||
```js
|
||||
assert(orderMyLogic(4) === 'Less than 5');
|
||||
```
|
||||
|
||||
`orderMyLogic(6)` should return "Less than 10"
|
||||
|
||||
```js
|
||||
assert(orderMyLogic(6) === 'Less than 10');
|
||||
```
|
||||
|
||||
`orderMyLogic(11)` should return "Greater than or equal to 10"
|
||||
|
||||
```js
|
||||
assert(orderMyLogic(11) === 'Greater than or equal to 10');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function orderMyLogic(val) {
|
||||
if (val < 10) {
|
||||
return "Less than 10";
|
||||
} else if (val < 5) {
|
||||
return "Less than 5";
|
||||
} else {
|
||||
return "Greater than or equal to 10";
|
||||
}
|
||||
}
|
||||
|
||||
orderMyLogic(7);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function orderMyLogic(val) {
|
||||
if(val < 5) {
|
||||
return "Less than 5";
|
||||
} else if (val < 10) {
|
||||
return "Less than 10";
|
||||
} else {
|
||||
return "Greater than or equal to 10";
|
||||
}
|
||||
}
|
||||
```
|
@ -0,0 +1,88 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392cc
|
||||
title: Manipulate Arrays With pop()
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cRbVZAB'
|
||||
forumTopicId: 18236
|
||||
dashedName: manipulate-arrays-with-pop
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Another way to change the data in an array is with the `.pop()` function.
|
||||
|
||||
`.pop()` is used to "pop" a value off of the end of an array. We can store this "popped off" value by assigning it to a variable. In other words, `.pop()` removes the last element from an array and returns that element.
|
||||
|
||||
Any type of entry can be "popped" off of an array - numbers, strings, even nested arrays.
|
||||
|
||||
```js
|
||||
var threeArr = [1, 4, 6];
|
||||
var oneDown = threeArr.pop();
|
||||
console.log(oneDown); // Returns 6
|
||||
console.log(threeArr); // Returns [1, 4]
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `.pop()` function to remove the last item from `myArray`, assigning the "popped off" value to `removedFromMyArray`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` should only contain `[["John", 23]]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (d) {
|
||||
if (d[0][0] == 'John' && d[0][1] === 23 && d[1] == undefined) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(myArray)
|
||||
);
|
||||
```
|
||||
|
||||
You should use `pop()` on `myArray`.
|
||||
|
||||
```js
|
||||
assert(/removedFromMyArray\s*=\s*myArray\s*.\s*pop\s*(\s*)/.test(code));
|
||||
```
|
||||
|
||||
`removedFromMyArray` should only contain `["cat", 2]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (d) {
|
||||
if (d[0] == 'cat' && d[1] === 2 && d[2] == undefined) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(removedFromMyArray)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [["John", 23], ["cat", 2]];
|
||||
|
||||
// Only change code below this line
|
||||
var removedFromMyArray;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [["John", 23], ["cat", 2]];
|
||||
var removedFromMyArray = myArray.pop();
|
||||
```
|
@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392cb
|
||||
title: Manipulate Arrays With push()
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cnqmVtJ'
|
||||
forumTopicId: 18237
|
||||
dashedName: manipulate-arrays-with-push
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
An easy way to append data to the end of an array is via the `push()` function.
|
||||
|
||||
`.push()` takes one or more <dfn>parameters</dfn> and "pushes" them onto the end of the array.
|
||||
|
||||
Examples:
|
||||
|
||||
```js
|
||||
var arr1 = [1,2,3];
|
||||
arr1.push(4);
|
||||
// arr1 is now [1,2,3,4]
|
||||
|
||||
var arr2 = ["Stimpson", "J", "cat"];
|
||||
arr2.push(["happy", "joy"]);
|
||||
// arr2 now equals ["Stimpson", "J", "cat", ["happy", "joy"]]
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Push `["dog", 3]` onto the end of the `myArray` variable.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` should now equal `[["John", 23], ["cat", 2], ["dog", 3]]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (d) {
|
||||
if (
|
||||
d[2] != undefined &&
|
||||
d[0][0] == 'John' &&
|
||||
d[0][1] === 23 &&
|
||||
d[2][0] == 'dog' &&
|
||||
d[2][1] === 3 &&
|
||||
d[2].length == 2
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(myArray)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return 'myArray = ' + JSON.stringify(z);})(myArray);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [["John", 23], ["cat", 2]];
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [["John", 23], ["cat", 2]];
|
||||
myArray.push(["dog",3]);
|
||||
```
|
@ -0,0 +1,87 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392cd
|
||||
title: Manipulate Arrays With shift()
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cRbVETW'
|
||||
forumTopicId: 18238
|
||||
dashedName: manipulate-arrays-with-shift
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`pop()` always removes the last element of an array. What if you want to remove the first?
|
||||
|
||||
That's where `.shift()` comes in. It works just like `.pop()`, except it removes the first element instead of the last.
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
var ourArray = ["Stimpson", "J", ["cat"]];
|
||||
var removedFromOurArray = ourArray.shift();
|
||||
// removedFromOurArray now equals "Stimpson" and ourArray now equals ["J", ["cat"]].
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `.shift()` function to remove the first item from `myArray`, assigning the "shifted off" value to `removedFromMyArray`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` should now equal `[["dog", 3]]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (d) {
|
||||
if (d[0][0] == 'dog' && d[0][1] === 3 && d[1] == undefined) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(myArray)
|
||||
);
|
||||
```
|
||||
|
||||
`removedFromMyArray` should contain `["John", 23]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (d) {
|
||||
if (
|
||||
d[0] == 'John' &&
|
||||
d[1] === 23 &&
|
||||
typeof removedFromMyArray === 'object'
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(removedFromMyArray)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [["John", 23], ["dog", 3]];
|
||||
|
||||
// Only change code below this line
|
||||
var removedFromMyArray;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [["John", 23], ["dog", 3]];
|
||||
|
||||
// Only change code below this line
|
||||
var removedFromMyArray = myArray.shift();
|
||||
```
|
@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392ce
|
||||
title: Manipulate Arrays With unshift()
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ckNDESv'
|
||||
forumTopicId: 18239
|
||||
dashedName: manipulate-arrays-with-unshift
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Not only can you `shift` elements off of the beginning of an array, you can also `unshift` elements to the beginning of an array i.e. add elements in front of the array.
|
||||
|
||||
`.unshift()` works exactly like `.push()`, but instead of adding the element at the end of the array, `unshift()` adds the element at the beginning of the array.
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
var ourArray = ["Stimpson", "J", "cat"];
|
||||
ourArray.shift(); // ourArray now equals ["J", "cat"]
|
||||
ourArray.unshift("Happy");
|
||||
// ourArray now equals ["Happy", "J", "cat"]
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add `["Paul",35]` to the beginning of the `myArray` variable using `unshift()`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` should now have \[["Paul", 35], ["dog", 3]].
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function (d) {
|
||||
if (
|
||||
typeof d[0] === 'object' &&
|
||||
d[0][0] == 'Paul' &&
|
||||
d[0][1] === 35 &&
|
||||
d[1][0] != undefined &&
|
||||
d[1][0] == 'dog' &&
|
||||
d[1][1] != undefined &&
|
||||
d[1][1] == 3
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})(myArray)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(y, z){return 'myArray = ' + JSON.stringify(y);})(myArray);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [["John", 23], ["dog", 3]];
|
||||
myArray.shift();
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [["John", 23], ["dog", 3]];
|
||||
myArray.shift();
|
||||
myArray.unshift(["Paul", 35]);
|
||||
```
|
@ -0,0 +1,177 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244cb
|
||||
title: Manipulating Complex Objects
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c9yNMfR'
|
||||
forumTopicId: 18208
|
||||
dashedName: manipulating-complex-objects
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Sometimes you may want to store data in a flexible <dfn>Data Structure</dfn>. A JavaScript object is one way to handle flexible data. They allow for arbitrary combinations of <dfn>strings</dfn>, <dfn>numbers</dfn>, <dfn>booleans</dfn>, <dfn>arrays</dfn>, <dfn>functions</dfn>, and <dfn>objects</dfn>.
|
||||
|
||||
Here's an example of a complex data structure:
|
||||
|
||||
```js
|
||||
var ourMusic = [
|
||||
{
|
||||
"artist": "Daft Punk",
|
||||
"title": "Homework",
|
||||
"release_year": 1997,
|
||||
"formats": [
|
||||
"CD",
|
||||
"Cassette",
|
||||
"LP"
|
||||
],
|
||||
"gold": true
|
||||
}
|
||||
];
|
||||
```
|
||||
|
||||
This is an array which contains one object inside. The object has various pieces of <dfn>metadata</dfn> about an album. It also has a nested `"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
|
||||
{
|
||||
"artist": "Daft Punk",
|
||||
"title": "Homework",
|
||||
"release_year": 1997,
|
||||
"formats": [
|
||||
"CD",
|
||||
"Cassette",
|
||||
"LP"
|
||||
],
|
||||
"gold": true
|
||||
}
|
||||
```
|
||||
|
||||
**Note**
|
||||
You will need to place a comma after every object in the array, unless it is the last object in the array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add a new album to the `myMusic` array. Add `artist` and `title` strings, `release_year` number, and a `formats` array of strings.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myMusic` should be an array
|
||||
|
||||
```js
|
||||
assert(Array.isArray(myMusic));
|
||||
```
|
||||
|
||||
`myMusic` should have at least two elements
|
||||
|
||||
```js
|
||||
assert(myMusic.length > 1);
|
||||
```
|
||||
|
||||
`myMusic[1]` should be an object
|
||||
|
||||
```js
|
||||
assert(typeof myMusic[1] === 'object');
|
||||
```
|
||||
|
||||
`myMusic[1]` should have at least 4 properties
|
||||
|
||||
```js
|
||||
assert(Object.keys(myMusic[1]).length > 3);
|
||||
```
|
||||
|
||||
`myMusic[1]` should contain an `artist` property which is a string
|
||||
|
||||
```js
|
||||
assert(
|
||||
myMusic[1].hasOwnProperty('artist') && typeof myMusic[1].artist === 'string'
|
||||
);
|
||||
```
|
||||
|
||||
`myMusic[1]` should contain a `title` property which is a string
|
||||
|
||||
```js
|
||||
assert(
|
||||
myMusic[1].hasOwnProperty('title') && typeof myMusic[1].title === 'string'
|
||||
);
|
||||
```
|
||||
|
||||
`myMusic[1]` should contain a `release_year` property which is a number
|
||||
|
||||
```js
|
||||
assert(
|
||||
myMusic[1].hasOwnProperty('release_year') &&
|
||||
typeof myMusic[1].release_year === 'number'
|
||||
);
|
||||
```
|
||||
|
||||
`myMusic[1]` should contain a `formats` property which is an array
|
||||
|
||||
```js
|
||||
assert(
|
||||
myMusic[1].hasOwnProperty('formats') && Array.isArray(myMusic[1].formats)
|
||||
);
|
||||
```
|
||||
|
||||
`formats` should be an array of strings with at least two elements
|
||||
|
||||
```js
|
||||
assert(
|
||||
myMusic[1].formats.every(function (item) {
|
||||
return typeof item === 'string';
|
||||
}) && myMusic[1].formats.length > 1
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(x){ if (Array.isArray(x)) { return JSON.stringify(x); } return "myMusic is not an array"})(myMusic);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myMusic = [
|
||||
{
|
||||
"artist": "Billy Joel",
|
||||
"title": "Piano Man",
|
||||
"release_year": 1973,
|
||||
"formats": [
|
||||
"CD",
|
||||
"8T",
|
||||
"LP"
|
||||
],
|
||||
"gold": true
|
||||
}
|
||||
// Add a record here
|
||||
];
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myMusic = [
|
||||
{
|
||||
"artist": "Billy Joel",
|
||||
"title": "Piano Man",
|
||||
"release_year": 1973,
|
||||
"formats": [
|
||||
"CS",
|
||||
"8T",
|
||||
"LP" ],
|
||||
"gold": true
|
||||
},
|
||||
{
|
||||
"artist": "ABBA",
|
||||
"title": "Ring Ring",
|
||||
"release_year": 1973,
|
||||
"formats": [
|
||||
"CS",
|
||||
"8T",
|
||||
"LP",
|
||||
"CD",
|
||||
]
|
||||
}
|
||||
];
|
||||
```
|
@ -0,0 +1,85 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb8bdef
|
||||
title: Modify Array Data With Indexes
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/czQM4A8'
|
||||
forumTopicId: 18241
|
||||
dashedName: modify-array-data-with-indexes
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Unlike strings, the entries of arrays are <dfn>mutable</dfn> and can be changed freely.
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
var ourArray = [50,40,30];
|
||||
ourArray[0] = 15; // equals [15,40,30]
|
||||
```
|
||||
|
||||
**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--
|
||||
|
||||
Modify the data stored at index `0` of `myArray` to a value of `45`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` should now be [45,64,99].
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
if (
|
||||
typeof myArray != 'undefined' &&
|
||||
myArray[0] == 45 &&
|
||||
myArray[1] == 64 &&
|
||||
myArray[2] == 99
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
You should be using correct index to modify the value in `myArray`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
if (code.match(/myArray\[0\]\s*=\s*/g)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [18,64,99];
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [18,64,99];
|
||||
myArray[0] = 45;
|
||||
```
|
@ -0,0 +1,150 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244df
|
||||
title: Multiple Identical Options in Switch Statements
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cdBKWCV'
|
||||
forumTopicId: 18242
|
||||
dashedName: multiple-identical-options-in-switch-statements
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
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 = "";
|
||||
switch(val) {
|
||||
case 1:
|
||||
case 2:
|
||||
case 3:
|
||||
result = "1, 2, or 3";
|
||||
break;
|
||||
case 4:
|
||||
result = "4 alone";
|
||||
}
|
||||
```
|
||||
|
||||
Cases for 1, 2, and 3 will all produce the same result.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a switch statement to set `answer` for the following ranges:
|
||||
`1-3` - "Low"
|
||||
`4-6` - "Mid"
|
||||
`7-9` - "High"
|
||||
|
||||
**Note**
|
||||
You will need to have a `case` statement for each number in the range.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sequentialSizes(1)` should return "Low"
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(1) === 'Low');
|
||||
```
|
||||
|
||||
`sequentialSizes(2)` should return "Low"
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(2) === 'Low');
|
||||
```
|
||||
|
||||
`sequentialSizes(3)` should return "Low"
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(3) === 'Low');
|
||||
```
|
||||
|
||||
`sequentialSizes(4)` should return "Mid"
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(4) === 'Mid');
|
||||
```
|
||||
|
||||
`sequentialSizes(5)` should return "Mid"
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(5) === 'Mid');
|
||||
```
|
||||
|
||||
`sequentialSizes(6)` should return "Mid"
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(6) === 'Mid');
|
||||
```
|
||||
|
||||
`sequentialSizes(7)` should return "High"
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(7) === 'High');
|
||||
```
|
||||
|
||||
`sequentialSizes(8)` should return "High"
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(8) === 'High');
|
||||
```
|
||||
|
||||
`sequentialSizes(9)` should return "High"
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(9) === 'High');
|
||||
```
|
||||
|
||||
You should not use any `if` or `else` statements
|
||||
|
||||
```js
|
||||
assert(!/else/g.test(code) || !/if/g.test(code));
|
||||
```
|
||||
|
||||
You should have nine `case` statements
|
||||
|
||||
```js
|
||||
assert(code.match(/case/g).length === 9);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function sequentialSizes(val) {
|
||||
var answer = "";
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
return answer;
|
||||
}
|
||||
|
||||
sequentialSizes(1);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function sequentialSizes(val) {
|
||||
var answer = "";
|
||||
|
||||
switch(val) {
|
||||
case 1:
|
||||
case 2:
|
||||
case 3:
|
||||
answer = "Low";
|
||||
break;
|
||||
case 4:
|
||||
case 5:
|
||||
case 6:
|
||||
answer = "Mid";
|
||||
break;
|
||||
case 7:
|
||||
case 8:
|
||||
case 9:
|
||||
answer = "High";
|
||||
}
|
||||
|
||||
return answer;
|
||||
}
|
||||
```
|
@ -0,0 +1,52 @@
|
||||
---
|
||||
id: bd7993c9c69feddfaeb7bdef
|
||||
title: Multiply Two Decimals with JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ce2GeHq'
|
||||
forumTopicId: 301173
|
||||
dashedName: multiply-two-decimals-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In JavaScript, you can also perform calculations with decimal numbers, just like whole numbers.
|
||||
|
||||
Let's multiply two decimals together to get their product.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the `0.0` so that product will equal `5.0`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The variable `product` should equal `5.0`.
|
||||
|
||||
```js
|
||||
assert(product === 5.0);
|
||||
```
|
||||
|
||||
You should use the `*` operator
|
||||
|
||||
```js
|
||||
assert(/\*/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(y){return 'product = '+y;})(product);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var product = 2.0 * 0.0;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var product = 2.0 * 2.5;
|
||||
```
|
@ -0,0 +1,58 @@
|
||||
---
|
||||
id: cf1231c1c11feddfaeb5bdef
|
||||
title: Multiply Two Numbers with JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cP3y3Aq'
|
||||
forumTopicId: 18243
|
||||
dashedName: multiply-two-numbers-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
We can also multiply one number by another.
|
||||
|
||||
JavaScript uses the `*` symbol for multiplication of two numbers.
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
myVar = 13 * 13; // assigned 169
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the `0` so that product will equal `80`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The variable `product` should be equal to 80.
|
||||
|
||||
```js
|
||||
assert(product === 80);
|
||||
```
|
||||
|
||||
You should use the `*` operator.
|
||||
|
||||
```js
|
||||
assert(/\*/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return 'product = '+z;})(product);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var product = 8 * 0;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var product = 8 * 10;
|
||||
```
|
@ -0,0 +1,51 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb7bdef
|
||||
title: Nest one Array within Another Array
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/crZQZf8'
|
||||
forumTopicId: 18247
|
||||
dashedName: nest-one-array-within-another-array
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
You can also nest arrays within other arrays, like below:
|
||||
|
||||
```js
|
||||
[["Bulls", 23], ["White Sox", 45]]
|
||||
```
|
||||
|
||||
This is also called a <dfn>multi-dimensional array<dfn>.</dfn></dfn>
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a nested array called `myArray`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` should have at least one array nested within another array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(myArray) && myArray.some(Array.isArray));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Only change code below this line
|
||||
var myArray = [];
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [[1,2,3]];
|
||||
```
|
@ -0,0 +1,93 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244e1
|
||||
title: Nesting For Loops
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cRn6GHM'
|
||||
forumTopicId: 18248
|
||||
dashedName: nesting-for-loops
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
If you have a multi-dimensional array, you can use the same logic as the prior waypoint to loop through both the array and any sub-arrays. Here is an example:
|
||||
|
||||
```js
|
||||
var arr = [
|
||||
[1,2], [3,4], [5,6]
|
||||
];
|
||||
for (var i=0; i < arr.length; i++) {
|
||||
for (var j=0; j < arr[i].length; j++) {
|
||||
console.log(arr[i][j]);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This outputs each sub-element in `arr` one at a time. Note that for the inner loop, we are checking the `.length` of `arr[i]`, since `arr[i]` is itself an array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modify function `multiplyAll` so that it returns the product of all the numbers in the sub-arrays of `arr`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`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`
|
||||
|
||||
```js
|
||||
assert(
|
||||
multiplyAll([
|
||||
[1, 2],
|
||||
[3, 4],
|
||||
[5, 6, 7]
|
||||
]) === 5040
|
||||
);
|
||||
```
|
||||
|
||||
`multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]])` should return `54`
|
||||
|
||||
```js
|
||||
assert(
|
||||
multiplyAll([
|
||||
[5, 1],
|
||||
[0.2, 4, 0.5],
|
||||
[3, 9]
|
||||
]) === 54
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function multiplyAll(arr) {
|
||||
var product = 1;
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
return product;
|
||||
}
|
||||
|
||||
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++) {
|
||||
product *= arr[i][j];
|
||||
}
|
||||
}
|
||||
return product;
|
||||
}
|
||||
|
||||
multiplyAll([[1,2],[3,4],[5,6,7]]);
|
||||
```
|
@ -0,0 +1,118 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244bd
|
||||
title: Passing Values to Functions with Arguments
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cy8rahW'
|
||||
forumTopicId: 18254
|
||||
dashedName: passing-values-to-functions-with-arguments
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
<dfn>Parameters</dfn> are variables that act as placeholders for the values that are to be input to a function when it is called. When a function is defined, it is typically defined along with one or more parameters. The actual values that are input (or <dfn>"passed"</dfn>) into a function when it is called are known as <dfn>arguments</dfn>.
|
||||
|
||||
Here is a function with two parameters, `param1` and `param2`:
|
||||
|
||||
```js
|
||||
function testFun(param1, param2) {
|
||||
console.log(param1, param2);
|
||||
}
|
||||
```
|
||||
|
||||
Then we can call `testFun`: `testFun("Hello", "World");` We have passed two arguments, `"Hello"` and `"World"`. Inside the function, `param1` will equal "Hello" and `param2` will equal "World". Note that you could call `testFun` again with different arguments and the parameters would take on the value of the new arguments.
|
||||
|
||||
# --instructions--
|
||||
|
||||
<ol><li>Create a function called <code>functionWithArgs</code> that accepts two arguments and outputs their sum to the dev console.</li><li>Call the function with two numbers as arguments.</li></ol>
|
||||
|
||||
# --hints--
|
||||
|
||||
`functionWithArgs` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof functionWithArgs === 'function');
|
||||
```
|
||||
|
||||
`functionWithArgs(1,2)` should output `3`.
|
||||
|
||||
```js
|
||||
if (typeof functionWithArgs === 'function') {
|
||||
capture();
|
||||
functionWithArgs(1, 2);
|
||||
uncapture();
|
||||
}
|
||||
assert(logOutput == 3);
|
||||
```
|
||||
|
||||
`functionWithArgs(7,9)` should output `16`.
|
||||
|
||||
```js
|
||||
if (typeof functionWithArgs === 'function') {
|
||||
capture();
|
||||
functionWithArgs(7, 9);
|
||||
uncapture();
|
||||
}
|
||||
assert(logOutput == 16);
|
||||
```
|
||||
|
||||
You should call `functionWithArgs` with two numbers after you define it.
|
||||
|
||||
```js
|
||||
assert(
|
||||
/functionWithArgs\([-+]?\d*\.?\d*,[-+]?\d*\.?\d*\)/.test(
|
||||
code.replace(/\s/g, '')
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --before-user-code--
|
||||
|
||||
```js
|
||||
var logOutput = "";
|
||||
var originalConsole = console
|
||||
function capture() {
|
||||
var nativeLog = console.log;
|
||||
console.log = function (message) {
|
||||
if(message) logOutput = JSON.stringify(message).trim();
|
||||
if(nativeLog.apply) {
|
||||
nativeLog.apply(originalConsole, arguments);
|
||||
} else {
|
||||
var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');
|
||||
nativeLog(nativeMsg);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function uncapture() {
|
||||
console.log = originalConsole.log;
|
||||
}
|
||||
|
||||
capture();
|
||||
```
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
uncapture();
|
||||
|
||||
if (typeof functionWithArgs !== "function") {
|
||||
(function() { return "functionWithArgs is not defined"; })();
|
||||
} else {
|
||||
(function() { return logOutput || "console.log never called"; })();
|
||||
}
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
```js
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function functionWithArgs(a, b) {
|
||||
console.log(a + b);
|
||||
}
|
||||
functionWithArgs(10, 5);
|
||||
```
|
@ -0,0 +1,80 @@
|
||||
---
|
||||
id: 599a789b454f2bbd91a3ff4d
|
||||
title: Practice comparing different values
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cm8PqCa'
|
||||
forumTopicId: 301174
|
||||
dashedName: practice-comparing-different-values
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In the last two challenges, we learned about the equality operator (`==`) and the strict equality operator (`===`). Let's do a quick review and practice using these operators some more.
|
||||
|
||||
If the values being compared are not of the same type, the equality operator will perform a type conversion, and then evaluate the values. However, the strict equality operator will compare both the data type and value as-is, without converting one type to the other.
|
||||
|
||||
**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
|
||||
```
|
||||
|
||||
**Note**
|
||||
In JavaScript, you can determine the type of a variable or a value with the `typeof` operator, as follows:
|
||||
|
||||
```js
|
||||
typeof 3 // returns 'number'
|
||||
typeof '3' // returns 'string'
|
||||
```
|
||||
|
||||
# --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.
|
||||
|
||||
# --hints--
|
||||
|
||||
`compareEquality(10, "10")` should return "Not Equal"
|
||||
|
||||
```js
|
||||
assert(compareEquality(10, '10') === 'Not Equal');
|
||||
```
|
||||
|
||||
`compareEquality("20", 20)` should return "Not Equal"
|
||||
|
||||
```js
|
||||
assert(compareEquality('20', 20) === 'Not Equal');
|
||||
```
|
||||
|
||||
You should use the `===` operator
|
||||
|
||||
```js
|
||||
assert(code.match(/===/g));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
function compareEquality(a, b) {
|
||||
if (a == b) { // Change this line
|
||||
return "Equal";
|
||||
}
|
||||
return "Not Equal";
|
||||
}
|
||||
|
||||
compareEquality(10, "10");
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function compareEquality(a,b) {
|
||||
if (a === b) {
|
||||
return "Equal";
|
||||
}
|
||||
return "Not Equal";
|
||||
}
|
||||
```
|
@ -0,0 +1,151 @@
|
||||
---
|
||||
id: 5688e62ea601b2482ff8422b
|
||||
title: Profile Lookup
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cDqW2Cg'
|
||||
forumTopicId: 18259
|
||||
dashedName: profile-lookup
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
We have an array of objects representing different people in our contacts lists.
|
||||
|
||||
A `lookUpProfile` function that takes `name` and a property (`prop`) as arguments has been pre-written for you.
|
||||
|
||||
The function should check if `name` is an actual contact's `firstName` and the given property (`prop`) is a property of that contact.
|
||||
|
||||
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 `prop` does not correspond to any valid properties of a contact found to match `name` then return `"No such property"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`lookUpProfile("Kristian", "lastName")` should return `"Vos"`
|
||||
|
||||
```js
|
||||
assert(lookUpProfile('Kristian', 'lastName') === 'Vos');
|
||||
```
|
||||
|
||||
`lookUpProfile("Sherlock", "likes")` should return `["Intriguing Cases", "Violin"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(lookUpProfile('Sherlock', 'likes'), [
|
||||
'Intriguing Cases',
|
||||
'Violin'
|
||||
]);
|
||||
```
|
||||
|
||||
`lookUpProfile("Harry", "likes")` should return an array
|
||||
|
||||
```js
|
||||
assert(typeof lookUpProfile('Harry', 'likes') === 'object');
|
||||
```
|
||||
|
||||
`lookUpProfile("Bob", "number")` should return "No such contact"
|
||||
|
||||
```js
|
||||
assert(lookUpProfile('Bob', 'number') === 'No such contact');
|
||||
```
|
||||
|
||||
`lookUpProfile("Bob", "potato")` should return "No such contact"
|
||||
|
||||
```js
|
||||
assert(lookUpProfile('Bob', 'potato') === 'No such contact');
|
||||
```
|
||||
|
||||
`lookUpProfile("Akira", "address")` should return "No such property"
|
||||
|
||||
```js
|
||||
assert(lookUpProfile('Akira', 'address') === 'No such property');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```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"]
|
||||
}
|
||||
];
|
||||
|
||||
|
||||
function lookUpProfile(name, prop){
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
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"]
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
//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";
|
||||
}
|
||||
}
|
||||
return "No such contact";
|
||||
}
|
||||
//Write your function in between these comments
|
||||
|
||||
lookUpProfile("Akira", "likes");
|
||||
```
|
@ -0,0 +1,79 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b4
|
||||
title: Quoting Strings with Single Quotes
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cbQmnhM'
|
||||
forumTopicId: 18260
|
||||
dashedName: quoting-strings-with-single-quotes
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
<dfn>String</dfn> values in JavaScript may be written with single or double quotes, as long as you start and end with the same type of quote. Unlike some other programming languages, single and double quotes work the same in JavaScript.
|
||||
|
||||
```js
|
||||
doubleQuoteStr = "This is a string";
|
||||
singleQuoteStr = 'This is also a string';
|
||||
```
|
||||
|
||||
The reason why you might want to use one type of quote over the other is if you want to use both in a string. This might happen if you want to save a conversation in a string and have the conversation in quotes. Another use for it would be saving an `<a>` tag with various attributes in quotes, all within a string.
|
||||
|
||||
```js
|
||||
conversation = 'Finn exclaims to Jake, "Algebraic!"';
|
||||
```
|
||||
|
||||
However, this becomes a problem if you need to use the outermost quotes within it. Remember, a string has the same kind of quote at the beginning and end. But if you have that same quote somewhere in the middle, the string will stop early and throw an error.
|
||||
|
||||
```js
|
||||
goodStr = 'Jake asks Finn, "Hey, let\'s go on an adventure?"';
|
||||
badStr = 'Finn responds, "Let's go!"'; // Throws an error
|
||||
```
|
||||
|
||||
In the <dfn>goodStr</dfn> above, you can use both quotes safely by using the backslash <code>\\</code> as an escape character.
|
||||
|
||||
**Note:** The backslash <code>\\</code> should not be confused with the forward slash `/`. They do not do the same thing.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the provided string to a string with single quotes at the beginning and end and no escape characters.
|
||||
|
||||
Right now, the `<a>` tag in the string uses double quotes everywhere. You will need to change the outer quotes to single quotes so you can remove the escape characters.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should remove all the `backslashes` (<code>\\</code>).
|
||||
|
||||
```js
|
||||
assert(
|
||||
!/\\/g.test(code) &&
|
||||
myStr.match(
|
||||
'\\s*<a href\\s*=\\s*"http://www.example.com"\\s*target\\s*=\\s*"_blank">\\s*Link\\s*</a>\\s*'
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
You should have two single quotes `'` and four double quotes `"`.
|
||||
|
||||
```js
|
||||
assert(code.match(/"/g).length === 4 && code.match(/'/g).length === 2);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function() { return "myStr = " + myStr; })();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var 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>';
|
||||
```
|
@ -0,0 +1,181 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244cf
|
||||
title: Record Collection
|
||||
challengeType: 1
|
||||
forumTopicId: 18261
|
||||
dashedName: record-collection
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
You are given a JSON object representing a part of your musical album collection. Each album has a unique id number as its key and several other properties. Not all albums have complete information.
|
||||
|
||||
You start with an `updateRecords` function that takes an object like `collection`, an `id`, a `prop` (like `artist` or `tracks`), and a `value`. Complete the function using the rules below to modify the object passed to the function.
|
||||
|
||||
- Your function must always return the entire object.
|
||||
- If `prop` isn't `tracks` and `value` isn't an empty string, update or set that album's `prop` to `value`.
|
||||
- If `prop` is `tracks` but the album doesn't have a `tracks` property, create an empty array and add `value` to it.
|
||||
- If `prop` is `tracks` and `value` isn't an empty string, add `value` to the end of the album's existing `tracks` array.
|
||||
- If `value` is an empty string, delete the given `prop` property from the album.
|
||||
|
||||
**Note:** A copy of the `collection` object is used for the tests.
|
||||
|
||||
# --hints--
|
||||
|
||||
After `updateRecords(collection, 5439, "artist", "ABBA")`, `artist` should be `ABBA`
|
||||
|
||||
```js
|
||||
assert(
|
||||
updateRecords(_recordCollection, 5439, 'artist', 'ABBA')[5439]['artist'] ===
|
||||
'ABBA'
|
||||
);
|
||||
```
|
||||
|
||||
After `updateRecords(collection, 5439, "tracks", "Take a Chance on Me")`, `tracks` should have `Take a Chance on Me` as the last element.
|
||||
|
||||
```js
|
||||
assert(
|
||||
updateRecords(_recordCollection, 5439, 'tracks', 'Take a Chance on Me')[5439][
|
||||
'tracks'
|
||||
].pop() === 'Take a Chance on Me'
|
||||
);
|
||||
```
|
||||
|
||||
After `updateRecords(collection, 2548, "artist", "")`, `artist` should not be set
|
||||
|
||||
```js
|
||||
updateRecords(_recordCollection, 2548, 'artist', '');
|
||||
assert(!_recordCollection[2548].hasOwnProperty('artist'));
|
||||
```
|
||||
|
||||
After `updateRecords(collection, 1245, "tracks", "Addicted to Love")`, `tracks` should have `Addicted to Love` as the last element.
|
||||
|
||||
```js
|
||||
assert(
|
||||
updateRecords(_recordCollection, 1245, 'tracks', 'Addicted to Love')[1245][
|
||||
'tracks'
|
||||
].pop() === 'Addicted to Love'
|
||||
);
|
||||
```
|
||||
|
||||
After `updateRecords(collection, 2468, "tracks", "Free")`, `tracks` should have `1999` as the first element.
|
||||
|
||||
```js
|
||||
assert(
|
||||
updateRecords(_recordCollection, 2468, 'tracks', 'Free')[2468][
|
||||
'tracks'
|
||||
][0] === '1999'
|
||||
);
|
||||
```
|
||||
|
||||
After `updateRecords(collection, 2548, "tracks", "")`, `tracks` should not be set
|
||||
|
||||
```js
|
||||
updateRecords(_recordCollection, 2548, 'tracks', '');
|
||||
assert(!_recordCollection[2548].hasOwnProperty('tracks'));
|
||||
```
|
||||
|
||||
After `updateRecords(collection, 1245, "albumTitle", "Riptide")`, `albumTitle` should be `Riptide`
|
||||
|
||||
```js
|
||||
assert(
|
||||
updateRecords(_recordCollection, 1245, 'albumTitle', 'Riptide')[1245][
|
||||
'albumTitle'
|
||||
] === 'Riptide'
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --before-user-code--
|
||||
|
||||
```js
|
||||
const _recordCollection = {
|
||||
2548: {
|
||||
albumTitle: 'Slippery When Wet',
|
||||
artist: 'Bon Jovi',
|
||||
tracks: ['Let It Rock', 'You Give Love a Bad Name']
|
||||
},
|
||||
2468: {
|
||||
albumTitle: '1999',
|
||||
artist: 'Prince',
|
||||
tracks: ['1999', 'Little Red Corvette']
|
||||
},
|
||||
1245: {
|
||||
artist: 'Robert Palmer',
|
||||
tracks: []
|
||||
},
|
||||
5439: {
|
||||
albumTitle: 'ABBA Gold'
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var collection = {
|
||||
2548: {
|
||||
albumTitle: 'Slippery When Wet',
|
||||
artist: 'Bon Jovi',
|
||||
tracks: ['Let It Rock', 'You Give Love a Bad Name']
|
||||
},
|
||||
2468: {
|
||||
albumTitle: '1999',
|
||||
artist: 'Prince',
|
||||
tracks: ['1999', 'Little Red Corvette']
|
||||
},
|
||||
1245: {
|
||||
artist: 'Robert Palmer',
|
||||
tracks: []
|
||||
},
|
||||
5439: {
|
||||
albumTitle: 'ABBA Gold'
|
||||
}
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
function updateRecords(object, id, prop, value) {
|
||||
return object;
|
||||
}
|
||||
|
||||
updateRecords(collection, 5439, 'artist', 'ABBA');
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var collection = {
|
||||
2548: {
|
||||
albumTitle: 'Slippery When Wet',
|
||||
artist: 'Bon Jovi',
|
||||
tracks: ['Let It Rock', 'You Give Love a Bad Name']
|
||||
},
|
||||
2468: {
|
||||
albumTitle: '1999',
|
||||
artist: 'Prince',
|
||||
tracks: ['1999', 'Little Red Corvette']
|
||||
},
|
||||
1245: {
|
||||
artist: 'Robert Palmer',
|
||||
tracks: []
|
||||
},
|
||||
5439: {
|
||||
albumTitle: 'ABBA Gold'
|
||||
}
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
function updateRecords(object, id, prop, value) {
|
||||
if (value === '') delete object[id][prop];
|
||||
else if (prop === 'tracks') {
|
||||
object[id][prop] = object[id][prop] || [];
|
||||
object[id][prop].push(value);
|
||||
} else {
|
||||
object[id][prop] = value;
|
||||
}
|
||||
|
||||
return object;
|
||||
}
|
||||
```
|
@ -0,0 +1,107 @@
|
||||
---
|
||||
id: 5cfa3679138e7d9595b9d9d4
|
||||
title: Replace Loops using Recursion
|
||||
challengeType: 1
|
||||
videoUrl: >-
|
||||
https://www.freecodecamp.org/news/how-recursion-works-explained-with-flowcharts-and-a-video-de61f40cb7f9/
|
||||
forumTopicId: 301175
|
||||
dashedName: replace-loops-using-recursion
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Recursion is the concept that a function can be expressed in terms of itself. To help understand this, start by thinking about the following task: multiply the first `n` elements of an array to create the product of those elements. Using a `for` loop, you could do this:
|
||||
|
||||
```js
|
||||
function multiply(arr, n) {
|
||||
var product = 1;
|
||||
for (var i = 0; i < n; i++) {
|
||||
product *= arr[i];
|
||||
}
|
||||
return product;
|
||||
}
|
||||
```
|
||||
|
||||
However, notice that `multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1]`. That means you can rewrite `multiply` in terms of itself and never need to use a loop.
|
||||
|
||||
```js
|
||||
function multiply(arr, n) {
|
||||
if (n <= 0) {
|
||||
return 1;
|
||||
} else {
|
||||
return multiply(arr, n - 1) * arr[n - 1];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The recursive version of `multiply` breaks down like this. In the <dfn>base case</dfn>, where `n <= 0`, it returns 1. For larger values of `n`, it calls itself, but with `n - 1`. That function call is evaluated in the same way, calling `multiply` again until `n <= 0`. At this point, all the functions can return and the original `multiply` returns the answer.
|
||||
|
||||
**Note:** Recursive functions must have a base case when they return without calling the function again (in this example, when `n <= 0`), otherwise they can never finish executing.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a recursive function, `sum(arr, n)`, that returns the sum of the first `n` elements of an array `arr`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sum([1], 0)` should equal 0.
|
||||
|
||||
```js
|
||||
assert.equal(sum([1], 0), 0);
|
||||
```
|
||||
|
||||
`sum([2, 3, 4], 1)` should equal 2.
|
||||
|
||||
```js
|
||||
assert.equal(sum([2, 3, 4], 1), 2);
|
||||
```
|
||||
|
||||
`sum([2, 3, 4, 5], 3)` should equal 9.
|
||||
|
||||
```js
|
||||
assert.equal(sum([2, 3, 4, 5], 3), 9);
|
||||
```
|
||||
|
||||
Your code should not rely on any kind of loops (`for` or `while` or higher order functions such as `forEach`, `map`, `filter`, or `reduce`.).
|
||||
|
||||
```js
|
||||
assert(
|
||||
!__helpers
|
||||
.removeJSComments(code)
|
||||
.match(/for|while|forEach|map|filter|reduce/g)
|
||||
);
|
||||
```
|
||||
|
||||
You should use recursion to solve this problem.
|
||||
|
||||
```js
|
||||
assert(
|
||||
__helpers.removeJSComments(sum.toString()).match(/sum\(.*\)/g).length > 1
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function sum(arr, n) {
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function sum(arr, n) {
|
||||
// Only change code below this line
|
||||
if(n <= 0) {
|
||||
return 0;
|
||||
} else {
|
||||
return sum(arr, n - 1) + arr[n - 1];
|
||||
}
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
@ -0,0 +1,157 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244e0
|
||||
title: Replacing If Else Chains with Switch
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c3JE8fy'
|
||||
forumTopicId: 18266
|
||||
dashedName: replacing-if-else-chains-with-switch
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
If you have many options to choose from, a `switch` statement can be easier to write than many chained `if`/`else if` statements. The following:
|
||||
|
||||
```js
|
||||
if (val === 1) {
|
||||
answer = "a";
|
||||
} else if (val === 2) {
|
||||
answer = "b";
|
||||
} else {
|
||||
answer = "c";
|
||||
}
|
||||
```
|
||||
|
||||
can be replaced with:
|
||||
|
||||
```js
|
||||
switch(val) {
|
||||
case 1:
|
||||
answer = "a";
|
||||
break;
|
||||
case 2:
|
||||
answer = "b";
|
||||
break;
|
||||
default:
|
||||
answer = "c";
|
||||
}
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the chained `if`/`else if` statements into a `switch` statement.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should not use any `else` statements anywhere in the editor
|
||||
|
||||
```js
|
||||
assert(!/else/g.test(code));
|
||||
```
|
||||
|
||||
You should not use any `if` statements anywhere in the editor
|
||||
|
||||
```js
|
||||
assert(!/if/g.test(code));
|
||||
```
|
||||
|
||||
You should have at least four `break` statements
|
||||
|
||||
```js
|
||||
assert(code.match(/break/g).length >= 4);
|
||||
```
|
||||
|
||||
`chainToSwitch("bob")` should be "Marley"
|
||||
|
||||
```js
|
||||
assert(chainToSwitch('bob') === 'Marley');
|
||||
```
|
||||
|
||||
`chainToSwitch(42)` should be "The Answer"
|
||||
|
||||
```js
|
||||
assert(chainToSwitch(42) === 'The Answer');
|
||||
```
|
||||
|
||||
`chainToSwitch(1)` should be "There is no #1"
|
||||
|
||||
```js
|
||||
assert(chainToSwitch(1) === 'There is no #1');
|
||||
```
|
||||
|
||||
`chainToSwitch(99)` should be "Missed me by this much!"
|
||||
|
||||
```js
|
||||
assert(chainToSwitch(99) === 'Missed me by this much!');
|
||||
```
|
||||
|
||||
`chainToSwitch(7)` should be "Ate Nine"
|
||||
|
||||
```js
|
||||
assert(chainToSwitch(7) === 'Ate Nine');
|
||||
```
|
||||
|
||||
`chainToSwitch("John")` should be "" (empty string)
|
||||
|
||||
```js
|
||||
assert(chainToSwitch('John') === '');
|
||||
```
|
||||
|
||||
`chainToSwitch(156)` should be "" (empty string)
|
||||
|
||||
```js
|
||||
assert(chainToSwitch(156) === '');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function chainToSwitch(val) {
|
||||
var answer = "";
|
||||
// Only change code below this line
|
||||
|
||||
if (val === "bob") {
|
||||
answer = "Marley";
|
||||
} else if (val === 42) {
|
||||
answer = "The Answer";
|
||||
} else if (val === 1) {
|
||||
answer = "There is no #1";
|
||||
} else if (val === 99) {
|
||||
answer = "Missed me by this much!";
|
||||
} else if (val === 7) {
|
||||
answer = "Ate Nine";
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
return answer;
|
||||
}
|
||||
|
||||
chainToSwitch(7);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function chainToSwitch(val) {
|
||||
var answer = "";
|
||||
|
||||
switch(val) {
|
||||
case "bob":
|
||||
answer = "Marley";
|
||||
break;
|
||||
case 42:
|
||||
answer = "The Answer";
|
||||
break;
|
||||
case 1:
|
||||
answer = "There is no #1";
|
||||
break;
|
||||
case 99:
|
||||
answer = "Missed me by this much!";
|
||||
break;
|
||||
case 7:
|
||||
answer = "Ate Nine";
|
||||
}
|
||||
return answer;
|
||||
}
|
||||
```
|
@ -0,0 +1,68 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c2
|
||||
title: Return a Value from a Function with Return
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cy87wue'
|
||||
forumTopicId: 18271
|
||||
dashedName: return-a-value-from-a-function-with-return
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
We can pass values into a function with <dfn>arguments</dfn>. You can use a `return` statement to send a value back out of a function.
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
function plusThree(num) {
|
||||
return num + 3;
|
||||
}
|
||||
var answer = plusThree(5); // 8
|
||||
```
|
||||
|
||||
`plusThree` takes an <dfn>argument</dfn> for `num` and returns a value equal to `num + 3`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a function `timesFive` that accepts one argument, multiplies it by `5`, and returns the new value. See the last line in the editor for an example of how you can test your `timesFive` function.
|
||||
|
||||
# --hints--
|
||||
|
||||
`timesFive` should be a function
|
||||
|
||||
```js
|
||||
assert(typeof timesFive === 'function');
|
||||
```
|
||||
|
||||
`timesFive(5)` should return `25`
|
||||
|
||||
```js
|
||||
assert(timesFive(5) === 25);
|
||||
```
|
||||
|
||||
`timesFive(2)` should return `10`
|
||||
|
||||
```js
|
||||
assert(timesFive(2) === 10);
|
||||
```
|
||||
|
||||
`timesFive(0)` should return `0`
|
||||
|
||||
```js
|
||||
assert(timesFive(0) === 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
```js
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function timesFive(num) {
|
||||
return num * 5;
|
||||
}
|
||||
timesFive(10);
|
||||
```
|
@ -0,0 +1,106 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c4
|
||||
title: Return Early Pattern for Functions
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cQe39Sq'
|
||||
forumTopicId: 18272
|
||||
dashedName: return-early-pattern-for-functions
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
When a `return` statement is reached, the execution of the current function stops and control returns to the calling location.
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
function myFun() {
|
||||
console.log("Hello");
|
||||
return "World";
|
||||
console.log("byebye")
|
||||
}
|
||||
myFun();
|
||||
```
|
||||
|
||||
The above outputs "Hello" to the console, returns "World", but `"byebye"` is never output, because the function exits at the `return` statement.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modify the function `abTest` so that if `a` or `b` are less than `0` the function will immediately exit with a value of `undefined`.
|
||||
|
||||
**Hint**
|
||||
Remember that [`undefined` is a keyword](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/understanding-uninitialized-variables), not a string.
|
||||
|
||||
# --hints--
|
||||
|
||||
`abTest(2,2)` should return a number
|
||||
|
||||
```js
|
||||
assert(typeof abTest(2, 2) === 'number');
|
||||
```
|
||||
|
||||
`abTest(2,2)` should return `8`
|
||||
|
||||
```js
|
||||
assert(abTest(2, 2) === 8);
|
||||
```
|
||||
|
||||
`abTest(-2,2)` should return `undefined`
|
||||
|
||||
```js
|
||||
assert(abTest(-2, 2) === undefined);
|
||||
```
|
||||
|
||||
`abTest(2,-2)` should return `undefined`
|
||||
|
||||
```js
|
||||
assert(abTest(2, -2) === undefined);
|
||||
```
|
||||
|
||||
`abTest(2,8)` should return `18`
|
||||
|
||||
```js
|
||||
assert(abTest(2, 8) === 18);
|
||||
```
|
||||
|
||||
`abTest(3,3)` should return `12`
|
||||
|
||||
```js
|
||||
assert(abTest(3, 3) === 12);
|
||||
```
|
||||
|
||||
`abTest(0,0)` should return `0`
|
||||
|
||||
```js
|
||||
assert(abTest(0, 0) === 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
function abTest(a, b) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
|
||||
}
|
||||
|
||||
abTest(2,2);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function abTest(a, b) {
|
||||
if(a < 0 || b < 0) {
|
||||
return undefined;
|
||||
}
|
||||
return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
|
||||
}
|
||||
```
|
@ -0,0 +1,82 @@
|
||||
---
|
||||
id: 5679ceb97cbaa8c51670a16b
|
||||
title: Returning Boolean Values from Functions
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cp62qAQ'
|
||||
forumTopicId: 18273
|
||||
dashedName: returning-boolean-values-from-functions
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
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:
|
||||
|
||||
```js
|
||||
function isEqual(a,b) {
|
||||
if (a === b) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
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) {
|
||||
return a === b;
|
||||
}
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Fix the function `isLess` to remove the `if/else` statements.
|
||||
|
||||
# --hints--
|
||||
|
||||
`isLess(10,15)` should return `true`
|
||||
|
||||
```js
|
||||
assert(isLess(10, 15) === true);
|
||||
```
|
||||
|
||||
`isLess(15,10)` should return `false`
|
||||
|
||||
```js
|
||||
assert(isLess(15, 10) === false);
|
||||
```
|
||||
|
||||
You should not use any `if` or `else` statements
|
||||
|
||||
```js
|
||||
assert(!/if|else/g.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function isLess(a, b) {
|
||||
// Only change code below this line
|
||||
if (a < b) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
isLess(10, 15);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function isLess(a, b) {
|
||||
return a < b;
|
||||
}
|
||||
```
|
@ -0,0 +1,114 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244dd
|
||||
title: Selecting from Many Options with Switch Statements
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c4mv4fm'
|
||||
forumTopicId: 18277
|
||||
dashedName: selecting-from-many-options-with-switch-statements
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
If you have many options to choose from, use a <dfn>switch</dfn> statement. A `switch` statement tests a value and can have many <dfn>case</dfn> statements which define various possible values. Statements are executed from the first matched `case` value until a `break` is encountered.
|
||||
|
||||
Here is an example of a `switch` statement:
|
||||
|
||||
```js
|
||||
switch(lowercaseLetter) {
|
||||
case "a":
|
||||
console.log("A");
|
||||
break;
|
||||
case "b":
|
||||
console.log("B");
|
||||
break;
|
||||
}
|
||||
```
|
||||
|
||||
`case` values are tested with strict equality (`===`). The `break` tells JavaScript to stop executing statements. If the `break` is omitted, the next statement will be executed.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a switch statement which tests `val` and sets `answer` for the following conditions:
|
||||
`1` - "alpha"
|
||||
`2` - "beta"
|
||||
`3` - "gamma"
|
||||
`4` - "delta"
|
||||
|
||||
# --hints--
|
||||
|
||||
`caseInSwitch(1)` should have a value of "alpha"
|
||||
|
||||
```js
|
||||
assert(caseInSwitch(1) === 'alpha');
|
||||
```
|
||||
|
||||
`caseInSwitch(2)` should have a value of "beta"
|
||||
|
||||
```js
|
||||
assert(caseInSwitch(2) === 'beta');
|
||||
```
|
||||
|
||||
`caseInSwitch(3)` should have a value of "gamma"
|
||||
|
||||
```js
|
||||
assert(caseInSwitch(3) === 'gamma');
|
||||
```
|
||||
|
||||
`caseInSwitch(4)` should have a value of "delta"
|
||||
|
||||
```js
|
||||
assert(caseInSwitch(4) === 'delta');
|
||||
```
|
||||
|
||||
You should not use any `if` or `else` statements
|
||||
|
||||
```js
|
||||
assert(!/else/g.test(code) || !/if/g.test(code));
|
||||
```
|
||||
|
||||
You should have at least 3 `break` statements
|
||||
|
||||
```js
|
||||
assert(code.match(/break/g).length > 2);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function caseInSwitch(val) {
|
||||
var answer = "";
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
return answer;
|
||||
}
|
||||
|
||||
caseInSwitch(1);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function caseInSwitch(val) {
|
||||
var answer = "";
|
||||
|
||||
switch(val) {
|
||||
case 1:
|
||||
answer = "alpha";
|
||||
break;
|
||||
case 2:
|
||||
answer = "beta";
|
||||
break;
|
||||
case 3:
|
||||
answer = "gamma";
|
||||
break;
|
||||
case 4:
|
||||
answer = "delta";
|
||||
}
|
||||
return answer;
|
||||
}
|
||||
```
|
@ -0,0 +1,95 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244bc
|
||||
title: Shopping List
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c9MEKHZ'
|
||||
forumTopicId: 18280
|
||||
dashedName: shopping-list
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Create a shopping list in the variable `myList`. The list should be a multi-dimensional array containing several sub-arrays.
|
||||
|
||||
The first element in each sub-array should contain a string with the name of the item. The second element should be a number representing the quantity i.e.
|
||||
|
||||
`["Chocolate Bar", 15]`
|
||||
|
||||
There should be at least 5 sub-arrays in the list.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myList` should be an array.
|
||||
|
||||
```js
|
||||
assert(isArray);
|
||||
```
|
||||
|
||||
The first elements in each of your sub-arrays should all be strings.
|
||||
|
||||
```js
|
||||
assert(hasString);
|
||||
```
|
||||
|
||||
The second elements in each of your sub-arrays should all be numbers.
|
||||
|
||||
```js
|
||||
assert(hasNumber);
|
||||
```
|
||||
|
||||
You should have at least 5 items in your list.
|
||||
|
||||
```js
|
||||
assert(count > 4);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
var count = 0;
|
||||
var isArray = false;
|
||||
var hasString = false;
|
||||
var hasNumber = false;
|
||||
(function(list){
|
||||
if(Array.isArray(myList)) {
|
||||
isArray = true;
|
||||
if(myList.length > 0) {
|
||||
hasString = true;
|
||||
hasNumber = true;
|
||||
for (var elem of myList) {
|
||||
if(!elem || !elem[0] || typeof elem[0] !== 'string') {
|
||||
hasString = false;
|
||||
}
|
||||
if(!elem || typeof elem[1] !== 'number') {
|
||||
hasNumber = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
count = myList.length;
|
||||
return JSON.stringify(myList);
|
||||
} else {
|
||||
return "myList is not an array";
|
||||
}
|
||||
|
||||
})(myList);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myList = [];
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myList = [
|
||||
["Candy", 10],
|
||||
["Potatoes", 12],
|
||||
["Eggs", 12],
|
||||
["Catfood", 1],
|
||||
["Toads", 9]
|
||||
];
|
||||
```
|
@ -0,0 +1,118 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c6
|
||||
title: Stand in Line
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ca8Q8tP'
|
||||
forumTopicId: 18307
|
||||
dashedName: stand-in-line
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In Computer Science a <dfn>queue</dfn> is an abstract <dfn>Data Structure</dfn> where items are kept in order. New items can be added at the back of the queue and old items are taken off from the front of the queue.
|
||||
|
||||
Write a function `nextInLine` which takes an array (`arr`) and a number (`item`) as arguments.
|
||||
|
||||
Add the number to the end of the array, then remove the first element of the array.
|
||||
|
||||
The `nextInLine` function should then return the element that was removed.
|
||||
|
||||
# --hints--
|
||||
|
||||
`nextInLine([], 5)` should return a number.
|
||||
|
||||
```js
|
||||
assert.isNumber(nextInLine([], 5));
|
||||
```
|
||||
|
||||
`nextInLine([], 1)` should return `1`
|
||||
|
||||
```js
|
||||
assert(nextInLine([], 1) === 1);
|
||||
```
|
||||
|
||||
`nextInLine([2], 1)` should return `2`
|
||||
|
||||
```js
|
||||
assert(nextInLine([2], 1) === 2);
|
||||
```
|
||||
|
||||
`nextInLine([5,6,7,8,9], 1)` should return `5`
|
||||
|
||||
```js
|
||||
assert(nextInLine([5, 6, 7, 8, 9], 1) === 5);
|
||||
```
|
||||
|
||||
After `nextInLine(testArr, 10)`, `testArr[4]` should be `10`
|
||||
|
||||
```js
|
||||
nextInLine(testArr, 10);
|
||||
assert(testArr[4] === 10);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --before-user-code--
|
||||
|
||||
```js
|
||||
var logOutput = [];
|
||||
var originalConsole = console
|
||||
function capture() {
|
||||
var nativeLog = console.log;
|
||||
console.log = function (message) {
|
||||
logOutput.push(message);
|
||||
if(nativeLog.apply) {
|
||||
nativeLog.apply(originalConsole, arguments);
|
||||
} else {
|
||||
var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');
|
||||
nativeLog(nativeMsg);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function uncapture() {
|
||||
console.log = originalConsole.log;
|
||||
}
|
||||
|
||||
capture();
|
||||
```
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
uncapture();
|
||||
testArr = [1,2,3,4,5];
|
||||
(function() { return logOutput.join("\n");})();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function nextInLine(arr, item) {
|
||||
// Only change code below this line
|
||||
|
||||
return item;
|
||||
// Only change code above this line
|
||||
|
||||
|
||||
}
|
||||
|
||||
// Setup
|
||||
var testArr = [1,2,3,4,5];
|
||||
|
||||
// Display code
|
||||
console.log("Before: " + JSON.stringify(testArr));
|
||||
console.log(nextInLine(testArr, 6));
|
||||
console.log("After: " + JSON.stringify(testArr));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var testArr = [ 1,2,3,4,5];
|
||||
|
||||
function nextInLine(arr, item) {
|
||||
arr.push(item);
|
||||
return arr.shift();
|
||||
}
|
||||
```
|
@ -0,0 +1,64 @@
|
||||
---
|
||||
id: bd7993c9c69feddfaeb8bdef
|
||||
title: Store Multiple Values in one Variable using JavaScript Arrays
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/crZQWAm'
|
||||
forumTopicId: 18309
|
||||
dashedName: store-multiple-values-in-one-variable-using-javascript-arrays
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
With JavaScript `array` variables, we can store several pieces of data in one place.
|
||||
|
||||
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:
|
||||
|
||||
`var sandwich = ["peanut butter", "jelly", "bread"]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modify the new array `myArray` so that it contains both a `string` and a `number` (in that order).
|
||||
|
||||
**Hint**
|
||||
Refer to the example code in the text editor if you get stuck.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` should be an `array`.
|
||||
|
||||
```js
|
||||
assert(typeof myArray == 'object');
|
||||
```
|
||||
|
||||
The first item in `myArray` should be a `string`.
|
||||
|
||||
```js
|
||||
assert(typeof myArray[0] !== 'undefined' && typeof myArray[0] == 'string');
|
||||
```
|
||||
|
||||
The second item in `myArray` should be a `number`.
|
||||
|
||||
```js
|
||||
assert(typeof myArray[1] !== 'undefined' && typeof myArray[1] == 'number');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return z;})(myArray);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Only change code below this line
|
||||
var myArray = [];
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = ["The Answer", 42];
|
||||
```
|
@ -0,0 +1,75 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244a8
|
||||
title: Storing Values with the Assignment Operator
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cEanysE'
|
||||
forumTopicId: 18310
|
||||
dashedName: storing-values-with-the-assignment-operator
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In JavaScript, you can store a value in a variable with the <dfn>assignment</dfn> operator (`=`).
|
||||
|
||||
`myVariable = 5;`
|
||||
|
||||
This assigns the `Number` value `5` to `myVariable`.
|
||||
|
||||
If there are any calculations to the right of the `=` operator, those are performed before the value is assigned to the variable on the left of the operator.
|
||||
|
||||
```js
|
||||
var myVar;
|
||||
myVar = 5;
|
||||
```
|
||||
|
||||
First, this code creates a variable named `myVar`. Then, the code assigns `5` to `myVar`. Now, if `myVar` appears again in the code, the program will treat it as if it is `5`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Assign the value `7` to variable `a`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should not change code above the specified comment.
|
||||
|
||||
```js
|
||||
assert(/var a;/.test(code));
|
||||
```
|
||||
|
||||
`a` should have a value of 7.
|
||||
|
||||
```js
|
||||
assert(typeof a === 'number' && a === 7);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --before-user-code--
|
||||
|
||||
```js
|
||||
if (typeof a != 'undefined') {
|
||||
a = undefined;
|
||||
}
|
||||
```
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a){return "a = " + a;})(a);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var a;
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var a;
|
||||
a = 7;
|
||||
```
|
@ -0,0 +1,58 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb4bdef
|
||||
title: Subtract One Number from Another with JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cP3yQtk'
|
||||
forumTopicId: 18314
|
||||
dashedName: subtract-one-number-from-another-with-javascript
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
We can also subtract one number from another.
|
||||
|
||||
JavaScript uses the `-` symbol for subtraction.
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
myVar = 12 - 6; // assigned 6
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the `0` so the difference is `12`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The variable `difference` should be equal to 12.
|
||||
|
||||
```js
|
||||
assert(difference === 12);
|
||||
```
|
||||
|
||||
You should only subtract one number from 45.
|
||||
|
||||
```js
|
||||
assert(/difference=45-33;?/.test(__helpers.removeWhiteSpace(code)));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return 'difference = '+z;})(difference);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var difference = 45 - 0;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var difference = 45 - 33;
|
||||
```
|
@ -0,0 +1,96 @@
|
||||
---
|
||||
id: 567af2437cbaa8c51670a16c
|
||||
title: Testing Objects for Properties
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c6Wz4ySr'
|
||||
forumTopicId: 18324
|
||||
dashedName: testing-objects-for-properties
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Sometimes it is useful to check if the property of a given object exists or not. We can use the `.hasOwnProperty(propname)` method of objects to determine if that object has the given property name. `.hasOwnProperty()` returns `true` or `false` if the property is found or not.
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
var myObj = {
|
||||
top: "hat",
|
||||
bottom: "pants"
|
||||
};
|
||||
myObj.hasOwnProperty("top"); // true
|
||||
myObj.hasOwnProperty("middle"); // false
|
||||
```
|
||||
|
||||
# --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"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "gift")` should return `"pony"`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
checkObj({ gift: 'pony', pet: 'kitten', bed: 'sleigh' }, 'gift') === 'pony'
|
||||
);
|
||||
```
|
||||
|
||||
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "pet")` should return `"kitten"`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
checkObj({ gift: 'pony', pet: 'kitten', bed: 'sleigh' }, 'pet') === 'kitten'
|
||||
);
|
||||
```
|
||||
|
||||
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "house")` should return `"Not Found"`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
checkObj({ gift: 'pony', pet: 'kitten', bed: 'sleigh' }, 'house') ===
|
||||
'Not Found'
|
||||
);
|
||||
```
|
||||
|
||||
`checkObj({city: "Seattle"}, "city")` should return `"Seattle"`.
|
||||
|
||||
```js
|
||||
assert(checkObj({ city: 'Seattle' }, 'city') === 'Seattle');
|
||||
```
|
||||
|
||||
`checkObj({city: "Seattle"}, "district")` should return `"Not Found"`.
|
||||
|
||||
```js
|
||||
assert(checkObj({ city: 'Seattle' }, 'district') === 'Not Found');
|
||||
```
|
||||
|
||||
`checkObj({pet: "kitten", bed: "sleigh"}, "gift")` should return `"Not Found"`.
|
||||
|
||||
```js
|
||||
assert(checkObj({ pet: 'kitten', bed: 'sleigh' }, 'gift') === 'Not Found');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function checkObj(obj, checkProp) {
|
||||
// Only change code below this line
|
||||
return "Change Me!";
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function checkObj(obj, checkProp) {
|
||||
if(obj.hasOwnProperty(checkProp)) {
|
||||
return obj[checkProp];
|
||||
} else {
|
||||
return "Not Found";
|
||||
}
|
||||
}
|
||||
```
|
@ -0,0 +1,70 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ba
|
||||
title: Understand String Immutability
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cWPVaUR'
|
||||
forumTopicId: 18331
|
||||
dashedName: understand-string-immutability
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In JavaScript, `String` values are <dfn>immutable</dfn>, which means that they cannot be altered once created.
|
||||
|
||||
For example, the following code:
|
||||
|
||||
```js
|
||||
var 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";
|
||||
myStr = "Job";
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Correct the assignment to `myStr` so it contains the string value of `Hello World` using the approach shown in the example above.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myStr` should have a value of `Hello World`.
|
||||
|
||||
```js
|
||||
assert(myStr === 'Hello World');
|
||||
```
|
||||
|
||||
You should not change the code above the specified comment.
|
||||
|
||||
```js
|
||||
assert(/myStr = "Jello World"/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(v){return "myStr = " + v;})(myStr);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myStr = "Jello World";
|
||||
|
||||
// Only change code below this line
|
||||
myStr[0] = "H"; // Change this line
|
||||
// Only change code above this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myStr = "Jello World";
|
||||
myStr = "Hello World";
|
||||
```
|
@ -0,0 +1,62 @@
|
||||
---
|
||||
id: bd7123c9c441eddfaeb5bdef
|
||||
title: Understanding Boolean Values
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c9Me8t4'
|
||||
forumTopicId: 301176
|
||||
dashedName: understanding-boolean-values
|
||||
---
|
||||
|
||||
# --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.
|
||||
|
||||
**Note**
|
||||
`Boolean` values are never written with quotes. The `strings` `"true"` and `"false"` are not `Boolean` and have no special meaning in JavaScript.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modify the `welcomeToBooleans` function so that it returns `true` instead of `false` when the run button is clicked.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `welcomeToBooleans()` function should return a boolean (true/false) value.
|
||||
|
||||
```js
|
||||
assert(typeof welcomeToBooleans() === 'boolean');
|
||||
```
|
||||
|
||||
`welcomeToBooleans()` should return true.
|
||||
|
||||
```js
|
||||
assert(welcomeToBooleans() === true);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
welcomeToBooleans();
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function welcomeToBooleans() {
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
return false; // Change this line
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function welcomeToBooleans() {
|
||||
return true; // Change this line
|
||||
}
|
||||
```
|
@ -0,0 +1,99 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ab
|
||||
title: Understanding Case Sensitivity in Variables
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cd6GDcD'
|
||||
forumTopicId: 18334
|
||||
dashedName: understanding-case-sensitivity-in-variables
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In JavaScript all variables and function names are case sensitive. This means that capitalization matters.
|
||||
|
||||
`MYVAR` is not the same as `MyVar` nor `myvar`. It is possible to have multiple distinct variables with the same name but different casing. It is strongly recommended that for the sake of clarity, you *do not* use this language feature.
|
||||
|
||||
**Best Practice**
|
||||
|
||||
Write variable names in JavaScript in <dfn>camelCase</dfn>. In <dfn>camelCase</dfn>, multi-word variable names have the first word in lowercase and the first letter of each subsequent word is capitalized.
|
||||
|
||||
**Examples:**
|
||||
|
||||
```js
|
||||
var someVariable;
|
||||
var anotherVariableName;
|
||||
var thisVariableNameIsSoLong;
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modify the existing declarations and assignments so their names use <dfn>camelCase</dfn>.
|
||||
Do not create any new variables.
|
||||
|
||||
# --hints--
|
||||
|
||||
`studlyCapVar` should be defined and have a value of `10`.
|
||||
|
||||
```js
|
||||
assert(typeof studlyCapVar !== 'undefined' && studlyCapVar === 10);
|
||||
```
|
||||
|
||||
`properCamelCase` should be defined and have a value of `"A String"`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
typeof properCamelCase !== 'undefined' && properCamelCase === 'A String'
|
||||
);
|
||||
```
|
||||
|
||||
`titleCaseOver` should be defined and have a value of `9000`.
|
||||
|
||||
```js
|
||||
assert(typeof titleCaseOver !== 'undefined' && titleCaseOver === 9000);
|
||||
```
|
||||
|
||||
`studlyCapVar` should use camelCase in both declaration and assignment sections.
|
||||
|
||||
```js
|
||||
assert(code.match(/studlyCapVar/g).length === 2);
|
||||
```
|
||||
|
||||
`properCamelCase` should use camelCase in both declaration and assignment sections.
|
||||
|
||||
```js
|
||||
assert(code.match(/properCamelCase/g).length === 2);
|
||||
```
|
||||
|
||||
`titleCaseOver` should use camelCase in both declaration and assignment sections.
|
||||
|
||||
```js
|
||||
assert(code.match(/titleCaseOver/g).length === 2);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Variable declarations
|
||||
var StUdLyCapVaR;
|
||||
var properCamelCase;
|
||||
var TitleCaseOver;
|
||||
|
||||
// Variable assignments
|
||||
STUDLYCAPVAR = 10;
|
||||
PRoperCAmelCAse = "A String";
|
||||
tITLEcASEoVER = 9000;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var studlyCapVar;
|
||||
var properCamelCase;
|
||||
var titleCaseOver;
|
||||
|
||||
studlyCapVar = 10;
|
||||
properCamelCase = "A String";
|
||||
titleCaseOver = 9000;
|
||||
```
|
@ -0,0 +1,94 @@
|
||||
---
|
||||
id: 598e8944f009e646fc236146
|
||||
title: Understanding Undefined Value returned from a Function
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ce2p7cL'
|
||||
forumTopicId: 301177
|
||||
dashedName: understanding-undefined-value-returned-from-a-function
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
A function can include the `return` statement but it does not have to. In the case that the function doesn't have a `return` statement, when you call it, the function processes the inner code but the returned value is `undefined`.
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
var sum = 0;
|
||||
function addSum(num) {
|
||||
sum = sum + num;
|
||||
}
|
||||
addSum(3); // sum will be modified but returned value 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`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a function `addFive` without any arguments. This function adds 5 to the `sum` variable, but its returned value is `undefined`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`addFive` should be a function.
|
||||
|
||||
```js
|
||||
assert(typeof addFive === 'function');
|
||||
```
|
||||
|
||||
Once both functions have ran, the `sum` should be equal to 8.
|
||||
|
||||
```js
|
||||
assert(sum === 8);
|
||||
```
|
||||
|
||||
Returned value from `addFive` should be `undefined`.
|
||||
|
||||
```js
|
||||
assert(addFive() === undefined);
|
||||
```
|
||||
|
||||
Inside the `addFive` function, you should add `5` to the `sum` variable.
|
||||
|
||||
```js
|
||||
assert(
|
||||
__helpers.removeWhiteSpace(addFive.toString()).match(/sum=sum\+5|sum\+=5/)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var sum = 0;
|
||||
|
||||
function addThree() {
|
||||
sum = sum + 3;
|
||||
}
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
addThree();
|
||||
addFive();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var sum = 0;
|
||||
|
||||
function addThree() {
|
||||
sum = sum + 3;
|
||||
}
|
||||
|
||||
function addFive() {
|
||||
sum = sum + 5;
|
||||
}
|
||||
|
||||
addThree();
|
||||
addFive();
|
||||
```
|
@ -0,0 +1,79 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244aa
|
||||
title: Understanding Uninitialized Variables
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cBa2JAL'
|
||||
forumTopicId: 18335
|
||||
dashedName: understanding-uninitialized-variables
|
||||
---
|
||||
|
||||
# --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"`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Initialize the three variables `a`, `b`, and `c` with `5`, `10`, and `"I am a"` respectively so that they will not be `undefined`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`a` should be defined and evaluated to have the value of `6`.
|
||||
|
||||
```js
|
||||
assert(typeof a === 'number' && a === 6);
|
||||
```
|
||||
|
||||
`b` should be defined and evaluated to have the value of `15`.
|
||||
|
||||
```js
|
||||
assert(typeof b === 'number' && b === 15);
|
||||
```
|
||||
|
||||
`c` should not contain `undefined` and should have a value of "I am a String!"
|
||||
|
||||
```js
|
||||
assert(!/undefined/.test(c) && c === 'I am a String!');
|
||||
```
|
||||
|
||||
You should not change code below the specified comment.
|
||||
|
||||
```js
|
||||
assert(
|
||||
/a = a \+ 1;/.test(code) &&
|
||||
/b = b \+ 5;/.test(code) &&
|
||||
/c = c \+ " String!";/.test(code)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(a,b,c){ return "a = " + a + ", b = " + b + ", c = '" + c + "'"; })(a,b,c);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Only change code below this line
|
||||
var a;
|
||||
var b;
|
||||
var c;
|
||||
// Only change code above this line
|
||||
|
||||
a = a + 1;
|
||||
b = b + 5;
|
||||
c = c + " String!";
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var a = 5;
|
||||
var b = 10;
|
||||
var c = "I am a";
|
||||
a = a + 1;
|
||||
b = b + 5;
|
||||
c = c + " String!";
|
||||
```
|
@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392d1
|
||||
title: Updating Object Properties
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c9yEJT4'
|
||||
forumTopicId: 18336
|
||||
dashedName: updating-object-properties
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
After you've created a JavaScript object, you can update its properties at any time just like you would update any other variable. You can use either dot or bracket notation to update.
|
||||
|
||||
For example, let's look at `ourDog`:
|
||||
|
||||
```js
|
||||
var ourDog = {
|
||||
"name": "Camper",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["everything!"]
|
||||
};
|
||||
```
|
||||
|
||||
Since he's a particularly happy dog, let's change his name to "Happy Camper". Here's how we update his object's name property: `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--
|
||||
|
||||
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--
|
||||
|
||||
You should update `myDog`'s `"name"` property to equal "Happy Coder".
|
||||
|
||||
```js
|
||||
assert(/happy coder/gi.test(myDog.name));
|
||||
```
|
||||
|
||||
You should not edit the `myDog` definition.
|
||||
|
||||
```js
|
||||
assert(/"name": "Coder"/.test(code));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(z){return z;})(myDog);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myDog = {
|
||||
"name": "Coder",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["freeCodeCamp Campers"]
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myDog = {
|
||||
"name": "Coder",
|
||||
"legs": 4,
|
||||
"tails": 1,
|
||||
"friends": ["freeCodeCamp Campers"]
|
||||
};
|
||||
myDog.name = "Happy Coder";
|
||||
```
|
@ -0,0 +1,72 @@
|
||||
---
|
||||
id: bd7123c9c549eddfaeb5bdef
|
||||
title: Use Bracket Notation to Find the First Character in a String
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ca8JwhW'
|
||||
forumTopicId: 18341
|
||||
dashedName: use-bracket-notation-to-find-the-first-character-in-a-string
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
<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.
|
||||
|
||||
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:
|
||||
|
||||
```js
|
||||
var firstName = "Charles";
|
||||
var firstLetter = firstName[0]; // firstLetter is "C"
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use bracket notation to find the first character in the `lastName` variable and assign it to `firstLetterOfLastName`.
|
||||
|
||||
**Hint:** Try looking at the example above if you get stuck.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `firstLetterOfLastName` variable should have the value of `L`.
|
||||
|
||||
```js
|
||||
assert(firstLetterOfLastName === 'L');
|
||||
```
|
||||
|
||||
You should use bracket notation.
|
||||
|
||||
```js
|
||||
assert(code.match(/firstLetterOfLastName\s*?=\s*?lastName\[.*?\]/));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(v){return v;})(firstLetterOfLastName);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var firstLetterOfLastName = "";
|
||||
var lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
firstLetterOfLastName = lastName; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var firstLetterOfLastName = "";
|
||||
var lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
firstLetterOfLastName = lastName[0];
|
||||
```
|
@ -0,0 +1,66 @@
|
||||
---
|
||||
id: bd7123c9c451eddfaeb5bdef
|
||||
title: Use Bracket Notation to Find the Last Character in a String
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cBZQGcv'
|
||||
forumTopicId: 18342
|
||||
dashedName: use-bracket-notation-to-find-the-last-character-in-a-string
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In order to get the last letter of a string, you can subtract one from the string's length.
|
||||
|
||||
For example, if `var firstName = "Charles"`, you can get the value of the last letter of the string by using `firstName[firstName.length - 1]`.
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
var firstName = "Charles";
|
||||
var lastLetter = firstName[firstName.length - 1]; // lastLetter is "s"
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use <dfn>bracket notation</dfn> to find the last character in the `lastName` variable.
|
||||
|
||||
**Hint:** Try looking at the example above if you get stuck.
|
||||
|
||||
# --hints--
|
||||
|
||||
`lastLetterOfLastName` should be "e".
|
||||
|
||||
```js
|
||||
assert(lastLetterOfLastName === 'e');
|
||||
```
|
||||
|
||||
You should use `.length` to get the last letter.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.length/g).length > 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(v){return v;})(lastLetterOfLastName);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
var lastLetterOfLastName = lastName; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var lastName = "Lovelace";
|
||||
var lastLetterOfLastName = lastName[lastName.length - 1];
|
||||
```
|
@ -0,0 +1,66 @@
|
||||
---
|
||||
id: bd7123c9c450eddfaeb5bdef
|
||||
title: Use Bracket Notation to Find the Nth Character in a String
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cWPVJua'
|
||||
forumTopicId: 18343
|
||||
dashedName: use-bracket-notation-to-find-the-nth-character-in-a-string
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
You can also use <dfn>bracket notation</dfn> to get the character at other positions within a string.
|
||||
|
||||
Remember that computers start counting at `0`, so the first character is actually the zeroth character.
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
var firstName = "Ada";
|
||||
var secondLetterOfFirstName = firstName[1]; // secondLetterOfFirstName is "d"
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Let's try to set `thirdLetterOfLastName` to equal the third letter of the `lastName` variable using bracket notation.
|
||||
|
||||
**Hint:** Try looking at the example above if you get stuck.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `thirdLetterOfLastName` variable should have the value of `v`.
|
||||
|
||||
```js
|
||||
assert(thirdLetterOfLastName === 'v');
|
||||
```
|
||||
|
||||
You should use bracket notation.
|
||||
|
||||
```js
|
||||
assert(code.match(/thirdLetterOfLastName\s*?=\s*?lastName\[.*?\]/));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
(function(v){return v;})(thirdLetterOfLastName);
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
var thirdLetterOfLastName = lastName; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var lastName = "Lovelace";
|
||||
var thirdLetterOfLastName = lastName[2];
|
||||
```
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user