fix(guide): restructure curriculum guide articles (#36501)

* fix: restructure certifications guide articles
* fix: added 3 dashes line before prob expl
* fix: added 3 dashes line before hints
* fix: added 3 dashes line before solutions
This commit is contained in:
Randell Dawson
2019-07-24 00:59:27 -07:00
committed by mrugesh
parent c911e77eed
commit 1494a50123
990 changed files with 13202 additions and 8628 deletions

View File

@@ -1,11 +1,11 @@
---
title: Boo Who
---
![](//discourse-user-assets.s3.amazonaws.com/original/2X/3/3c8584a085a0deaea66b3400e6321eeadab552a2.jpg)
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
# Boo Who
### Problem Explanation:
---
## Problem Explanation
This program is very simple, the trick is to understand what a boolean primitive is. The programs requires a true or false answer.
@@ -13,50 +13,42 @@ This program is very simple, the trick is to understand what a boolean primitive
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean' target='_blank' rel='nofollow'>Boolean</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
* You will need to check for the type of the parameter to see if it is a boolean.
---
## Hints
> _try to solve the problem now_
### Hint 1
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
You will need to check for the type of the parameter to see if it is a boolean.
* To check for the type of a parameter, you can use `typeof`.
### Hint 2
To check for the type of a parameter, you can use `typeof`.
> _try to solve the problem now_
### Hint 3
Since you must return true or false you can use if statements or just have it return the boolean used for the if statement.
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
* Since you must return true or false you can use if statements or just have it return the boolean used for the if statement.
> _try to solve the problem now_
---
## Solutions
## Spoiler Alert!
<details><summary>Solution 1 (Click to Show/Hide)</summary>
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
```javascript
function booWho(bool) {
return typeof bool === 'boolean';
}
function booWho(bool) {
return typeof bool === "boolean";
}
// test here
booWho(null);
// test here
booWho(null);
```
# Code Explanation:
#### Code Explanation
Uses the operator `typeof` to check if the variable is a boolean. If it is, it will return `true`. Otherwise, if it is any other type it will return `false`.
* Uses the operator `typeof` to check if the variable is a boolean. If it is, it will return `true`. Otherwise, if it is any other type it will return `false`.
#### Relevant Links
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof' target='_blank' rel='nofollow'>typeof</a>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,11 +1,11 @@
---
title: Chunky Monkey
---
![](//discourse-user-assets.s3.amazonaws.com/original/2X/a/aadd6bead83ab7d79a795c326f005a89e6ad81f5.png)
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
# Chunky Monkey
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
---
## Problem Explanation
Our goal for this Algorithm is to split `arr` (first argument) into smaller chunks of arrays with the length provided by `size` (second argument). There are 4 green checks (objectives) our code needs to pass in order to complete this Algorithm:
@@ -19,56 +19,52 @@ Our goal for this Algorithm is to split `arr` (first argument) into smaller chun
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push' rel='nofollow'>Array.push()</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice' target='_blank' rel='nofollow'>Array.slice()</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
The links above suggest to use `Array.push()`, so let's start by first creating a new array to store the smaller arrays we will soon have like this:
```javascript
var newArray = [];
```
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:")</a> Hint: 2
```javascript
var newArray = [];
```
### Hint 2
Next we'll need a `for loop` to loop through `arr`.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 3
Finally, we need a method to do the actual splitting and we can use `Array.slice()` to do that. The key to this Algorithm is understanding how a `for loop`, `size`, `Array.slice()` and `Array.push()` all work together.
> _try to solve the problem now_
## Spoiler Alert!
---
## Solutions
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
<details><summary>Solution 1 (Click to Show/Hide)</summary>
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
```javascript
function chunkArrayInGroups(arr, size) {
function chunkArrayInGroups(arr, size) {
var temp = [];
var result = [];
var temp = [];
var result = [];
for (var a = 0; a < arr.length; a++) {
if (a % size !== size - 1)
temp.push(arr[a]);
else {
temp.push(arr[a]);
result.push(temp);
temp = [];
}
}
if (temp.length !== 0)
result.push(temp);
return result;
for (var a = 0; a < arr.length; a++) {
if (a % size !== size - 1) temp.push(arr[a]);
else {
temp.push(arr[a]);
result.push(temp);
temp = [];
}
}
if (temp.length !== 0) result.push(temp);
return result;
}
```
### Code Explanation:
#### Code Explanation
* Firstly, we create two empty arrays called `temp` and `result`, which we will eventually return.
* Our **for loop** loops until `a` is equal to or more than the length of the array in our test.
@@ -82,19 +78,22 @@ Finally, we need a method to do the actual splitting and we can use `Array.slice
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push' rel='nofollow'>Array.push()</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for' target='_blank' rel='nofollow'>For Loops</a>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
</details>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
```javascript
function chunkArrayInGroups(arr, size) {
// Break it up.
var arr2 = [];
for (var i = 0; i < arr.length; i+=size) {
arr2.push(arr.slice(i , i+size));
}
return arr2;
}
function chunkArrayInGroups(arr, size) {
// Break it up.
var arr2 = [];
for (var i = 0; i < arr.length; i += size) {
arr2.push(arr.slice(i, i + size));
}
return arr2;
}
```
### Code Explanation:
#### Code Explanation
* First, we create an empty array `arr2` where we will store our 'chunks'.
* The for loop starts at zero, increments by `size` each time through the loop, and stops when it reaches `arr.length`.
@@ -108,23 +107,26 @@ Finally, we need a method to do the actual splitting and we can use `Array.slice
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice' target='_blank' rel='nofollow'>Array.slice()</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for' target='_blank' rel='nofollow'>For Loops</a>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
```javascript
function chunkArrayInGroups(arr, size) {
// Break it up.
var newArr = [];
var i = 0;
</details>
while (i < arr.length) {
newArr.push(arr.slice(i, i+size));
i += size;
}
return newArr;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
<details><summary>Solution 3 (Click to Show/Hide)</summary>
```javascript
function chunkArrayInGroups(arr, size) {
// Break it up.
var newArr = [];
var i = 0;
while (i < arr.length) {
newArr.push(arr.slice(i, i + size));
i += size;
}
return newArr;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
```
### Code Explanation:
#### Code Explanation
* Firstly, we create two variables. `newArr` is an empty array which we will push to. We also have the `i` variable set to zero, for use in our while loop.
* Our while loop loops until `i` is equal to or more than the length of the array in our test.
@@ -141,18 +143,21 @@ Finally, we need a method to do the actual splitting and we can use `Array.slice
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice' target='_blank' rel='nofollow'>Array.slice()</a>
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/while' target='_blank' rel='nofollow'>While Loops</a>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution 2:
</details>
<details><summary>Solution 4 (Click to Show/Hide)</summary>
```javascript
function chunkArrayInGroups(arr, size) {
var newArr = [];
while (arr.length) {
newArr.push(arr.splice(0,size));
}
return newArr;
}
function chunkArrayInGroups(arr, size) {
var newArr = [];
while (arr.length) {
newArr.push(arr.splice(0, size));
}
return newArr;
}
```
### Code Explanation:
#### Code Explanation
* Firstly, we create a variable. `newArr` is an empty array which we will push to.
* Our `while` loop loops until the length of the array in our test is not 0.
@@ -166,19 +171,23 @@ Finally, we need a method to do the actual splitting and we can use `Array.slice
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice' target='_blank' rel='nofollow'>Array.splice()</a>
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/while' target='_blank' rel='nofollow'>While Loops</a>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution 3:
</details>
<details><summary>Solution 5 (Click to Show/Hide)</summary>
```javascript
function chunkArrayInGroups(arr, size) {
if (arr.length <= size){
return [arr];
}
else {
return [arr.slice(0,size)].concat(chunkArrayInGroups(arr.slice(size),size));
}
}
function chunkArrayInGroups(arr, size) {
if (arr.length <= size) {
return [arr];
} else {
return [arr.slice(0, size)].concat(
chunkArrayInGroups(arr.slice(size), size)
);
}
}
```
### Code Explanation:
#### Code Explanation
* Array smaller than size is returned nested.
* For any array larger than size, it is split in two. First segment is nested and concatenated with second segment which makes a recursive call.
@@ -187,9 +196,4 @@ Finally, we need a method to do the actual splitting and we can use `Array.slice
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#Recursion' target='_blank' rel='nofollow'>Recursion</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice' target='_blank' rel='nofollow'>Array.slice()</a>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,26 +1,27 @@
---
title: Confirm the Ending
---
## Confirm the Ending
# Confirm the Ending
---
## Solutions
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
# 🌻 Intermediate Code Solution:
<details><summary>Solution 1 (Click to Show/Hide)</summary>
(Declarative approach)
```javascript
function confirmEnding(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
return str.slice(str.length - target.length) === target;
}
confirmEnding("He has to give me a new name", "name");
```
# Code Explanation:
#### Code Explanation
- First we use the `slice` method copy the string.
- In order to get the last characters in `str` equivalent to the `target`'s length we use the `slice` method.
- The first parameter inside the `slice` method is the starting index and the second parameter would be the ending index.
@@ -29,33 +30,34 @@ confirmEnding("He has to give me a new name", "name");
- We substract the length of `str` and the length of `target`, that way, we shall get the last remaining characters equivalent to the `target`'s length.
- Finally we compare the return result of slice to `target` and check if they have the same characters.
### Relevant Links
#### Relevant Links
- [String.prototype.slice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice)
</details>
# ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:")Advanced Code Solution:
<details><summary>Solution 2 (Click to Show/Hide)</summary>
(using Regular Expression)
```javascript
```javascript
function confirmEnding(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
let re = new RegExp(target+'$','i');
let re = new RegExp(target + "$", "i");
return re.test(str);
}
console.log(confirmEnding("Bastian", "n"));
```
## Code Explanation:
#### Code Explanation
- We need to make a pattern from the `target` variable that exists at the end of the string `str`.
- Since we will use a variable that will change the pattern each time the function is called, we will use the constructor of the regular expression object `new RegExp(pattern[, flags])`, so we start with: `new RegExp(target)`.
- Then we have to check at the end of the string, so we concatenate to the `target` variable the `$` character to match the end: `new RegExp(target+'$')`.
- We use the flag `i` to ignore the case of the pattern and we have our completed RegExp: `new RegExp(target+'$','i')`, or we can ommit the flag entirely.
- Finally, we are using our regular expression with the `test` method to the given string, to check if the string ends with the pattern and return true or false accordingly.
### Relevant Links
#### Relevant Links
- [RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)
- [RegExp.prototype.test()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test)
</details>

View File

@@ -1,9 +1,11 @@
---
title: Convert Celsius to Fahrenheit
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
# Convert Celsius to Fahrenheit
---
## Problem Explanation
The algorithm to convert from Celsius to Fahrenheit is the temperature in Celsius times `9/5`, plus `32`.
@@ -14,48 +16,43 @@ You are given a variable **celsius** representing a temperature in Celsius. Use
* <a href='http://www.purplemath.com/modules/orderops.htm' target='_blank' rel='nofollow'>The Order of Operations: PEMDAS</a>
* <a href='https://www.khanacademy.org/math/pre-algebra/order-of-operations/order_of_operations/v/order-of-operations' target='_blank' rel='nofollow'>Order of Operation: Video</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
Take a look at the code. There is an area that you're not supposed to edit. From there, ask yourself - what is used there that I haven't seen before?
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
Keep in mind the **order of operation** check the link in the _links_ section for more information.
> _try to solve the problem now_
## Spoiler Alert!
---
## Solutions
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
<details><summary>Solution 1 (Click to Show/Hide)</summary>
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
```javascript
function convertToF(celsius) {
// Only change code below this line
var fahrenheit = (celsius * (9/5)) + 32;
function convertToF(celsius) {
// Only change code below this line
var fahrenheit = celsius * (9 / 5) + 32;
// Only change code above this line
if ( typeof fahrenheit !== 'undefined' ) {
return fahrenheit;
} else {
return 'fahrenheit not defined';
}
}
// Only change code above this line
if (typeof fahrenheit !== "undefined") {
return fahrenheit;
} else {
return "fahrenheit not defined";
}
}
// Change the inputs below to test your code
convertToF(30);
// Change the inputs below to test your code
convertToF(30);
```
### Code Explanation:
#### Code Explanation
* Declare the **fahrenheit** variable.
* Make sure the proper order of arithmetic operations is followed by using parenthesis (`()`) when needed.
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,20 +1,19 @@
---
title: Factorialize a Number
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
## Hints for Solution
# Factorialize a Number
### ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint:
---
## Hints
### Hint 1
You know your solution should return `1` when the number passed to the function is `0` or `1`. Also, the final value returned will be the product of all the numbers between 1 and the number (inclusive). If you initialize the value for the product to `1`, then think how you could start at the given number and continue decrementing this number until a specific value while multiplying the product by the number at each step.
> _try to solve the problem now_
## Hints for a Recursive Solution
### ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
**Recursive Solution**
This one starts easily since `0! = 1`, so you can go ahead and simply `return 1` there.
@@ -22,23 +21,17 @@ We can use that as an `if` in order to break the loop we're going to create usin
This is also why **instead** of having _"finished"_, a function is always said to _"have returned"_. And now this...
> _try to solve the problem now_
### ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
**Understanding recursion**
Recursion refers to a function repeating (calling) itself. In this case we are basically returning the given number (i.e. 5), multiplied by the function itself but this time the value passed to the _num_ parameter is `num-1` (which initially translates to 4). The very function is going to **run inside itself** interesting, eh?
> _try to solve the problem now_
### ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
**Understanding the flow**
The first **returned** value can be visualized better if you think about those parenthesis operations you did in secondary school where you do the math inside every parenthesis from inside out, bracket and square bracket until you get a final result (a total). This time it's the same thing, look at the program flow:
#### During the first execution of the function:
**During the first execution of the function:**
[**num** = 5]
@@ -50,7 +43,7 @@ Is 5 _equal_ to 1 or 0? **No** ---> Oki doki, let's continue...
What it returns can be viewed as `(5*(4*(3*(2*1))))` or just `5 * 4 * 3 * 2 * 1`, and the function will return the result of that operation: `120`. Now, let's check what the rest of the executions do:
#### During the rest of the executions:
**During the rest of the executions**:
**Second Execution**: _num_ = 5-1 = **4** -> is _num_ 0 or 1? No
@@ -68,24 +61,17 @@ What it returns can be viewed as `(5*(4*(3*(2*1))))` or just `5 * 4 * 3 * 2 * 1`
--> return **1**. And this is where the recursion stops because there are no more executions.
Got it? ![:wink:](https://forum.freecodecamp.com/images/emoji/emoji_one/wink.png?v=3 ":wink:")
> _try to solve the problem now_
### Relevant Links
#### Relevant Links
* <a href='https://www.youtube.com/watch?v=R8SjM4DKK80' target='_blank' rel='nofollow'>JS Functions</a>
* <a href='https://www.youtube.com/watch?v=k7-N8R0-KY4' target='_blank' rel='nofollow'>Recursion in JS</a>
## Spoiler Alert!
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
---
## Solutions
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution #1:
<details><summary>Click to see solution</summary>
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
function factorialize(num) {
@@ -98,39 +84,39 @@ function factorialize(num) {
factorialize(5);
```
#### Code Explanation:
#### Code Explanation
- Since the return values for the function will always be greater than or equal to 1, `product` is initialized at one. For the case where the number is `0`, the for loop condition will be false, but since `product` is initialized as `1`, it will have the correct value when the `return` statement is executed.
- For all numbers passed to the function which are greater than one, the simple `for` loop will decrement `num` by one each iteration and recalculate `product` down to the value `1`.
</details><br>
</details>
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution #2 (using Recursion):
<details><summary>Click to see solution</summary>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
(using Recursion)
```js
function factorialize(num) {
if (num === 0) { return 1; }
return num * factorialize(num-1);
if (num === 0) {
return 1;
}
return num * factorialize(num - 1);
}
factorialize(5);
```
#### Code Explanation:
#### Code Explanation
Notice at the first line we have the terminal condition, i.e a condition to check the end of the recursion. If `num == 0`, then we return 1, i.e. effectively ending the recursion and informing the stack to propagate this value to the upper levels. If we do not have this condition, the recursion would go on until the stack space gets consumed, thereby resulting in a <a href='https://en.wikipedia.org/wiki/Stack_overflow' target='_blank' rel='nofollow'>Stack Overflow</a>.
### Relevant Links
#### Relevant Links
* <a href='https://www.codecademy.com/en/courses/javascript-lesson-205/0/1' target='_blank' rel='nofollow'>Recursion</a>
* <a href='https://en.wikipedia.org/wiki/Factorial' target='_blank' rel='nofollow'>Factorialization</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators' target='_blank' rel='nofollow'>Arithmetic Operators</a>
</details><br>
</details>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
<details><summary>Click to see solution</summary>
<details><summary>Solution 3 (Click to Show/Hide)</summary>
```js
function factorialize(num, factorial = 1) {
@@ -144,23 +130,17 @@ function factorialize(num, factorial = 1) {
factorialize(5);
```
#### Code Explanation:
#### Code Explanation
In this solution, we use <a href='https://stackoverflow.com/questions/33923/what-is-tail-recursion' target='_blank' rel='nofollow'>Tail Recursion</a> to optimize the the memory use.
* In this solution, we use <a href='https://stackoverflow.com/questions/33923/what-is-tail-recursion' target='_blank' rel='nofollow'>Tail Recursion</a> to optimize the the memory use.
In traditional head recursion, the typical model is that you perform your recursive calls first, and then you take the return value of the recursive call and calculate the result. In this manner, you don't get the result of your calculation until you have returned from every recursive call.
* In traditional head recursion, the typical model is that you perform your recursive calls first, and then you take the return value of the recursive call and calculate the result. In this manner, you don't get the result of your calculation until you have returned from every recursive call.
In tail recursion, you perform your calculations first, and then you execute the recursive call, passing the results of your current step to the next recursive step. This results in the last statement being in the form of (return (recursive-function params)).
* In tail recursion, you perform your calculations first, and then you execute the recursive call, passing the results of your current step to the next recursive step. This results in the last statement being in the form of (return (recursive-function params)).
In this solution, with each evaluation of the recursive call, the factorial is updated. This is different from the head-recursive solution where all evaluation calculations are stored on the stack until the base case is reached.
* In this solution, with each evaluation of the recursive call, the factorial is updated. This is different from the head-recursive solution where all evaluation calculations are stored on the stack until the base case is reached.
### Relevant Links
#### Relevant Links
* <a href='https://www.geeksforgeeks.org/tail-recursion/' target='_blank' rel='nofollow'>Tail Recursion</a>
</details><br>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,11 +1,11 @@
---
title: Falsy Bouncer
---
![](//discourse-user-assets.s3.amazonaws.com/original/2X/5/55dedad40d9f3f662c70d1eac4effc00c7d26bd9.jpg)
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
# Falsy Bouncer
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
---
## Problem Explanation
Remove all <a href='https://guide.freecodecamp.org/javascript/falsy-values/' target='_blank' rel='nofollow'>falsy</a> values from an array.
@@ -13,49 +13,44 @@ Remove all <a href='https://guide.freecodecamp.org/javascript/falsy-values/' tar
* <a href='https://guide.freecodecamp.org/javascript/falsy-values/' target='_blank' rel='nofollow'>Falsy Values</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
Falsy is something which evaluates to FALSE. There are only six falsy values in JavaScript: undefined, null, NaN, 0, "" (empty string), and false of course.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
We need to make sure we have all the falsy values to compare, we can know it, maybe with a function with all the falsy values...
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 3
Then we need to add a `filter()` with the falsy values function...
> _try to solve the problem now_
## Spoiler Alert!
---
## Solutions
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
function bouncer(arr) {
let newArray = [];
for (var i = 0; i < arr.length; i++){
if (arr[i])
newArray.push(arr[i]);
for (var i = 0; i < arr.length; i++) {
if (arr[i]) newArray.push(arr[i]);
}
return newArray;
}
```
### Code Explanation:
We create a new empty array.
We use a for cycle to iterate over all elements of the provided array (arr).
We use the if statement to check if the current element is <a href='http://forum.freecodecamp.com/t/javascript-truthy-value/15975' target='_blank' rel='nofollow'>truthy</a> or <a href='https://guide.freecodecamp.org/javascript/falsy-values/' target='_blank' rel='nofollow'>falsy</a>.
If the element is truthy, we push it to the new array (newArray). This result in the new array (newArray) containing only truthy elements.
We return the new array (newArray).
#### Code Explanation
* We create a new empty array.
* We use a for cycle to iterate over all elements of the provided array (arr).
* We use the if statement to check if the current element is <a href='http://forum.freecodecamp.com/t/javascript-truthy-value/15975' target='_blank' rel='nofollow'>truthy</a> or <a href='https://guide.freecodecamp.org/javascript/falsy-values/' target='_blank' rel='nofollow'>falsy</a>.
* If the element is truthy, we push it to the new array (newArray). This result in the new array (newArray) containing only truthy elements.
* We return the new array (newArray).
#### Relevant Links
@@ -64,30 +59,23 @@ We return the new array (newArray).
* [Falsey values](https://www.freecodecamp.org/forum/t/javascript-falsy-values/14664)
* [Array.prototype.push](https://www.freecodecamp.org/forum/t/javascript-array-prototype-push/14298)
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
</details>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
```js
function bouncer(arr) {
return arr.filter(Boolean);
}
function bouncer(arr) {
return arr.filter(Boolean);
}
```
### Code Explanation:
#### Code Explanation
The `Array.prototype.filter` method expects a function that returns a `Boolean` value which takes a single argument and returns `true` for <a href='http://forum.freecodecamp.com/t/javascript-truthy-value/15975' target='_blank' rel='nofollow'>truthy</a> value or `false` for <a href='https://guide.freecodecamp.org/javascript/falsy-values/' target='_blank' rel='nofollow'>falsy</a> value. Hence we pass the built-in `Boolean` function.
* The `Array.prototype.filter` method expects a function that returns a `Boolean` value which takes a single argument and returns `true` for <a href='http://forum.freecodecamp.com/t/javascript-truthy-value/15975' target='_blank' rel='nofollow'>truthy</a> value or `false` for <a href='https://guide.freecodecamp.org/javascript/falsy-values/' target='_blank' rel='nofollow'>falsy</a> value. Hence we pass the built-in `Boolean` function.
#### Relevant Links
* <a href='http://forum.freecodecamp.com/t/javascript-boolean/14311' target='_blank' rel='nofollow'>Boolean</a>
* <a href='http://forum.freecodecamp.com/t/javascript-truthy-value/15975' target='_blank' rel='nofollow'>Truthy</a>
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-filter/14289' target='_blank' rel='nofollow'>Array.prototype.filter()</a>
## ![:trophy:](https://forum.freecodecamp.com/images/emoji/emoji_one/trophy.png?v=3 ":trophy:") Credits:
If you found this page useful, you can give thanks by copying and pasting this on the main chat:
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,9 +1,11 @@
---
title: Find the Longest Word in a String
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
# Find the Longest Word in a String
---
## Problem Explanation
You have to go through each word and figure out which one is the longest and return not the word, but how many characters it has.
@@ -11,31 +13,29 @@ You have to go through each word and figure out which one is the longest and ret
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length' target='_blank' rel='nofollow'>JS String Length</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
You should split the string into an array of words.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
You will need to figure out a way to keep track globally of the greatest current length.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 3
Remember how to get the length of elements on the array? `Array[index].length`.
> _try to solve the problem now_
## Spoiler Alert!
---
## Solutions
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
<details><summary>Solution 1 (Click to Show/Hide)</summary>
function findLongestWordLength(str) {
var words = str.split(' ');
@@ -51,7 +51,7 @@ Remember how to get the length of elements on the array? `Array[index].length`.
}
### Code Explanation:
#### Code Explanation
Take the string and convert it into an array of words. Declare a variable to keep track of the maximum length and loop from 0 to the length of the array of words.
@@ -61,7 +61,7 @@ Then check for the longest word by comparing the current word to the previous on
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/length' target='_blank' rel='nofollow'>JS Array.length</a>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
<details><summary>Solution 2 (Click to Show/Hide)</summary>
**Using `.reduce()`**
@@ -73,7 +73,7 @@ Then check for the longest word by comparing the current word to the previous on
}
### Code Explanation:
#### Code Explanation
For more information on `reduce` <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce' target='_blank' rel='nofollow'>click here.</a>
@@ -85,17 +85,19 @@ In case you're wondering about that `0` after the callback function, it is used
* <a href='http://forum.freecodecamp.com/t/using-array-prototype-reduce-to-reduce-conceptual-boilerplate-for-problems-on-arrays/14687' target='_blank' rel='nofollow'>JS Reduce Made Easy</a>
* <a href='http://forum.freecodecamp.com/t/javascript-math-max/14682.md' target='_blank' rel='nofollow'>JS Math Max</a>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution 2:
</details>
<details><summary>Solution 3 (Click to Show/Hide)</summary>
**Using `.map()`**
```javascript
function findLongestWordLength(str) {
return Math.max(...str.split(" ").map(word => word.length));
return Math.max(...str.split(" ").map(word => word.length));
}
```
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/6' target='_blank' rel='nofollow'>Run Code</a>
### Code Explanation:
#### Code Explanation
We provide `Math.max` with the length of each word as argument, and it will simply return the highest of all.
@@ -110,40 +112,41 @@ Then, we will make another array, made from the lengths of each element of the `
Finally, we pass the array as argument for the Math.max function with the spread operator `...`
For more information on `map` <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map' target='_blank' rel='nofollow'>click here.</a>
</details>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
<details><summary>Solution 4 (Click to Show/Hide)</summary>
**Using recursiveness**
**Using recursion**
function findLongestWordLength(str) {
```js
function findLongestWordLength(str) {
//split the string into individual words
//(important!!, you'll see why later)
str = str.split(" ");
//split the string into individual words
//(important!!, you'll see why later)
str = str.split(" ");
//str only has 1 element left that is the longest element,
//return the length of that element
if (str.length == 1) {
return str[0].length;
}
//str only has 1 element left that is the longest element,
//return the length of that element
if(str.length == 1){
return str[0].length;
}
//if the first element's length is greater than the second element's (or equal)
//remove the second element and recursively call the function)
if (str[0].length >= str[1].length) {
str.splice(1, 1);
return findLongestWordLength(str.join(" "));
}
//if the first element's length is greater than the second element's (or equal)
//remove the second element and recursively call the function)
if(str[0].length >= str[1].length){
str.splice(1,1);
return findLongestWordLength(str.join(" "));
}
//if the second element's length is greater thant the first element's start
//call the function past the first element
if (str[0].length <= str[1].length) {
// from the first element to the last element inclusive.
return findLongestWordLength(str.slice(1, str.length).join(" "));
}
}
```
//if the second element's length is greater thant the first element's start
//call the function past the first element
if(str[0].length <= str[1].length){
// from the first element to the last element inclusive.
return findLongestWordLength(str.slice(1,str.length).join(" "));
}
}
### Code Explanation:
#### Code Explanation
The first line splits the string into individual words. Then we check if `str` only has 1 element left then that is the longest element and we return it. If the first element's length is greater than the second element's (or equal), we remove the second element and recursively call the function `findLongestWord`. However, if the second element's length is greater thant the first element's start, then we call the function past the first element.
@@ -152,8 +155,4 @@ The first line splits the string into individual words. Then we check if `str` o
* <a href='https://www.youtube.com/watch?v=R8SjM4DKK80' target='_blank' rel='nofollow'>JS Functions</a>
* <a href='https://www.youtube.com/watch?v=k7-N8R0-KY4' target='_blank' rel='nofollow'>Recursion Basics</a>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,52 +1,59 @@
---
title: Finders Keepers
---
![](//discourse-user-assets.s3.amazonaws.com/original/2X/f/ff2fd8ffa014eea28587a8ef4933340d3dcc4b09.jpg)
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
## ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
# Finders Keepers
---
## Problem Explanation
We need to return the element from an array that passes a function. Both the `function` and the `array` are passed into our function `findElement(arr, func)`.
## Hint: 1
Looking through the array can be done with a `for` loop.
>*try to solve the problem now*
## Hint: 2
---
## Hints
### Hint 1
We need to return the element from an array that passes a function. Both the `function` and the `array` are passed into our function `findElement(arr, func)`. Looking through the array can be done with a `for` loop.
### Hint 2
`num` is passed to the function. We will need to set it to the elements we want to check with the function.
>*try to solve the problem now*
## Hint: 3
### Hint 3
Do not forget, if none of the numbers in the array pass the test, it should return `undefined`.
>*try to solve the problem now*
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function findElement(arr, func) {
let num = 0;
for(var i = 0; i < arr.length; i++) {
for (var i = 0; i < arr.length; i++) {
num = arr[i];
if (func(num)) {
return num;
}
}
return undefined;
}
```
## Code Explanation
#### Code Explanation
* Challenge asks us to look through array. This is done using a `for` loop.
* The `num` variable is being passed into the function, so we set it to each index in our array.
* The pre-defined function already checks each number for us, so if it is "true", we return that num.
* If none of the numbers in the array pass the function's test, we return undefined.
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
</details>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
```javascript
function findElement(arr, func) {
return arr.find(func);
@@ -57,23 +64,21 @@ function findElement(arr, func) {
* [Array.prototype.find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
</details>
<details><summary>Solution 3 (Click to Show/Hide)</summary>
```javascript
function findElement(arr, func) {
return arr[(arr.map(func)).indexOf(true)];
return arr[arr.map(func).indexOf(true)];
}
```
## Code Explanation
#### Code Explanation
1. Look through the array given in the 1st paramater "arr" using the .map() method
2. Use the function in the 2nd parameter as the callback function in arr.map()
3. Acquire the index of the first number that meets the condition in the function.
4. Use that index to display the first available number that meets the condition.
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories -- **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,13 +1,11 @@
---
title: Basic Algorithm Scripting
---
## Basic Algorithm Scripting
# Basic Algorithm Scripting
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/quadratic-equations/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@@ -1,9 +1,11 @@
---
title: Mutations
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
# Mutations
---
## Problem Explanation
* Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array..
@@ -11,46 +13,44 @@ title: Mutations
* <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-indexof/15936' target='_blank' rel='nofollow'>String.indexOf()</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
* If everything is lowercase it will be easier to compare.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
* Our strings might be easier to work with if they were arrays of characters.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 3
* A loop might help. Use `indexOf()` to check if the letter of the second word is on the first.
> _try to solve the problem now_
## Spoiler Alert!
---
## Solutions
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
<details><summary>Solution 1 (Click to Show/Hide)</summary>
**Procedural**
function mutation(arr) {
var test = arr[1].toLowerCase();
var target = arr[0].toLowerCase();
for (var i=0;i<test.length;i++) {
if (target.indexOf(test[i]) < 0)
return false;
}
return true;
}
```js
function mutation(arr) {
var test = arr[1].toLowerCase();
var target = arr[0].toLowerCase();
for (var i = 0; i < test.length; i++) {
if (target.indexOf(test[i]) < 0) return false;
}
return true;
}
```
### Code Explanation:
#### Code Explanation
First we make the two strings in the array lowercase. `test` will hold what we are looking for in `target`.
Then we loop through our test characters and if any of them is not found we `return false`.
@@ -62,21 +62,24 @@ If they are _all_ found, the loop will finish without returning anything and we
* <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-tolowercase/15948' target='_blank' rel='nofollow'>String.toLowerCase()</a>
* <a href='http://forum.freecodecamp.com/t/javascript-for-loop/14666s-Explained' target='_blank' rel='nofollow'>For loops</a>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
</details>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
**Declarative**
function mutation(arr) {
return arr[1].toLowerCase()
.split('')
.every(function(letter) {
return arr[0].toLowerCase()
.indexOf(letter) != -1;
});
}
```js
function mutation(arr) {
return arr[1]
.toLowerCase()
.split("")
.every(function(letter) {
return arr[0].toLowerCase().indexOf(letter) != -1;
});
}
```
### Code Explanation:
#### Code Explanation
Grab the second string, lowercase and turn it into an array; then make sure _every_ one of its _letters_ is a part of the lowercased first string.
@@ -87,8 +90,4 @@ Grab the second string, lowercase and turn it into an array; then make sure _eve
* <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-split/15944' target='_blank' rel='nofollow'>Array.split()</a>
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-every/14287' target='_blank' rel='nofollow'>Array.every()</a>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,9 +1,11 @@
---
title: Repeat a String Repeat a String
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
# Repeat a String Repeat a String
---
## Problem Explanation
The program is very simple, we have to take a variable and return that variable being repeated certain amount of times. No need to add space or anything, just keep repeating it into one single string.
@@ -11,45 +13,47 @@ The program is very simple, we have to take a variable and return that variable
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String' target='_blank' rel='nofollow'>Global String Object</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
The program is very simple, we have to take a variable and return that variable being repeated certain amount of times. No need to add space or anything, just keep repeating it into one single string.
### Hint 2
You can't edit strings, you will need to create a variable to store the new string.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 3
Create a loop to repeat the code as many times as needed.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 4
Make the variable created store the current value and append the word to it.
> _try to solve the problem now_
## Spoiler Alert!
---
## Solutions
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
<details><summary>Solution 1 (Click to Show/Hide)</summary>
**Solution ahead!**
```js
function repeatStringNumTimes(str, num) {
var accumulatedStr = "";
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
while (num > 0) {
accumulatedStr += str;
num--;
}
function repeatStringNumTimes(str, num) {
var accumulatedStr = '';
return accumulatedStr;
}
```
while (num > 0) {
accumulatedStr += str;
num--;
}
return accumulatedStr;
}
### Code Explanation:
#### Code Explanation
* Create an empty string variable to store the repeated word.
* Use a while loop or for loop to repeat code as many times as needed according to `num`
@@ -60,21 +64,23 @@ Make the variable created store the current value and append the word to it.
* <a>JS while Loop</a>
* <a href='https://forum.freecodecamp.com/t/javascript-for-loop/14666s-Explained' target='_blank' rel='nofollow'>JS For Loops Explained</a>
</details>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
<details><summary>Solution 2 (Click to Show/Hide)</summary>
function repeatStringNumTimes(str, num) {
if (num < 1) {
return "";
} else if (num === 1) {
return str;
} else {
return str + repeatStringNumTimes(str, num - 1);
}
}
```js
function repeatStringNumTimes(str, num) {
if (num < 1) {
return "";
} else if (num === 1) {
return str;
} else {
return str + repeatStringNumTimes(str, num - 1);
}
}
```
### Code Explanation:
#### Code Explanation
* This solution uses recursion.
* We check if `num` is negative and return an empty string if true.
@@ -85,16 +91,19 @@ Make the variable created store the current value and append the word to it.
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#Recursion' target='_blank' rel='nofollow'>Functions - Recursion</a>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
</details>
function repeatStringNumTimes(str, num) {
return num > 0 ? str.repeat(num) : '';
}
<details><summary>Solution 3 (Click to Show/Hide)</summary>
repeatStringNumTimes("abc", 3);
```js
function repeatStringNumTimes(str, num) {
return num > 0 ? str.repeat(num) : "";
}
repeatStringNumTimes("abc", 3);
```
### Code Explanation:
#### Code Explanation
* This solution takes a declarative approach.
* It is similar to the third solution, except it uses the ternary operator form of the `if` statement.
@@ -102,9 +111,4 @@ Make the variable created store the current value and append the word to it.
#### Relevant Links
* <a href='https://forum.freecodecamp.com/t/javascript-ternary-operator/15973' target='_blank' rel='nofollow'>JS Ternary</a>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,59 +1,57 @@
---
title: Return Largest Numbers in Arrays
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
# Return Largest Numbers in Arrays
---
## Problem Explanation
You will get an array that contains sub arrays of numbers and you need to return an array with the largest number from each of the sub arrays.
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
You will need to keep track of the array with the answer and the largest number of each sub-array.
---
## Hints
> _try to solve the problem now_
### Hint 1
You will get an array that contains sub arrays of numbers and you need to return an array with the largest number from each of the sub arrays. You will need to keep track of the array with the answer and the largest number of each sub-array.
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
You can work with multidimensional arrays by `Array[Index][SubIndex]`
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 3
Pay close attention to the timing of the storing of variables when working with loops
> _try to solve the problem now_
## Spoiler Alert!
---
## Solutions
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**Solutions ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
<details><summary>Solution 1 (Click to Show/Hide)</summary>
**(Procedural approach)**
function largestOfFour(arr) {
var results = [];
for (var n = 0; n < arr.length; n++) {
var largestNumber = arr[n][0];
for (var sb = 1; sb < arr[n].length; sb++) {
if (arr[n][sb] > largestNumber) {
largestNumber = arr[n][sb];
}
}
results[n] = largestNumber;
```js
function largestOfFour(arr) {
var results = [];
for (var n = 0; n < arr.length; n++) {
var largestNumber = arr[n][0];
for (var sb = 1; sb < arr[n].length; sb++) {
if (arr[n][sb] > largestNumber) {
largestNumber = arr[n][sb];
}
return results;
}
results[n] = largestNumber;
}
### Code Explanation:
return results;
}
```
#### Code Explanation
* Create a variable to store the _results_ as an array.
* Create an outer loop to iterate through the outer array.
@@ -67,20 +65,23 @@ Pay close attention to the timing of the storing of variables when working with
* <a href='http://forum.freecodecamp.com/t/javascript-for-loop/14666s-Explained' target='_blank' rel='nofollow'>For loops</a>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
</details>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
**(Declarative approach)**
function largestOfFour(arr) {
return arr.map(function(group){
return group.reduce(function(prev, current) {
return (current > prev) ? current : prev;
});
});
}
```js
function largestOfFour(arr) {
return arr.map(function(group) {
return group.reduce(function(prev, current) {
return current > prev ? current : prev;
});
});
}
```
### Code Explanation:
#### Code Explanation
* we map all items within the main array to a new array using `Array.prototype.map()` and return this array as the final result
* within each inner array, we reduce its contents down to a single value using `Array.prototype.reduce()`
@@ -93,18 +94,21 @@ Pay close attention to the timing of the storing of variables when working with
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-reduce/14299' target='_blank' rel='nofollow'>Array.prototype.reduce()</a>
* <a href='http://forum.freecodecamp.com/t/javascript-ternary-operator/15973' target='_blank' rel='nofollow'>Ternary Operators</a>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
</details>
<details><summary>Solution 3 (Click to Show/Hide)</summary>
**(Declarative approach)**
function largestOfFour(arr) {
return arr.map(Function.apply.bind(Math.max, null));
}
```js
function largestOfFour(arr) {
return arr.map(Function.apply.bind(Math.max, null));
}
```
#### Code Explanation
### Code Explanation:
TL;DR: We build a special callback function (using the `Function.bind` method), that works just like `Math.max` but also has `Function.prototype.apply`'s ability to take arrays as its arguments ![:smiley:](https://forum.freecodecamp.com/images/emoji/emoji_one/smiley.png?v=3 ":smiley:")
TL;DR: We build a special callback function (using the `Function.bind` method), that works just like `Math.max` but also has `Function.prototype.apply`'s ability to take arrays as its arguments.
* We start by mapping through the elements inside the main array. Meaning each one of the inner arrays.
* Now the need a callback function to find the max of each inner array provided by the map.
@@ -137,9 +141,4 @@ Here we're passing `null` as the _context_ of the `Function.prototype.apply` met
* <a href ='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max' target='_blank' rel='nofollow'> Math.max</a>
* <a href='http://devdocs.io/#q=js+Function+apply' target='_blank' rel='nofollow'>Function.prototype.apply on DevDocs</a>
* <a href='http://devdocs.io/#q=js+Function+bind' target='_blank' rel='nofollow'>Function.bind on DevDocs</a>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,44 +1,54 @@
---
title: Reverse a String
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
# Reverse a String
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
We need to take the string and reverse it, so if it originally reads 'hello', it will now read 'olleh'. We will need to split the string, and therefore we will be working with Arrays as well.
### Hint 2
Start by splitting the string by characters.
> _try to solve the problem now_
#### Relevant Links
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split' target='_blank' rel='nofollow'>str.split()</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 3
Look up the built in function to reverse a string.
> _try to solve the problem now_
#### Relevant Links
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse' target='_blank' rel='nofollow'>arr.reverse()</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 4
Do not forget to join the characters back together after you reverse them.
> _try to solve the problem now_
#### Relevant Links
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/join' target='_blank' rel='nofollow'>arr.join()</a>
## Spoiler Alert!
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**Solution ahead!**
---
## Solutions
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution #1:
<details><summary>Click to see solution</summary>
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
function reverseString(str) {
return str.split('').reverse().join('');
return str
.split("")
.reverse()
.join("");
}
```
#### Code Explanation:
#### Code Explanation
* Our goal is to take the input, `str`, and return it in reverse. Our first step is to split the string by characters using `split('')`. Notice that we don't leave anything in between the single quotes, this tells the function to split the string by each character.
@@ -48,28 +58,26 @@ function reverseString(str) {
* Finally, we _chain_ `join('')` to put our characters back together into a string. Notice once again that we left no spaces in the argument for join, this makes sure that the array of characters is joined back together by each character.
### Relevant Links
#### Relevant Links
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split' target='_blank' rel='nofollow'>str.split()</a>
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse' target='_blank' rel='nofollow'>arr.reverse()</a>
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/join' target='_blank' rel='nofollow'>arr.join()</a>
</details><br>
</details>
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution #2:
<details><summary>Click to see solution</summary>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
```js
function reverseString(str) {
for (var reversedStr = '', i = str.length - 1; i >= 0; i--){
for (var reversedStr = "", i = str.length - 1; i >= 0; i--) {
reversedStr += str[i];
}
return reversedStr;
};
}
```
#### Code Explanation:
#### Code Explanation
* Starting at the last character of the string passed to the function, you build a new string `reversedStr` from `str`.
@@ -77,10 +85,4 @@ function reverseString(str) {
* Finally, you return the final value of `reversedStr`.
</details><br>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,11 +1,11 @@
---
title: Slice and Splice
---
## Slice and Splice
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
# Slice and Splice
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
---
## Problem Explanation
We need to copy each element from the first array into the second array starting at the index n. We've also got to ensure that the original arrays are not mutated. That is, we cannot make any changes to the original arrays.
@@ -14,31 +14,30 @@ We need to copy each element from the first array into the second array starting
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice' target='_blank' rel='nofollow'>Array.slice()</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice' target='_blank' rel='nofollow'>Array.splice()</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
Create a copy of the second array inside of the function. This will ensure that the original array is not mutated. This can be done by using the slice operation on the second array, and assign it to a variable.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
Loop through all of the items in the first array. For each item in the first array splice it into the copied array in the index given as argument.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 3
Increment the index after performing the splice.
> _try to solve the problem now_
## Spoiler Alert!
---
## Solutions
![warning sign](https://discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
<details><summary>Solution 1 (Click to Show/Hide)</summary>
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
```js
function frankenSplice(arr1, arr2, n) {
// It's alive. It's alive!
@@ -51,7 +50,7 @@ function frankenSplice(arr1, arr2, n) {
}
```
### Code Explanation:
#### Code Explanation
* Our goal is to take all of the elements from `arr1` and insert them into `arr2` starting with index position `n`. At the same time we must ensurethat neither `arr` or `arr2` have been mutated.
@@ -63,8 +62,10 @@ function frankenSplice(arr1, arr2, n) {
* Finally, we return the `localArray` and end the function.
</details>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
## 🌻 Intermediate Code Solution:
```js
function frankenSplice(arr1, arr2, n) {
// It's alive. It's alive!
@@ -80,8 +81,4 @@ function frankenSplice(arr1, arr2, n) {
* `localArr` is returned and the function is complete.
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,9 +1,11 @@
---
title: Title Case a Sentence
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
# Title Case a Sentence
---
## Problem Explanation
We have to return a sentence with title case. This means that the first letter will always be in uppercase and the rest will be in lowercase.
@@ -14,50 +16,53 @@ We have to return a sentence with title case. This means that the first letter w
* <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-touppercase/15950' target='_blank' rel='nofollow'>JS String Prototype ToUpperCase</a>
* <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-replace/15942' target='_blank' rel='nofollow'>JS String Prototype Replace</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
* You should start by splitting the string into an array of words.
* Split the sentence.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
* You should make the word lowercase before making the first letter uppercase.
* Use replace method on each word to capitalize the first letter of each word.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 3
* You will need to create a new string with pieces of the previous one and at the end merge everything into a single string again.
* In replace method, give first argument as the position of the first letter using charAt. For second argument write a function to return the capitalized letter as the replacement.
> _try to solve the problem now_
## Spoiler Alert!
---
## Solutions
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
<details><summary>Solution 1 (Click to Show/Hide)</summary>
**Solution ahead!**
```js
String.prototype.replaceAt = function(index, character) {
return (
this.substr(0, index) + character + this.substr(index + character.length)
);
};
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
function titleCase(str) {
var newTitle = str.split(" ");
var updatedTitle = [];
for (var st in newTitle) {
updatedTitle[st] = newTitle[st]
.toLowerCase()
.replaceAt(0, newTitle[st].charAt(0).toUpperCase());
}
return updatedTitle.join(" ");
}
```
String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
};
function titleCase(str) {
var newTitle = str.split(' ');
var updatedTitle = [];
for (var st in newTitle) {
updatedTitle[st] = newTitle[st].toLowerCase().replaceAt(0, newTitle[st].charAt(0).toUpperCase());
}
return updatedTitle.join(' ');
}
### Code Explanation:
#### Code Explanation
We are modifying the `replaceAt` function using prototype to facilitate the use of the program.
@@ -69,21 +74,23 @@ Split the string by white spaces, and create a variable to track the updated tit
* <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-split/15944' target='_blank' rel='nofollow'>JS String Prototype Split</a>
* <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-substr/15945' target='_blank' rel='nofollow'>JS String Prototype Substr</a>
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-join/14292' target='_blank' rel='nofollow'>JS Array Prototype Join</a>
</details>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
<details><summary>Solution 2 (Click to Show/Hide)</summary>
function titleCase(str) {
var convertToArray = str.toLowerCase().split(" ");
var result = convertToArray.map(function(val){
return val.replace(val.charAt(0), val.charAt(0).toUpperCase());
});
return result.join(" ");
}
```js
function titleCase(str) {
var convertToArray = str.toLowerCase().split(" ");
var result = convertToArray.map(function(val) {
return val.replace(val.charAt(0), val.charAt(0).toUpperCase());
});
return result.join(" ");
}
titleCase("I'm a little tea pot");
titleCase("I'm a little tea pot");
```
### Code Explanation:
#### Code Explanation
We are making entire string lowercase and then converting it into array. Then we are using map function to replace the lowercase character with uppercase. Finally, we are returning the string using `join` method.
@@ -91,14 +98,17 @@ We are making entire string lowercase and then converting it into array. Then we
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-map/14294' target='_blank' rel='nofollow'>JS Array Prototype Map</a>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
</details>
function titleCase(str) {
return str.toLowerCase().replace(/(^|\s)\S/g, (L) => L.toUpperCase());
}
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
function titleCase(str) {
return str.toLowerCase().replace(/(^|\s)\S/g, L => L.toUpperCase());
}
```
### Code Explanation:
#### Code Explanation
The solution works by first lowercasing all the characters in the string and then only uppercasing the first character of each word.
- Lowercase the whole string using `str.toLowerCase()`.
@@ -119,8 +129,4 @@ The solution works by first lowercasing all the characters in the string and the
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions' target='_blank' rel='nofollow'>JS Regex Resources</a>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,9 +1,10 @@
---
title: Truncate a String
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
# Truncate a String
---
## Problem Explanation
We need to reduce the length of the string or **truncate** it if it is longer than the given maximum length specified and add `...` to the end. If it is not that long then we keep it as is.
@@ -11,50 +12,53 @@ We need to reduce the length of the string or **truncate** it if it is longer th
* <a href='https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/JS-String-Prototype-Slice' target='_blank' rel='nofollow'>String.prototype.slice()</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
Strings are immutable in JavaScript so we will need a new variable to store the truncated string.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
You will need to use the slice() method and specify where to start and where to stop.
> _try to solve the problem now_
## Spoiler Alert!
---
## Solutions
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
<details><summary>Solution 1 (Click to Show/Hide)</summary>
**Solution ahead!**
```js
function truncateString(str, num) {
// Clear out that junk in your trunk
if (str.length > num) {
return str.slice(0, num) + "...";
} else {
return str;
}
}
```
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
function truncateString(str, num) {
// Clear out that junk in your trunk
if(str.length > num) {
return str.slice(0,num)+"...";
} else {
return str;
}
}
### Code Explanation:
#### Code Explanation
* We start off with a simple `if` statement to determine one of two outcomes...
* If our string length is greater than the `num` we want to truncate it, we return a slice of our string starting at character 0, and ending at `num`. We then append our `'...'` to the end of the string.
* However, if above situation is not true, it means our string length is less than our truncation `num`. Therefore, we can just return the string.
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
</details>
function truncateString(str, num) {
return (str.length > num)?(str.slice(0,num)+"..."):str;
}
<details><summary>Solution 2 (Click to Show/Hide)</summary>
```js
function truncateString(str, num) {
return str.length > num ? str.slice(0, num) + "..." : str;
}
```
### Code Explanation:
#### Code Explanation
* This solution is very similar to basic solution. To determine the new string, we use a ternary operator. In our ternary operation, if `str.length` is larger than `num`, we return a new string which is slice of our string starting at character 0, and ending at `num` and the `'...'` is appended to the end of our new string. If `str.length` is less than or equal to `num`, we return the string without any truncation.
@@ -64,9 +68,4 @@ You will need to use the slice() method and specify where to start and where to
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator' target='_blank' rel='nofollow'>Conditional (ternary) Operator</a>
* <a href='https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/JS-String-Prototype-Slice' target='_blank' rel='nofollow'>String.prototype.slice()</a>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,9 +1,11 @@
---
title: Where Do I Belong
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
# Where Do I Belong
---
## Problem Explanation
This can be a tricky problem to understand. You need to find where in the array a number should be inserted by order, and return the index where it should go.
@@ -11,114 +13,119 @@ This can be a tricky problem to understand. You need to find where in the array
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-sort/14306' target='_blank' rel='nofollow'>JS Array Sort</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
The first thing to do is sort the array from lower to bigger, just to make the code easier. This is where sort comes in, it needs a callback function so you have to create it.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
Once the array is sorted, then just check for the first number that is bigger and return the index.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 3
If there is no index for that number then you will have to deal with that case too.
> _try to solve the problem now_
## Spoiler Alert!
---
## Solutions
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
<details><summary>Solution 1 (Click to Show/Hide)</summary>
**Solution ahead!**
```js
function getIndexToIns(arr, num) {
arr.sort(function(a, b) {
return a - b;
});
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
for (var a = 0; a < arr.length; a++) {
if (arr[a] >= num) return a;
}
function getIndexToIns(arr, num) {
arr.sort(function(a, b) {
return a - b;
});
return arr.length;
}
```
for (var a = 0; a < arr.length; a++) {
if (arr[a] >= num)
return a;
}
#### Code Explanation
return arr.length;
}
## Code Explanation:
* First I sort the array using `.sort(callbackFuntion)` to sort it by lowest to highest, from left to right.
* First I sort the array using `.sort(callbackFunction)` to sort it by lowest to highest, from left to right.
* Then I use a for loop to compare the items in the array starting from the smallest one. When an item on the array is greater than the number we are comparing against, then we return the index as an integer.
#### Relevant Links
* <a href='http://forum.freecodecamp.com/t/javascript-parseint/14686' target='_blank' rel='nofollow'>parseInt()</a>
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
</details>
function getIndexToIns(arr, num) {
// Find my place in this sorted array.
var times = arr.length; // runs the for loop once for each thing in the array
var count = 0;
for (var i=0;i<times;i++){
if(num>arr[i]){count++;} } // counts how many array numbers are smaller than num
return count; // the above equals num's position in a sorted array
<details><summary>Solution 2 (Click to Show/Hide)</summary>
```js
function getIndexToIns(arr, num) {
// Find my place in this sorted array.
var times = arr.length; // runs the for loop once for each thing in the array
var count = 0;
for (var i = 0; i < times; i++) {
if (num > arr[i]) {
count++;
}
} // counts how many array numbers are smaller than num
return count; // the above equals num's position in a sorted array
}
getIndexToIns([40, 60], 50);
getIndexToIns([40, 60], 50);
```
## Code Explanation:
#### Code Explanation
* I do not sort the arr input array
* I run a for loop counting whenever the num input is bigger than an arr input number.
* This number is equivalent to what num's position would be in a sorted array.
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
<details><summary>Solution 3 (Click to Show/Hide)</summary>
by [@HarinaPana](/u/harinapana)
```js
function getIndexToIns(arr, num) {
arr.sort(function(a, b) {
return a - b;
});
function getIndexToIns(arr, num) {
var i = 0;
while (num > arr[i]) {
i++;
}
arr.sort(function(a, b) {
return a - b;
});
return i;
}
var i = 0;
while (num > arr[i]) {
i++;
}
getIndexToIns([40, 60], 50);
```
return i;
}
getIndexToIns([40, 60], 50);
## Code Explanation:
#### Code Explanation
* Sort existing array.
* Iterate through the array while checking if _num_ is bigger.
* The loop will stop when _num_ isn't bigger than _i_ and return the last element checked.
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
</details>
by [@faustodc](/u/faustodc)
<details><summary>Solution 4 (Click to Show/Hide)</summary>
function getIndexToIns(arr, num) {
arr.push(num);
arr.sort(function(a, b){return a-b});
return arr.indexOf(num);
}
```js
function getIndexToIns(arr, num) {
arr.push(num);
arr.sort(function(a, b) {
return a - b;
});
return arr.indexOf(num);
}
```
## Code Explanation:
#### Code Explanation
* First we add the number `num` to the array using `push()` which adds it as the last element of the array.
* Then we use `sort()` with the callback function `function(a, b){return a-b}` to sort the numbers in ascending order.
@@ -130,22 +137,26 @@ by [@faustodc](/u/faustodc)
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort' target='_blank' rel='nofollow'>sort()</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf' target='_blank' rel='nofollow'>indexOf()</a>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
</details>
<details><summary>Solution 5 (Click to Show/Hide)</summary>
**Using `.findIndex()`**
function getIndexToIns(arr, num) {
// sort and find right index
var index = arr.sort((curr, next) => curr > next)
.findIndex((currNum)=> num <= currNum);
// Returns proper answer
return index === -1 ? arr.length : index;
}
```js
function getIndexToIns(arr, num) {
// sort and find right index
var index = arr
.sort((curr, next) => curr > next)
.findIndex(currNum => num <= currNum);
// Returns proper answer
return index === -1 ? arr.length : index;
}
getIndexToIns([40, 60], 500);
getIndexToIns([40, 60], 500);
```
## Code Explanation:
#### Code Explanation
* First sort the array in ascending order, this is currently done using array functions for minimal footprint.
* Once the array it is sorted, we directly apply the `.findIndex()` where we are going to compare every element in the array until we find where `num <= currNum` meaning where the number we want to insert is less or equal to the current number number in the iteration.
@@ -157,20 +168,22 @@ by [@faustodc](/u/faustodc)
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions' target='_blank' rel='nofollow'>Arrow Functions</a>
* <a href='http://forum.freecodecamp.com/t/javascript-ternary-operator/15973' target='_blank' rel='nofollow'>Ternary Operator</a>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
</details>
by [@nivrith](/u/nivrith)
<details><summary>Solution 6 (Click to Show/Hide)</summary>
function getIndexToIns(arr, num) {
```js
function getIndexToIns(arr, num) {
return arr
.concat(num)
.sort((a, b) => a - b)
.indexOf(num);
}
return arr.concat(num).sort((a,b) => a-b).indexOf(num);
getIndexToIns([1, 3, 4], 2);
```
}
getIndexToIns([1,3,4],2);
## Code Explanation:
#### Code Explanation
* We use method-chaining to invoke one method after another to solve the problem in a single line. First we merge `arr` and `num` by invoking the arr.concat(num) method
* Then we use `sort()` with the callback **arrow function** `(a, b) => return a-b` to sort the numbers in ascending order
@@ -181,9 +194,4 @@ by [@nivrith](/u/nivrith)
* <a href='https://schier.co/blog/2013/11/14/method-chaining-in-javascript.html' target='_blank' rel='nofollow'>Method chaining in JavaScript</a>
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/concat?v=example' target='_blank' rel='nofollow'>concat()</a>
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions' target='_blank' rel='nofollow'>Arrow functions</a>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,11 +1,21 @@
---
title: Access an Array's Contents Using Bracket Notation
---
## Access an Array's Contents Using Bracket Notation
# Access an Array's Contents Using Bracket Notation
---
## Hints
### Hint 1
- Remember the arrays index begins at 0 so the postion of b will be located in `myArray[1]`.
## Solution
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
myArray[1] = "anything we want";
```
</details>

View File

@@ -1,15 +1,15 @@
---
title: Access Property Names with Bracket Notation
---
## Access Property Names with Bracket Notation
# Access Property Names with Bracket Notation
Method:
---
## Problem Explanation
- Using bracket notation simply write the return statement in the `checkInventory()` function.
- The following code block demonstrates the required syntax.
## Example:
```javascript
let juice = {
apple: 1.15,
orange: 1.45
@@ -17,11 +17,14 @@ let juice = {
function checkInventory(scannedItem) {
return juice[scannedItem];
}
```
## Solution:
```javascript
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
let foods = {
apples: 25,
oranges: 32,
@@ -39,5 +42,6 @@ function checkInventory(scannedItem) {
// change code below this line to test different cases:
console.log(checkInventory("apples"));
```
</details>

View File

@@ -1,20 +1,31 @@
---
title: Add Items to an Array with push() and unshift()
---
## Add Items to an Array with push() and unshift()
# Add Items to an Array with push() and unshift()
---
## Hints
### Hint 1
- Just like the example given, use the `.unshift()` method on the array to add elements to the start of the array and use the `.push()` method to add elements to the end of the array.
## Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function mixedNumbers(arr) {
// change code below this line
arr.unshift('I',2,'three');
arr.push(7,'VIII', 9);
arr.unshift("I", 2, "three");
arr.push(7, "VIII", 9);
// change code above this line
return arr;
}
// do not change code below this line
console.log(mixedNumbers(['IV', 5, 'six']));
console.log(mixedNumbers(["IV", 5, "six"]));
```
</details>

View File

@@ -1,10 +1,16 @@
---
title: Add Items Using splice()
---
## Add Items Using splice()
# Add Items Using splice()
---
## Hints
### Hint 1
- Using the splice() function, you must remove the first 2 elements from array `arr` and replace them with `DarkSalmon` and `BlanchedAlmond`.
- Remember the splice function can take up to three parameters.
## Example:
#### Example:
```javascript
arr.splice(0, 1, "Two");
/* The first two paramemters are the same as they were in the previous challenge.
@@ -15,15 +21,29 @@ arr.splice(0, 1, "Two");
*/
```
## Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function htmlColorNames(arr) {
// change code below this line
arr.splice(0, 2, "DarkSalmon", "BlanchedAlmond");
// change code above this line
return arr;
}
}
// do not change code below this line
console.log(htmlColorNames(['DarkGoldenRod', 'WhiteSmoke', 'LavenderBlush', 'PaleTurqoise', 'FireBrick']));
console.log(
htmlColorNames([
"DarkGoldenRod",
"WhiteSmoke",
"LavenderBlush",
"PaleTurqoise",
"FireBrick"
])
);
```
</details>

View File

@@ -1,17 +1,26 @@
---
title: Add Key-Value Pairs to JavaScript Objects
---
## Add Key-Value Pairs to JavaScript Objects
# Add Key-Value Pairs to JavaScript Objects
---
## Hints
### Hint 1
- The foods object has already been declared. All that is left to be done is to add three new `key-values`.
```javascript
OBJECT[{KEY}] = {VALUE}
OBJECT[{ KEY }] = { VALUE };
```
- The above code will create a ney `key-value` within the object.
## Solution
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
let foods = {
apples: 25,
@@ -19,9 +28,10 @@ let foods = {
plums: 28
};
// change code below this line
foods['bananas'] = 13;
foods['grapes'] = 35;
foods['strawberries'] = 27;
foods["bananas"] = 13;
foods["grapes"] = 35;
foods["strawberries"] = 27;
// change code above this line
console.log(foods);
```
</details>

View File

@@ -1,37 +1,53 @@
---
title: Check For The Presence of an Element With indexOf()
---
## Check For The Presence of an Element With indexOf()
# Check For The Presence of an Element With indexOf()
- A simple `if-statement` can be used to check whether or not the value returned by the `indexOf()` function is less than 0.
- Once the value is discovered then you can return either `true` or `false`.
- `Solution-1` demonstrates how a simple `if-statement` can return the correct result.
## Solution-1:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function quickCheck(arr, elem) {
if(arr.indexOf(elem)>=0) {
if (arr.indexOf(elem) >= 0) {
return true;
}
return false;
}
console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
console.log(quickCheck(["squash", "onions", "shallots"], "mushrooms"));
```
- `Solution-2` demonstrates how the problem can be solved using the `? : (conditional)` operator.
## Solution-2:
#### Code Explanation
- A simple `if-statement` can be used to check whether or not the value returned by the `indexOf()` function is less than 0.
- Once the value is discovered then you can return either `true` or `false`.
- demonstrates how a simple `if-statement` can return the correct result.
</details>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
```javascript
function quickCheck(arr, elem) {
return arr.indexOf(elem) >= 0 ? true : false;
return arr.indexOf(elem) >= 0 ? true : false;
}
console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
console.log(quickCheck(["squash", "onions", "shallots"], "mushrooms"));
```
- `Solution-3` demonstrates how the problem can be solved by directly returning result of the comparison.
## Solution-3:
#### Code Explanation
- demonstrates how the problem can be solved using the `? : (conditional)` operator.
</details>
<details><summary>Solution 3 (Click to Show/Hide)</summary>
```javascript
function quickCheck(arr, elem) {
return arr.indexOf(elem) != -1;
}
console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
console.log(quickCheck(["squash", "onions", "shallots"], "mushrooms"));
```
#### Code Explanation
- demonstrates how the problem can be solved by directly returning result of the comparison.
</details>

View File

@@ -1,11 +1,15 @@
---
title: Check if an Object has a Property
---
## Check if an Object has a Property
# Check if an Object has a Property
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
### Basic Solution:
```javascript
let users = {
Alan: {
age: 27,
@@ -27,8 +31,10 @@ let users = {
function isEveryoneHere(obj) {
if (
obj.hasOwnProperty('Alan') && obj.hasOwnProperty('Jeff') &&
obj.hasOwnProperty('Sarah') && obj.hasOwnProperty('Ryan')
obj.hasOwnProperty("Alan") &&
obj.hasOwnProperty("Jeff") &&
obj.hasOwnProperty("Sarah") &&
obj.hasOwnProperty("Ryan")
) {
return true;
}
@@ -39,8 +45,10 @@ function isEveryoneHere(obj) {
#### Code Explanation
* Checks whether object contains all users by using the `hasOwnProperty` method for each name with the `&&` operator to return a `true` or `false` value.
</details>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
### Advanced Solution:
```javascript
let users = {
Alan: {
@@ -62,12 +70,9 @@ let users = {
};
function isEveryoneHere(obj) {
return [
'Alan',
'Jeff',
'Sarah',
'Ryan'
].every(name => obj.hasOwnProperty(name));
return ["Alan", "Jeff", "Sarah", "Ryan"].every(name =>
obj.hasOwnProperty(name)
);
}
```
@@ -80,3 +85,5 @@ function isEveryoneHere(obj) {
#### Relevant Links
* [Array.prototype.every](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every)
</details>

View File

@@ -1,14 +1,17 @@
---
title: Combine Arrays with the Spread Operator
---
## Combine Arrays with the Spread Operator
# Combine Arrays with the Spread Operator
- The solution is exactly like the example given. Simply insert the `fragment[]` array into the `sentence[]` array at the desired index.
## Solution:
---
## Solutions
<details><summary>Solution 2 (Click to Show/Hide)</summary>
```javascript
function spreadOut() {
let fragment = ['to', 'code'];
let fragment = ["to", "code"];
let sentence = ["learning", ...fragment, "is", "fun"]; // change this line
return sentence;
}
@@ -16,3 +19,6 @@ function spreadOut() {
// do not change code below this line
console.log(spreadOut());
```
#### Code Explanation
- The solution is exactly like the example given. Simply insert the `fragment[]` array into the `sentence[]` array at the desired index.
</details>

View File

@@ -1,9 +1,16 @@
---
title: Copy an Array with the Spread Operator
---
## Copy an Array with the Spread Operator
# Copy an Array with the Spread Operator
---
## Hints
### Hint 1
- The final hint in the example tells you to use a recently learned method.
### Hint 2
- The spread operator copies all elements into a new empty object.
```javascript
@@ -16,7 +23,12 @@ while (num >= 1) {
- The code above will copy all of the elements into `newArr` but will also reinitialise `newArr` with every new iteration of the while loop.
- A new variable should first be initialised using the spread operator - `let obj = [...arr];` - then this variable should be added to the `newArr` for every iteration of the while loop.
## Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function copyMachine(arr, num) {
let newArr = [];
@@ -32,3 +44,4 @@ function copyMachine(arr, num) {
// change code here to test different cases:
console.log(copyMachine([true, false, true], 2));
```
</details>

View File

@@ -1,24 +1,32 @@
---
title: Copy Array Items Using slice()
---
## Copy Array Items Using slice()
# Copy Array Items Using slice()
- the `slice()` function must be used to return an array consisting of only `warm` and `sunny`.
- Therefore, two parameters must be passed to the `slice()` function. The first parameter must be the index you would like the substring to start at. The second parameter must be the index at which the substring ends.
- Note: The second parameter will end the substring at that exact index.
## Example:
```javascript
return arr.slice(1,4);
/* This will return a substring consisting of indexs [1,2,3]
Note: arr[4] is NOT included.
return arr.slice(1, 4);
/* This will return a substring consisting of indexs [1,2,3]
Note: arr[4] is NOT included. */
```
## Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function forecast(arr) {
// change code below this line
return arr.slice(2,4);
return arr.slice(2, 4);
}
// do not change code below this line
console.log(forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']));
console.log(
forecast(["cold", "rainy", "warm", "sunny", "cool", "thunderstorms"])
);
```
</details>

View File

@@ -1,24 +1,38 @@
---
title: Create complex multi-dimensional arrays
---
## Create complex multi-dimensional arrays
# Create complex multi-dimensional arrays
---
## Hints
### Hint 1
- The first string - `deep` - must be inserted three levels deep. This means within exactly threes sets of `[square-brackets]`.
```javascript
let threeLevelArray = ["first level", ["Two levels deep", ["Three levels deep"]]];
let threeLevelArray = [
"first level",
["Two levels deep", ["Three levels deep"]]
];
```
- Using this logic insert strings `deep` , `deeper` and `deepest` in the matrix three levels deep, four levels deep and five levels deep respectively.
## Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
let myNestedArray = [
// change code below this line
['unshift', false, 1, 2, 3, 'complex', 'nested'],
['loop', 'shift', 6, 7, 1000, 'method'],
['concat', false, true, 'spread', 'array',["deep"]],
['mutate', 1327.98, 'splice', 'slice', 'push', [["deeper"]]],
['iterate', 1.3849, 7, '8.4876', 'arbitrary', 'depth', [[["deepest"]]] ]
["unshift", false, 1, 2, 3, "complex", "nested"],
["loop", "shift", 6, 7, 1000, "method"],
["concat", false, true, "spread", "array", ["deep"]],
["mutate", 1327.98, "splice", "slice", "push", [["deeper"]]],
["iterate", 1.3849, 7, "8.4876", "arbitrary", "depth", [[["deepest"]]]]
// change code above this line
];
```
</details>

View File

@@ -1,17 +1,21 @@
---
title: Generate an Array of All Object Keys with Object.keys()
---
## Generate an Array of All Object Keys with Object.keys()
# Generate an Array of All Object Keys with Object.keys()
### Method:
---
## Problem Explanation
- To return the array of users the `Object.keys()` method must take an arguement.
- This challenge can be solved using a single line return statement.
### Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
let users = {
Alan: {
age: 27,
@@ -38,5 +42,5 @@ function getArrayOfUsers(obj) {
}
console.log(getArrayOfUsers(users));
```
</details>

View File

@@ -1,13 +1,11 @@
---
title: Basic Data Structures
---
## Basic Data Structures
# Basic Data Structures
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/quadratic-equations/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@@ -1,40 +1,50 @@
---
title: Iterate Through All an Array's Items Using For Loops
---
## Iterate Through All an Array's Items Using For Loops
# Iterate Through All an Array's Items Using For Loops
### Hint 1
- A nested `for` loop must be used to search through every element in the array.
## Hint 1
- A nested ``for`` loop must be used to search through every element in the array.
```javascript
for (let i = 0; i < arr.length; i++) {
````
## Hint 2
for (let i = 0; i < arr.length; i++) {}
```
### Hint 2
- Every element of the array must then be compared to the `elem` parameter passed through the `filteredArray()` function.
```javascript
if (arr[i].indexOf(elem)==-1){
if (arr[i].indexOf(elem) == -1) {
}
```
## Hint 3
### Hint 3
- If a match is NOT found then `newArr` have that entire subarray added. The `push()` function is very useful here.
```javascript
newArr.push(arr[i]);
```
- Once that entire subarray is added to `newArr` the loop continue with the next element.
## Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function filteredArray(arr, elem) {
let newArr = [];
// change code below this line
for (let i = 0; i < arr.length; i++) {
if (arr[i].indexOf(elem)==-1){ //Checks every parameter for the element and if is NOT there continues the code
newArr.push(arr[i]); //Inserts the element of the array in the new filtered array
};
};
for (let i = 0; i < arr.length; i++) {
if (arr[i].indexOf(elem) == -1) {
//Checks every parameter for the element and if is NOT there continues the code
newArr.push(arr[i]); //Inserts the element of the array in the new filtered array
}
}
// change code above this line
return newArr;
};
}
// change code here to test different cases:
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));
```
</details>

View File

@@ -1,42 +1,45 @@
---
title: Iterate Through the Keys of an Object with a for...in Statement
---
## Iterate Through the Keys of an Object with a for...in Statement
# Iterate Through the Keys of an Object with a for...in Statement
Method:
---
## Problem Explanation
- Note: `dot-notation` will cause errors in this challenge.
- `[square-bracket]` notation must be used to call a variable property name.
- The following code will not work.
### Example 1:
---
## Hints
### Hint 1:
```javascript
for (let user in obj) {
if(obj.user.online === true) {
if (obj.user.online === true) {
//code
}
}
```
### Hint 2
- Example 2 demonstrates how using `[square-bracket]` notation the code will be executed.
### Example 2:
```javascript
for (let user in obj) {
if(obj[user].online === true) {
if (obj[user].online === true) {
//code
}
}
```
### Solution:
```javascript
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
let users = {
Alan: {
age: 27,
@@ -59,7 +62,7 @@ function countOnline(obj) {
// change code below this line
let result = 0;
for (let user in obj) {
if(obj[user].online === true) {
if (obj[user].online === true) {
result++;
}
}
@@ -67,5 +70,5 @@ function countOnline(obj) {
// change code above this line
}
console.log(countOnline(users));
```
</details>

View File

@@ -1,45 +1,45 @@
---
title: Modify an Array Stored in an Object
---
## Modify an Array Stored in an Object
# Modify an Array Stored in an Object
### Method:
---
## Problem Explanation
- The function can be written in just two lines of code.
- The first line should just use the `push()` function to add the `friend`parameter to the array found in `user.data.friend`. The second line will return the modified array.
- Remember that `user` mustb be referenced with the first parameter given to the `addFriend()` function.
### Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
let user = {
name: 'Kenneth',
name: "Kenneth",
age: 28,
data: {
username: 'kennethCodesAllDay',
joinDate: 'March 26, 2016',
organization: 'freeCodeCamp',
friends: [
'Sam',
'Kira',
'Tomo'
],
username: "kennethCodesAllDay",
joinDate: "March 26, 2016",
organization: "freeCodeCamp",
friends: ["Sam", "Kira", "Tomo"],
location: {
city: 'San Francisco',
state: 'CA',
country: 'USA'
city: "San Francisco",
state: "CA",
country: "USA"
}
}
};
function addFriend(userObj, friend) {
// change code below this line
// change code below this line
userObj.data.friends.push(friend);
return userObj.data.friends;
// change code above this line
}
console.log(addFriend(user, 'Pete'));
console.log(addFriend(user, "Pete"));
```
</details>

View File

@@ -1,31 +1,38 @@
---
title: Modify an Object Nested Within an Object
---
## Modify an Object Nested Within an Object
Method:
# Modify an Object Nested Within an Object
---
## Problem Explanation
- Remember the object you want to change is two levels deep, `dot-notation` is easier to use in this instance.
- Simply define the object and then use `dot-notation` to access the second object and finally the final element you wish to modify.
## Example:
```javascript
let myObject = {
level_1: 'outside',
level_1: "outside",
first_level_object: {
level_2: '2 levels deep',
level_2: "2 levels deep",
second_level_object: {
level_3: '3 levels deep'
}
}
level_3: "3 levels deep"
}
}
};
//The following line of code will modify the data found in level_2.
myObject.first_level_object.level_2 = 'level-2 has been reached';
myObject.first_level_object.level_2 = "level-2 has been reached";
```
## Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
let userActivity = {
id: 23894201352,
date: 'January 1, 2017',
date: "January 1, 2017",
data: {
totalUsers: 51,
online: 42
@@ -38,3 +45,4 @@ userActivity.data.online = 45;
console.log(userActivity);
```
</details>

View File

@@ -1,11 +1,18 @@
---
title: Remove Items from an Array with pop() and shift()
---
## Remove Items from an Array with pop() and shift()
# Remove Items from an Array with pop() and shift()
---
## Problem Explanation
- The `.pop()` method and `.shift()` method must be called and initialised using the `popped` and `shifted` variables to return the correct answer from the function.
## Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function popShift(arr) {
let popped = arr.pop();
@@ -14,5 +21,6 @@ function popShift(arr) {
}
// do not change code below this line
console.log(popShift(['challenge', 'is', 'not', 'complete']));
console.log(popShift(["challenge", "is", "not", "complete"]));
```
</details>

View File

@@ -1,16 +1,23 @@
---
title: Remove Items Using splice()
---
## Remove Items Using splice()
# Remove Items Using splice()
---
## Problem Explanation
- The `splice()` function must be called on the `arr` array in order to remove 1 or more elements from the center of the array.
- The array `arr` currently adds up to the value of 16. Simply remove as many variables neccessary to return 10.
## Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function sumOfTen(arr) {
// change code below this line
arr.splice(1,2);
arr.splice(1, 2);
// change code above this line
return arr.reduce((a, b) => a + b);
}
@@ -18,3 +25,4 @@ function sumOfTen(arr) {
// do not change code below this line
console.log(sumOfTen([2, 5, 1, 5, 2, 1]));
```
</details>

View File

@@ -1,9 +1,9 @@
---
title: Use an Array to Store a Collection of Data
---
## Use an Array to Store a Collection of Data
# Use an Array to Store a Collection of Data
### Method:
Problem Explanation
- In JS, Arrays are one of the most commonly used data structure. Unlike other languages Arrays in JS can store different data types and can also change their size on runtime and hence are also referred as "Dynamic Arrays". They are also 0 indexed.
- Arrays can be initialized in different ways:
@@ -12,22 +12,26 @@ title: Use an Array to Store a Collection of Data
- In this challenge we'll focus on Array literals. To initialize an array we simply do `let arr = [];`
- We can add values to this array by accessing its index, example:
```javascript
let arr = [];
arr[0] = "hello";
console.log(arr); // ["hello"]
```
```javascript
let arr = [];
arr[0] = "hello";
console.log(arr); // ["hello"]
```
- We can also initialize the values in the array when we declare it, example:
```javascript
let arr = [1, 2, 3, "John"];
```
```javascript
let arr = [1, 2, 3, "John"];
```
- In this challenge you need to create an array with at least 5 elements and at least one string, one number, and one boolean.
### Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
let yourArray = ["a", 2, true, "c", null, {name: "john"}];
let yourArray = ["a", 2, true, "c", null, { name: "john" }];
```
### Resources
Further reading about arrays at [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array).
#### Relevant Links
Further reading about arrays at [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array).
</details>

View File

@@ -1,11 +1,14 @@
---
title: Use the delete Keyword to Remove Object Properties
---
## Use the delete Keyword to Remove Object Properties
# Use the delete Keyword to Remove Object Properties
[Developer.mozilla.org](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete) provides a comprehensive tutorial on the delete operator.
### Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
let foods = {
apples: 25,
@@ -22,3 +25,7 @@ delete foods.strawberries;
// change code above this line
console.log(foods);
```
#### Relevant Links
* [Developer.mozilla.org](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete) provides a comprehensive tutorial on the delete operator.
</details>

View File

@@ -1,17 +1,21 @@
---
title: Access Array Data with Indexes
---
## Access Array Data with Indexes
# Access Array Data with Indexes
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
The first element of an array is at position zero. So, if you want to access the first element of an array, you can do it like so:
```javascript
var arr = ["Programming", 123, "Coding", 789];
var firstElem = arr[0] // This is "Programming"
var thirdElem = arr[2] // This is "Coding"
var fourthElem = arr[3] // This is 789
var firstElem = arr[0]; // This is "Programming"
var thirdElem = arr[2]; // This is "Coding"
var fourthElem = arr[3]; // This is 789
```
Notice that the length of the array is 4, and the position of the last element of the array is 3.

View File

@@ -1,9 +1,13 @@
---
title: Access Multi-Dimensional Arrays With Indexes
---
## Access Multi-Dimensional Arrays With Indexes
# Access Multi-Dimensional Arrays With Indexes
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
Consider the following multi-dimensional array:
```javascript

View File

@@ -1,66 +1,66 @@
---
title: Accessing Nested Arrays
---
## Accessing Nested Arrays
# Accessing Nested Arrays
### Accessing elements within an array using bracket notation `[]`
---
## Hints
### Hint 1
Accessing elements within an array using bracket notation `[]`
```js
var fruitBasket = ['apple', 'banana' 'orange', 'melon'];
var fruitBasket = ["apple", "banana", "orange", "melon"];
var favoriteFruit = fruitBasket[2];
console.log(favoriteFruit) // 'orange'
console.log(favoriteFruit); // 'orange'
```
In this example, our favourite fruit is 'orange' which is at index `2` in the `fruitBasket` array. Using braket notation, we assign index `2` of the `fruitBasket` array to `favoriteFruit`. This makes `favoriteFruit` equal to 'orange'.
### Accessing objects within arrays using braket `[]` and dot `.` notation
### Hint 2
Accessing objects within arrays using braket `[]` and dot `.` notation
```js
var garage = [
{
type: 'car',
color: 'red',
make: 'Ford'
type: "car",
color: "red",
make: "Ford"
},
{
type: 'motorbike',
color: 'black',
make: 'Yamaha'
type: "motorbike",
color: "black",
make: "Yamaha"
},
{
type: 'bus',
color: 'yellow',
make: 'Blue Bird'
type: "bus",
color: "yellow",
make: "Blue Bird"
}
];
var busColor = garage[2].color; // 'yellow'
```
## Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
// Setup
var myPlants = [
{
{
type: "flowers",
list: [
"rose",
"tulip",
"dandelion"
]
list: ["rose", "tulip", "dandelion"]
},
{
type: "trees",
list: [
"fir",
"pine",
"birch"
]
}
list: ["fir", "pine", "birch"]
}
];
// Only change code below this line
var secondTree = myPlants[1].list[1];
```
</details>

View File

@@ -1,20 +1,26 @@
---
title: Accessing Nested Objects
---
## Accessing Nested Objects
Clue: ***" Use bracket notation for properties with a space in their name."***
# Accessing Nested Objects
---
## Hints
### Hint 1
Use bracket notation for properties with a space in their name.
If we look at our object:
```javascript
var myStorage = {
"car": {
"inside": {
car: {
inside: {
"glove box": "maps",
"passenger seat": "crumbs"
},
"outside": {
"trunk": "jack"
},
outside: {
trunk: "jack"
}
}
};
@@ -45,8 +51,8 @@ which in turn, is nested in the `car` object.
We can use dot notation to access the `glove box` as follows:
```javascript
var gloveBoxContents = myStorage.car.inside'complete here'
```
var gloveBoxContents = myStorage.car.inside[complete here]
```
You must replace `complete here` with the correct way to access the property.
See clue above if you get stuck.

View File

@@ -1,9 +1,13 @@
---
title: Accessing Object Properties with Bracket Notation
---
## Accessing Object Properties with Bracket Notation
# Accessing Object Properties with Bracket Notation
Here's one possible solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
var testObj = {
@@ -14,6 +18,7 @@ var testObj = {
// Only change code below this line
var entreeValue = testObj["an entree"]; // Change this line
var drinkValue = testObj["the drink"]; // Change this line
var entreeValue = testObj["an entree"]; // Change this line
var drinkValue = testObj["the drink"]; // Change this line
```
</details>

View File

@@ -1,18 +1,24 @@
---
title: Accessing Object Properties with Dot Notation
---
## Accessing Object Properties with Dot Notation
# Accessing Object Properties with Dot Notation
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
Here's one possible solution:
```js
var testObj = {
"hat": "ballcap",
"shirt": "jersey",
"shoes": "cleats"
hat: "ballcap",
shirt: "jersey",
shoes: "cleats"
};
// Only change code below this line
var hatValue = testObj.hat; // Change this line
var shirtValue = testObj.shirt; // Change this line
var hatValue = testObj.hat; // Change this line
var shirtValue = testObj.shirt; // Change this line
```
</details>

View File

@@ -2,9 +2,13 @@
title: Accessing Object Properties with Variables
---
## Accessing Object Properties with Variables
# Accessing Object Properties with Variables
Here's a working solution in case you are stuck:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
// Setup
@@ -16,6 +20,7 @@ var testObj = {
// Only change code below this line;
var playerNumber = 16; // Change this Line
var player = testObj[playerNumber]; // Change this Line
var playerNumber = 16; // Change this Line
var player = testObj[playerNumber]; // Change this Line
```
</details>

View File

@@ -1,31 +1,23 @@
---
title: Add New Properties to a JavaScript Object
---
## Add New Properties to a JavaScript Object
# Add New Properties to a JavaScript Object
Here's the example:
```js
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"]
};
---
## Solutions
ourDog.bark = "bow-wow";
```
Here's a solution:
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
var myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"]
name: "Happy Coder",
legs: 4,
tails: 1,
friends: ["freeCodeCamp Campers"]
};
// Only change code below this line.
myDog.bark = "woof";
```
</details>

View File

@@ -3,7 +3,20 @@ title: Add Two Numbers with JavaScript
---
# Add Two Numbers with JavaScript
---
## Hints
### Hint 1
JavaScript uses the `+` symbol for addition.
var sum = 10 + 10; //sum gets the value 20
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
var sum = 10 + 10; //sum gets the value 20
```
</details>

View File

@@ -4,23 +4,38 @@ title: Adding a Default Option in Switch Statements
# Adding a Default Option in Switch Statements
* Adding a default option makes sure that in case your variable doesn't match any of the options, the default will be used.
## Solution:
---
## Hints
### Hint 1
Adding a default option makes sure that in case your variable doesn't match any of the options, the default will be used.
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
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';
switch (val) {
case "a":
answer = "apple";
break;
case "b":
answer = "bird";
break;
case "c":
answer = "cat";
break;
default:
answer = "stuff";
}
return answer;
return answer;
}
```
```
</details>

View File

@@ -1,11 +1,16 @@
---
title: Appending Variables to Strings
---
## Appending Variables to Strings
# Appending Variables to Strings
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
Make sure your spelling and spacing are correct. Appending strings (stored inside variables) can be done like so:
var adj = "happy!";
var sent = "Today, I woke up being ";
sent += adj; // The result is "Today, I woke up being happy!"
```js
var adj = "happy!";
var sent = "Today, I woke up being ";
sent += adj; // The result is "Today, I woke up being happy!"
```

View File

@@ -1,13 +1,22 @@
---
title: Assignment with a Returned Value
---
## Assignment with a Returned Value
# Assignment with a Returned Value
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
Functions act as placeholders for the data they output. Basically, you can assign the output of a function to a variable, just like any normal data.
Here is the basic code solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
processed = processArg(7); // Equal to 2
```
</details>

View File

@@ -3,17 +3,21 @@ title: Build JavaScript Objects
---
# Build JavaScript Objects
---
## Hints
### Hint 1
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.
Here's a sample object:
var cat = {
"name": "Whiskers",
"legs": 4,
"tails": 1,
"enemies": ["Water", "Dogs"]
};
```js
var cat = {
name: "Whiskers",
legs: 4,
tails: 1,
enemies: ["Water", "Dogs"]
};
```
Objects are useful for storing data in a structured way, and can represents real world objects, like a cats.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@@ -1,62 +1,55 @@
---
title: Chaining If Else Statements
---
## Chaining If Else Statements
# Chaining If Else Statements
---
## Problem Explanation
* ```If```: the first conditional in every if/else statement, case the conditional is *true*, execute the code and ignore the rest.
* ```Else if```: can never be used as the first conditional. It is always a conditional after an ```if```, case the conditional is true, execute the code. Otherwise jumps into the next conditional.
* ```Else```: case all the previous conditionals are *false*, **else** is executed.
### Problem explanation:
_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
#### Hint 1
### Hint 1
Remember that you can combine (chain) several `if...else` statements one after the other until your last one using `else if (condition) {do this}`.
> _try to solve the problem now_
>
>
#### Hint 2
### Hint 2
Sometimes, when you write more code than you are used to and it doesn't work, the little things are what betray us. Checking for missing semicolons, brackets, etc. can prove very useful.
> _try to solve the problem now_
## Spoiler alert!
**Solution ahead!**
## Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function testSize(num) {
// Only change code below this line
if (num < 5){
if (num < 5) {
return "Tiny";
}
else if (num < 10) {
} else if (num < 10) {
return "Small";
}
else if (num < 15){
} else if (num < 15) {
return "Medium";
}
else if (num < 20){
} else if (num < 20) {
return "Large";
}
else {
} else {
return "Huge";
}
// Only change code above this line
}
```
### Code explanation
#### Code Explanation
The function first checks the `if` condition `(num < 5)`. If it evaluates to `true`, it returns the statement between the curly braces ("Tiny"). If it doesn't, it checks the next condition until the last `else` statement.
### Resources
#### Relevant Links
- ["if...else" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else)
</details>

View File

@@ -1,19 +1,24 @@
---
title: Comment Your JavaScript Code
---
## Comment Your JavaScript Code
# Comment Your JavaScript Code
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
Commenting allows you to type stuff that you don't want the computer to run as code. For example, notes to other programmers, directions, and more. Here's how to create a single-line comment.
// Hey, I'm a comment!
```js
// Hey, I'm a comment!
```
Now, if you want to comment an entire paragraph, that can be easily accomplished with...
/*
```js
/*
Hey, I'm a paragraph comment.
This allows for programmers to
write tons and tons of random
words, without the fear of me
being compiled!
*/
```

View File

@@ -1,42 +1,43 @@
---
title: Comparison with the Equality Operator
---
## Comparison with the equality operator
# Comparison with the equality operator
### Problem explanation:
---
## Problem Explanation
_Add the equality operator to the indicated line so that the function will return "Equal" when `val` is equivalent to 12._
#### Hint 1
---
## Hints
### Hint 1
Remember that _equality is different from assignment (`=`), which assigns the value at the right of the operator to a variable in the left._<sup><a href="#cite1">1</a></sup>
> _try to solve the problem now_
## Spoiler alert!
**Solution ahead!**
---
## Solutions
## Basic code solution:
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function testEqual(val) {
if (val == 12) { // Change this line
if (val == 12) {
// Change this line
return "Equal";
}
return "Not equal";
}
// Change this value to test
testEqual(10);
```
### Code explanation
#### Code Explanation
The function first evaluates `if` the condition `(val == 12)` evaluates to `true`. If it does, it returns the statement between the curly braces ("Equal"). If it doesn't, it returns the next `return` statement outside them ("Not equal").
### Sources
<span id="cite1">1</span>. ["Basic JavaScript: Comparison with the Equality Operator", fCC lesson at *JavaScript Algorithms And Data Structures Certification*](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator)
### Resources
#### Relevant Links
- <span id="cite1">1</span>. ["Basic JavaScript: Comparison with the Equality Operator", fCC lesson at *JavaScript Algorithms And Data Structures Certification*](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator)
- ["Equality operator" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Equality_())
</details>

View File

@@ -1,30 +1,36 @@
---
title: Comparison with the greater than operator (>)
---
## Comparison with the Greater Than Operator (>)
# Comparison with the Greater Than Operator (>)
### Problem explanation:
---
## Problem Explanation
· _Add the `greater than` operator to the indicated lines so that the return statements make sense._
#### Hint 1
---
## Hints
### Hint 1
The greater than operator `(>)` compares both operands using type coercion (converting data types if necessary) and returns `true` if the first one is greater than the second one.
> _try to solve the problem now_
>
## Spoiler alert!
**Solution ahead!**
## Basic code solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function testGreaterThan(val) {
if (val > 100) { // Change this line
if (val > 100) {
// Change this line
return "Over 100";
}
if (val > 10) { // Change this line
if (val > 10) {
// Change this line
return "Over 10";
}
@@ -34,9 +40,10 @@ function testGreaterThan(val) {
// Change this value to test
testGreaterThan(10);
```
### Code explanation
#### Code Explanation
The function first evaluates `if` the condition `(val > 100)` evaluates to `true` converting `val` to a number if necessary. If it does, it returns the statement between the curly braces ("Over 100"). If it doesn't, it checks if the next condition is `true` (returning "Over 10"). Otherwise the function will return "10 or under".
### Resources
#### Relevant Links
- ["Greater than operator (>)" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Greater_than_operator_(%3E))
</details>

View File

@@ -1,20 +1,23 @@
---
title: Comparison with the Greater Than Or Equal To Operator
---
## Comparison with the Greater Than Or Equal To Operator
# Comparison with the Greater Than Or Equal To Operator
* `>=` (Greater Than or Equal To) is a logical operator that returns true case the value on the left is the **same or higher** than the one on the right.
## Basic Solution
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function testGreaterOrEqual(val) {
if (val >= 20)
return "20 or Over";
if (val >= 10)
return "10 or Over";
if (val >= 20) return "20 or Over";
if (val >= 10) return "10 or Over";
return "Less than 10";
}
```
```
</details>

View File

@@ -1,27 +1,31 @@
---
title: Comparison with the Inequality Operator
---
## Comparison with the Inequality Operator
# Comparison with the Inequality Operator
### Problem explanation:
---
## Problem Explanation
· _Add the inequality operator `!=` in the `if` statement so that the function will return "Not equal" when `val` is not equivalent to `99`._
#### Hint 1
---
## Hints
### Hint 1
The inequality operator (`!=`) will return `true` if the first value is not equal to the second one without taking value type into consideration.
> _try to solve the problem now_
>
## Spoiler alert!
**Solution ahead!**
## Basic code solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
// Setup
function testNotEqual(val) {
if (val != 99) { // Change this line
if (val != 99) {
// Change this line
return "Not Equal";
}
return "Equal";
@@ -31,9 +35,10 @@ function testNotEqual(val) {
testNotEqual(10);
```
### Code explanation
#### Code Explanation
The function first evaluates `if` the condition `(val != 99)` evaluates to `true`. If it does, it returns the statement between the curly braces ("Not equal"). If it doesn't, it returns the next `return` statement outside them ("Equal").
### Resources
#### Relevant Links
- ["Inequality operator" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Using_the_Equality_Operators#Inequality_(!))
</details>

View File

@@ -1,20 +1,28 @@
---
title: Comparison with the Less Than Operator
---
## Comparison with the Less Than Operator
# Comparison with the Less Than Operator
---
## Hints
### Hint 1
**`<`** (Less Than) is a logical operator that returns true case the value on the left is lower than the one on the right.
## Basic Solution
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function testLessThan(val) {
if (val < 25)
return "Under 25";
if (val < 55)
return "Under 55";
if (val < 25) return "Under 25";
if (val < 55) return "Under 55";
return "55 or Over";
}
```
```
</details>

View File

@@ -1,20 +1,28 @@
---
title: Comparison with the Less Than Or Equal To Operator
---
## Comparison with the Less Than Or Equal To Operator
# Comparison with the Less Than Or Equal To Operator
---
## Hints
### Hint 1
**`<=`** (Less Than Or Equal To) is a logical operator that returns true case the value on the left is the **same or lower** than the one on the right.
## Basic Solution
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function testLessOrEqual(val) {
if (val <= 12)
return "Smaller Than or Equal to 12";
if (val <= 24)
return "Smaller Than or Equal to 24";
if (val <= 12) return "Smaller Than or Equal to 12";
if (val <= 24) return "Smaller Than or Equal to 24";
return "More Than 24";
}
```
```
</details>

View File

@@ -1,31 +1,34 @@
---
title: Comparison with the strict equality operator
---
## Comparison with the strict equality operator
# Comparison with the strict equality operator
### Problem explanation:
---
## Problem Explanation
· _Use the strict equality operator in the `if` statement so the function will return "Equal" when `val` is strictly equal to `7`._
#### Hint 1
---
## Hints
### Hint 1
Remember from last exercise that _equality is different from assignment (`=`), which assigns the value at the right of the operator to a variable in the left._<sup><a href="#cite1">1</a></sup>
> _try to solve the problem now_
>
#### Hint 2
### Hint 2
_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._<sup><a href="#cite2">2</a></sup>
> _try to solve the problem now_
## Spoiler alert!
**Solution ahead!**
---
## Solutions
## Basic code solution:
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
// Setup
function testStrict(val) {
if (val === 7) { // Change this line
if (val === 7) {
// Change this line
return "Equal";
}
return "Not equal";
@@ -33,21 +36,22 @@ function testStrict(val) {
// Change this value to test
testStrict(10);
```
### Code explanation
#### Code Explanation
The function first evaluates `if` the condition `(val === 7)` evaluates to `true`. If it does, it returns the statement between the curly braces ("Equal"). If it doesn't, it returns the next `return` statement outside them ("Not equal").
### Sources
#### Relevant Links
<span id="cite1">1</span>. ["Basic JavaScript: Comparison with the Equality Operator", fCC lesson at *JavaScript Algorithms And Data Structures Certification*](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator)
<span id="cite2">2</span>. ["Basic JavaScript: Comparison with the Strict Equality Operator", fCC lesson at *JavaScript Algorithms And Data Structures Certification*](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-strict-equality-operator)
### Resources
#### Relevant Links
- ["if...else" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else)
- [Kondov, Alexander. "Understanding JS: Coercion". *Hackernoon*](https://hackernoon.com/understanding-js-coercion-ff5684475bfc), Accessed 15 Sep. 2018
- ["Comparison operators" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
</details>

View File

@@ -1,22 +1,25 @@
---
title: Comparison with the Strict Inequality Operator
---
## Comparison with the Strict Inequality Operator
# Comparison with the Strict Inequality Operator
### Problem explanation:
---
## Problem Explanation
· _Add the `strict inequality operator` to the `if` statement so the function will return "Not Equal" when `val` is not strictly equal to `17`._
#### Hint 1
---
## Hints
### Hint 1
The strict inequality operator (`!==`) will return `true` if the first value is not equal to the second one taking value type into consideration.
> _try to solve the problem now_
>
## Spoiler alert!
**Solution ahead!**
## Basic code solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function testStrictNotEqual(val) {
@@ -30,9 +33,10 @@ function testStrictNotEqual(val) {
testStrictNotEqual(10);
```
### Code explanation
#### Code Explanation
The function first evaluates `if` the condition `(val !== 17)` evaluates to `true` considering both value and value type. If it does, it returns the statement between the curly braces ("Not equal"). If it doesn't, it returns the next `return` statement outside them ("Equal").
### Resources
#### Relevant Links
- ["Non-identity / strict inequality (!==)" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Non-identity_strict_inequality_(!))
</details>

View File

@@ -1,33 +1,36 @@
---
title: Comparisons with the && (logical AND) operator
---
## Comparisons with the && (logical AND) operator
# Comparisons with the && (logical AND) operator
### Problem explanation:
---
## Problem Explanation
· _Combine the two if statements into one statement which will return `"Yes"` if `val` is less than or equal to `50` and greater than or equal to `25`. Otherwise, will return `"No"`._
#### Hint 1
---
## Hints
### Hint 1
The logical AND (`&&`) operator compares both statements and returns `true` only if both are true or can be converted to true (truthy).
> _try to solve the problem now_
>
#### Hint 2
### Hint 2
Remember that this effect can be also achieved by nesting `if` statements.
> _try to solve the problem now_
>
## Spoiler alert!
**Solution ahead!**
## Basic code solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function testLogicalAnd(val) {
// Only change code below this line
if (val <= 50 && val >= 25) {
return "Yes";
return "Yes";
}
// Only change code above this line
@@ -38,9 +41,10 @@ function testLogicalAnd(val) {
testLogicalAnd(10);
```
### Code explanation
#### Code Explanation
The function first evaluates `if` the condition `val <= 50` evaluates to `true` converting `val` to a number if necessary, then does the same with `val >=25` because of the logical AND (`&&`) operator; if both return true, the `return "Yes"` statement is executed.
### Resources
#### Relevant Links
- ["Logical operators" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators)
</details>

View File

@@ -1,19 +1,22 @@
---
title: Comparisons with the Logical Or Operator
---
## Comparisons with the Logical Or Operator
### Guide: Follow the code given in the example
**Spoiler Alert**
# Comparisons with the Logical Or Operator
Below is the sample code (the simplest way).
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
if ( val < 10 || val > 20 ) {
return "Outside";
if (val < 10 || val > 20) {
return "Outside";
}
```
The above code will return "Outside" only if `val` is between 10 and 20 (inclusive).
#### Code Explanation
* The above code will return "Outside" only if `val` is between 10 and 20 (inclusive).
</details>

View File

@@ -1,11 +1,15 @@
---
title: Compound Assignment With Augmented Addition
---
## Compound Assignment With Augmented Addition
# Compound Assignment With Augmented Addition
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
Computers read from left to right. So, using the '+=' operator means that the variable is added with the right number, then the variable is assigned to the sum. Like so:
var a = 9;
a += 10; // Now, 'a' is equal to 19
```js
var a = 9;
a += 10; // Now, 'a' is equal to 19
```

View File

@@ -1,10 +1,15 @@
---
title: Compound Assignment With Augmented Division
---
## Compound Assignment With Augmented Division
# Compound Assignment With Augmented Division
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
Computers read from left to right. So, using the '/=' operator means that the variable is divided with the number on the right, then the variable is assigned to the quotient. Like so:
var d = 10;
d /= 5; // Now, 'd' is equal to 2
```js
var d = 10;
d /= 5; // Now, 'd' is equal to 2
```

View File

@@ -1,10 +1,15 @@
---
title: Compound Assignment With Augmented Multiplication
---
## Compound Assignment With Augmented Multiplication
# Compound Assignment With Augmented Multiplication
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
Computers read from left to right. So, using the multiplication assignment operator means that the variable is multiplied with the number on the right, then the variable is assigned to the product. Like so:
var c = 2;
c *= 3; // Now, 'c' is equal to 6
```js
var c = 2;
c *= 3; // Now, 'c' is equal to 6
```

View File

@@ -1,10 +1,16 @@
---
title: Compound Assignment With Augmented Subtraction
---
## Compound Assignment With Augmented Subtraction
# Compound Assignment With Augmented Subtraction
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
Computers read from left to right. So, using the '-=' operator means that the variable is subtracted by the number on the right, then the variable is assigned to the difference. Like so:
var b = 10;
b -= 4; // Now, 'b' is 6
```javascript
var b = 10;
b -= 4; // Now, 'b' is 6
```

View File

@@ -1,10 +1,16 @@
---
title: Concatenating Strings with Plus Operator
---
## Concatenating Strings with Plus Operator
# Concatenating Strings with Plus Operator
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
Concatenate means to link together. Think of the '+' operator like a chain linking strings together; add the strings just like you add numbers. Make sure your spelling is correct! Take note of spaces between words.
var str = "Good " + "job!" // It says "Good job!"
var abc = "Good" + "job!" // It says "Goodjob!"
```javascript
var str = "Good " + "job!"; // It says "Good job!"
var abc = "Good" + "job!"; // It says "Goodjob!"
```

View File

@@ -1,11 +1,17 @@
---
title: Concatenating Strings with the Plus Equals Operator
---
## Concatenating Strings with the Plus Equals Operator
# Concatenating Strings with the Plus Equals Operator
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
The '+=' operator can concatenate (link) strings easily. Make sure your spelling is right, and you've left appropriate spaces.
var str = "Hello ";
str += "coding"; // Now the string reads "Hello coding"
str += "camper!"; // And now the string reads "Hello codingcamper!"
```javascript
var str = "Hello ";
str += "coding"; // Now the string reads "Hello coding"
str += "camper!"; // And now the string reads "Hello codingcamper!"
```

View File

@@ -1,12 +1,19 @@
---
title: Constructing Strings with Variables
---
## Constructing Strings with Variables
# Constructing Strings with Variables
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
Add variables that store strings, to create longer strings. Make sure your spelling and spacing is right.
var myName = "Bobby";
var myFavLetter = "B";
var sentence = "Hello, I'm " + myName + ". My favorite letter is " + myFavLetter + ".";
//The result is "Hello, I'm Bobby. My favorite letter is B.
```javascript
var myName = "Bobby";
var myFavLetter = "B";
var sentence =
"Hello, I'm " + myName + ". My favorite letter is " + myFavLetter + ".";
//The result is "Hello, I'm Bobby. My favorite letter is B.
```

View File

@@ -1,31 +1,23 @@
---
title: Count Backwards With a For Loop
---
## Count Backwards With a For Loop
# Count Backwards With a For Loop
Heres the example:
```javascript
// Example
var ourArray = [];
---
## Hints
for (var i = 10; i > 0; i -= 2) {
ourArray.push(i);
}
// Setup
var myArray = [];
// Only change code below this line.
```
#### HINT: 1
### Hint 1
* create a new for loop for myArray
#### HINT: 2
### Hint 2
* start from the first odd number just before 9
# SPOILER WARNING: SOLUTION AHEAD
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
var ourArray = [];
@@ -38,7 +30,8 @@ for (var i = 10; i > 0; i -= 2) {
var myArray = [];
// Only change code below this line.
for (var i = 9; i > 0; i-=2){
myArray.push(i)
for (var i = 9; i > 0; i -= 2) {
myArray.push(i);
}
```
```
</details>

View File

@@ -1,88 +1,62 @@
---
title: Counting Cards
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
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.
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.
Value | Cards
----- | :-------------------:
+1 | 2, 3, 4, 5, 6
0 | 7, 8, 9
-1 | 10, 'J', 'Q', 'K','A'
You will write a card counting function. It will receive a **card** parameter 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.
* Change the code below `// Only change code below this line` and up to `// Only change code above this line`
* Ensure that you are editing the inside of the `cc` function.
* Use what you've learned to check the value of each **card** parameter passed into the function.
* Keep a running count of that number.
* If the final count is 1 or greater, return **# Hold**.
* If the final count is 0 or less, return **# Bet**.
**Example Output:**
* -3 Hold
* 5 Bet
# Counting Cards
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
Use a `switch` (or `else if`) statement to count the value of each card.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
Add/subtract the value of each card to variable **count**. If the card is worth 0, don't do anything.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 3
After you've counted the cards, use an `if` statement to check the value of **count**. Also, make sure your `return` has a space between the number and the string.
> _try to solve the problem now_
## Spoiler Alert!
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
---
## Solutions
**Solution ahead!**
<details><summary>Solution 1 (Click to Show/Hide)</summary>
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
```javascript
function cc(card) {
// Only change code below this line
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--;
break;
}
if (count > 0){
return count + " Bet";
} else {
return count + " Hold";
}
// Only change code above this line
}
function cc(card) {
// Only change code below this line
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--;
break;
}
if (count > 0) {
return count + " Bet";
} else {
return count + " Hold";
}
// Only change code above this line
}
```
### Code Explanation:
#### Code Explanation
* Check the value of each card via a `switch` statement.
* The variable **count**:
@@ -101,16 +75,20 @@ After you've counted the cards, use an `if` statement to check the value of **co
* This then drops down to the `else` statement, which will return **0 Hold**.
**_Note_**: As mentioned earlier, the `switch` statement could have also been an `else if` statement.
</details>
## Additional code solution:
<details><summary>Solution 2 (Click to Show/Hide)</summary>
```javascript
function cc(card) {
// Only change code below this line
var regex = /[JQKA]/;
if (card > 1 && card < 7){count++;}
else if (card === 10 || String(card).match(regex)){count--;}
if (card > 1 && card < 7) {
count++;
} else if (card === 10 || String(card).match(regex)) {
count--;
}
if (count > 0) return count + " Bet";
return count + " Hold";
@@ -119,15 +97,16 @@ function cc(card) {
}
```
### Code explanation
#### Code Explanation
· The function first evaluates `if` the condition `card` is a value greater than `1` and lower than `7`, in which case it increments `count` by one.
· Then if the card is `10` or higher it decrements `count` by one.
· The variable `regex` is a [regular expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) representing values (letters) for the higher cards.
· The `else` statement checks those values with the `|| (logical OR)` operator; first for `10` and then for any string that matches the regular expression using [String.match()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match).
#### Resources
#### Relevant Links
* <a href='https://en.wikipedia.org/wiki/Card_counting' target='_blank' rel='nofollow'>Card counting at Wikipedia</a>
* <a href='http://www.freecodecamp.com/challenges/selecting-from-many-options-with-switch-statements' target='_blank' rel='nofollow'>Challenge: Selecting from many options with Switch Statements</a>
* <a href='http://www.freecodecamp.com/challenges/chaining-if-else-statements' target='_blank' rel='nofollow'>Challenge: Chaining If Else Statements</a>
* <a href='http://www.freecodecamp.com/challenges/increment-a-number-with-javascript' target='_blank' rel='nofollow'>Challenge: Increment a Number with JavaScript</a>
</details>

View File

@@ -3,8 +3,20 @@ title: Create Decimal Numbers with JavaScript
---
# Create Decimal Numbers with JavaScript
---
## Hints
### Hint 1
JavaScript number variables can have decimals.
var myDecimal = 2.8;
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
var myDecimal = 2.8;
```
</details>

View File

@@ -3,30 +3,36 @@ title: Declare JavaScript Variables
---
# Declare JavaScript Variables
---
## Hints
### Hint 1
When we store data in a data structure, we call it a variable. JavaScript variables are written in camel case. An example of camel case is: `camelCase`.
You can declare a variable this way
```js
var myName = "Rafael";
var myName = "Rafael";
```
ES6 introduced two other ways to declare variables. __let__ and __const__. _Let_ is pretty similar to var and for the most part is interchangeable:
```js
let myAge = 36;
let myAge = 36;
```
Where _let_ differs, is in its scope. When we declare using _var_, it's global in scope. When we declare using _let_, the scope is limited to that function. If you want to use a _let_ variable outside a function, you have to make it global in scope or redeclare it in the next function.
__const__, on the other hand, can only be declared once. Its value can never change.
```js
const myName = "Christina";
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
const myName = "Christina";
```
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
</details>

View File

@@ -1,13 +1,21 @@
---
title: Declare String Variables
---
## Declare String Variables
# Declare String Variables
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
In JavaScript, variables are <strong>dynamic</strong>. That means they can hold numbers, strings, or any other data type at a given time. To declare a string, simply <strong>initialize</strong> (create) a variable:
var a;
```javascript
var a;
```
Then, using single or double quotation marks, declare the string:
a = "Hello Camper!";
```javascript
a = "Hello Camper!";
```

View File

@@ -1,11 +1,17 @@
---
title: Decrement a Number with JavaScript
---
## Decrement a Number with JavaScript
# Decrement a Number with JavaScript
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
Decrement a number using the '--' operator:
var a = 5;
a--; // Now, 'a' is 4
--a; // Now, 'a' is 3
```javascript
var a = 5;
a--; // Now, 'a' is 4
--a; // Now, 'a' is 3
```

View File

@@ -1,35 +1,39 @@
---
title: Delete Properties from a JavaScript Object
---
## Delete Properties from a JavaScript Object
# Delete Properties from a JavaScript Object
### HINT:1
### Hint 1
* change the properties of myDog by using dot notation
# SPOILER WARNING: SOLUTION AHEAD
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"],
"bark": "bow-wow"
name: "Camper",
legs: 4,
tails: 1,
friends: ["everything!"],
bark: "bow-wow"
};
delete ourDog.bark;
// Setup
var myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"],
"bark": "woof"
name: "Happy Coder",
legs: 4,
tails: 1,
friends: ["freeCodeCamp Campers"],
bark: "woof"
};
// Only change code below this line.
delete myDog.tails;
```
</details>
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@@ -3,8 +3,21 @@ title: Divide One Decimal by Another with JavaScript
---
# Divide One Decimal by Another with JavaScript
---
## Hints
### Hint 1
JavaScript uses the `/` symbol for division.
var quotient = 0.6 / 0.3; //quotient gets the value 2
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
var quotient = 0.6 / 0.3; //quotient gets the value 2
```
</details>

View File

@@ -3,8 +3,17 @@ title: Divide One Number by Another with JavaScript
---
# Divide One Number by Another with JavaScript
---
## Hints
### Hint 1
JavaScript uses the `/` symbol for division.
var quotient = 6 / 3; //quotient will get value 2
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
var quotient = 6 / 3; //quotient will get value 2
```
</details>
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@@ -1,21 +1,15 @@
---
title: Escape Sequences in Strings
---
## Escape Sequences in Strings
# Escape Sequences in Strings
* Escape sequences allow you to use characters you might not otherwise be able to type out, such as a word boundary.
* By following this diagram with character combinations you will be able to assign escape sequences to the string.
* single quote
* " double quote
* \ backslash
* \n new line
* \r carriage return
* \t tab
* \b word boundary
* \f form feed
* The challenge requires that you don't use space between characters.
## Solution
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
var myStr = "FirstLine\n\t\\SecondLine\nThirdLine";
```
</details>

View File

@@ -1,16 +1,27 @@
---
title: Escaping Literal Quotes in Strings
---
## Escaping Literal Quotes in Strings
# Escaping Literal Quotes in Strings
---
## Hints
### Hint 1
* When you need to use a special character such as `"` inside a string you need to escape it using `\`.
* If you use double quotes `"` for the string, single quotes `'` in the string do not need to be escaped.
* If you use single quotes `'` for the string, double quotes `"` in the string do not need to be escaped.
## Solution
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
var myStr = "I am a \"double quoted\" string inside \"double quotes\".";
var otherStr = 'I am a \'single quoted\' string inside \'single quotes\'.';
var myStr = 'I am a "double quoted" string inside "double quotes".';
var otherStr = "I am a 'single quoted' string inside 'single quotes'.";
var noEscapeSingle = "There is no need to 'escape' the single quotes.";
var noEscapeDouble = 'There is no need to "escape" the double quotes.';
```
</details>

View File

@@ -1,12 +1,18 @@
---
title: Find the Length of a String
---
## Find the Length of a String
# Find the Length of a String
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
Strings have an <strong>attribute</strong> (feature) called 'length'. All you have to do is tag it after the string / variable.
var str1 = "Hello";
var length1 = str1.length; // This returns 5
var length2 = " Camper".length; // This returns 7 because the space is counted as one character.
```javascript
var str1 = "Hello";
var length1 = str1.length; // This returns 5
var length2 = " Camper".length; // This returns 7 because the space is counted as one character.
```

View File

@@ -3,8 +3,14 @@ title: Finding a Remainder in JavaScript
---
# Finding a Remainder in JavaScript
---
## Hints
### Hint 1
The remainder operator `%` gives the remainder of the division of two numbers.
var remainder = 11 % 3; //remainder gets the value 2
```javascript
var remainder = 11 % 3; //remainder gets the value 2
```
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@@ -3,34 +3,24 @@ title: Generate Random Fractions with JavaScript
---
# Generate Random Fractions with JavaScript
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.
---
## Solutions
## Note
<details><summary>Solution 1 (Click to Show/Hide)</summary>
Like Storing Values with the Equal Operator, all function calls will be resolved before the return executes, so we can return the value of the `Math.random()` function.
```javascript
function randomFraction() {
// Only change code below this line.
var result = 0;
// Math.random() can generate 0. We don't want to return a 0,
// so keep generating random numbers until we get one that isn't 0
while (result === 0) {
result = Math.random();
}
## Instructions
Change randomFraction to return a random number instead of returning 0.
## **Warning !!!**
### **Spoiler Alert !!**
A solution to follow:
function randomFraction() {
// Only change code below this line.
var result = 0;
// Math.random() can generate 0. We don't want to return a 0,
// so keep generating random numbers until we get one that isn't 0
while (result === 0) {
result = Math.random();
}
return result;
// Only change code above this line.
}
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
return result;
// Only change code above this line.
}
```
</details>

View File

@@ -1,42 +1,25 @@
---
title: Generate Random Whole Numbers with JavaScript
---
title: Generate Random Whole Numbers with JavaScript
---
## Generate Random Whole Numbers with JavaScript
# Generate Random Whole Numbers with JavaScript
Heres the setup:
```javascript
var randomNumberBetween0and19 = Math.floor(Math.random() * 20);
---
## Solutions
function randomWholeNum() {
// Only change code below this line.
Math.floor(Math.random() * 10);
return Math.floor(Math.random());
}
```
We need to use ```Math.floor()``` with ```Math.random()``` to generate and return a random whole number between 0 and 9.
Putting ```Math.floor()``` and ```Math.random()``` together, this is what our code looks like:
```javascript
Math.floor(Math.random() * 10);
```
And we need change the value of ```return```:
```javascript
return Math.floor(Math.random());
```
Heres a full solution:
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
var randomNumberBetween0and19 = Math.floor(Math.random() * 20);
function randomWholeNum() {
// Only change code below this line.
return Math.floor(Math.random()*10);
return Math.floor(Math.random() * 10);
}
```
#### Code Explanation
* We need to use ```Math.floor()``` with ```Math.random()``` to generate and return a random whole number between 0 and 9.
* Putting ```Math.floor()``` and ```Math.random()``` together
</details>

View File

@@ -1,34 +1,31 @@
---
title: Generate Random Whole Numbers within a Range
---
## Generate Random Whole Numbers within a Range
# Generate Random Whole Numbers within a Range
### Problem explanation:
_Create a function called `randomRange` that takes a range `myMin` and `myMax`and returns a random number that's greater than or equal to `myMin`, and is less than or equal to `myMax`, inclusive._
---
## Hints
#### Hint 1
### Hint 1
`randomRange` should use both `myMax` and `myMin`, and return a random number in your range.
You cannot pass the test if you are only re-using the function `ourRandomRange` inside your `randomRange` formula. You need to write your own formula that uses the variables `myMax` and `myMin`. It will do the same job as using `ourRandomRange`, but ensures that you have understood the principles of the `Math.floor()` and `Math.random()` functions.
> _try to solve the problem now_
## Spoiler alert!
**Solution ahead!**
---
## Solutions
## Basic code solution:
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function randomRange(myMin, myMax) {
return Math.floor(Math.random() * (myMax - myMin + 1) + myMin);
}
```
### Code explanation
#### Code Explanation
- `Math.random()` generates our random number between 0 and ≈ 0.9.
- Before multiplying it, it resolves the part between parenthesis `(myMax - myMin + 1)` because of the grouping operator `( )`.
- The result of that multiplication is followed by adding `myMin` and then "rounded" to the largest integer less than or equal to it (eg: 9.9 would result in 9)
@@ -41,10 +38,11 @@ If the values were `myMin = 1, myMax= 10`, one result could be the following:
5. `Math.floor(9.244326990411024) = 9`
### Resources
#### Relevant Links
- ["Math.random()" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random)
- ["Math.floor()" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor)
- ["Grouping operator" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Grouping)
</details>

View File

@@ -1,9 +1,13 @@
---
title: Global Scope and Functions
---
## Global Scope and Functions
# Global Scope and Functions
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
The scope of a variable is its visibility; where in the code is the function available? Here is a list of the different scopes a variable can have.
* **Global scope**: The variable is available throughout the code
@@ -36,7 +40,11 @@ function fun() {
}
```
Alright, here is the basic code solution.
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
// Declare your variable here
@@ -44,7 +52,6 @@ var myGlobal = 10;
function fun1() {
oopsGlobal = 5;
}
// Only change code above this line
@@ -59,3 +66,4 @@ function fun2() {
console.log(output);
}
```
</details>

View File

@@ -1,15 +1,21 @@
---
title: Global vs. Local Scope in Functions
---
## Global vs. Local Scope in Functions
# Global vs. Local Scope in Functions
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
Remember that global scope means that the variable is available throughout the entire code. Local scope, means that the variable is available within a certain range.
In this exercise, you have an `outerWear` variable in global scope with "T-shirt" as its value. You should now create another variable named `outerWear`, but this time within the function `myOutfit()`. The basic code solution is as follows:
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
var outerWear = "T-shirt";
var outerWear = "T-Shirt";
function myOutfit() {
var outerWear = "sweater";
@@ -18,4 +24,7 @@ function myOutfit() {
myOutfit();
```
The function will return the closest `outerWear` it can find. Since we created an `outerWear` inside the function, that is the 'closest', so the function will return "sweater".
#### Code Explanation
* The function will return the closest `outerWear` it can find. Since we created an `outerWear` inside the function, that is the 'closest', so the function will return "sweater".
</details>

View File

@@ -1,109 +1,104 @@
---
title: Golf Code
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
In the game of 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. You've to return the correct string according to this table which lists the strokes in order of priority; top (highest) to bottom (lowest):
Strokes | Return
:--------- | :-------------
1 | "Hole-in-one!"
<= par - 2 | "Eagle"
par - 1 | "Birdie"
par | "Par"
par + 1 | "Bogey"
par + 2 | "Double Bogey"
&gt;= par + 3 | "Go Home!"
**par** and **strokes** will always be numeric and positive.
* Change the code below `// Only change code below this line` and above `// Only change code above this line`.
* Ensure that you're editing the inside of the `golfScore` function.
* You will have to make the function return exactly the same string as shown shown in the table, depending on the value of the parameters **par** and **strokes** that are passed to your function.
# Golf Code
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
---
## Problem Explanation
Change the code below `// Only change code below this line` and above `// Only change code above this line`.
Ensure that you're editing the inside of the `golfScore` function.
You will have to make the function return exactly the same string as shown shown in the table, depending on the value of the parameters **par** and **strokes** that are passed to your function.
### Hint 1
`+number -number` can be used to increase or decrease a parameter in your condition.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
You use `if / else if` chains to return different values in different scenarios.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 3
Control the flow of your function based on the tables order of priority - top (highest) to bottom (lowest) to return matching string values.
> _try to solve the problem now_
## Spoiler Alert!
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
---
## Solutions
**Solution ahead!**
<details><summary>Solution 1 (Click to Show/Hide)</summary>
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
```javascript
function golfScore(par, strokes) {
// Only change code below this line
if (strokes == 1) {
return "Hole-in-one!";
} else if (strokes <= par - 2) {
return "Eagle";
} else if (strokes == par - 1) {
return "Birdie";
} else if (strokes == par) {
return "Par";
} else if (strokes == par + 1) {
return "Bogey";
} else if (strokes == par + 2) {
return "Double Bogey";
} else {
return "Go Home!";
}
// Only change code above this line
}
// Change these values to test
golfScore(5, 4);
```
function golfScore(par, strokes) {
// Only change code below this line
if (strokes == 1){
return "Hole-in-one!";
} else if (strokes <= par -2){
return "Eagle";
} else if (strokes == par -1) {
return "Birdie";
} else if (strokes == par) {
return "Par";
} else if (strokes == par +1) {
return "Bogey";
} else if (strokes == par +2) {
return "Double Bogey";
} else {
return "Go Home!";
}
// Only change code above this line
}
// Change these values to test
golfScore(5, 4);
### Code Explanation:
#### Code Explanation
* Compare the parameters **par** and **strokes** to return appropriate string values.
* `if / else if` chain is used for flow control.
* String "Go Home!" is returned for every condition where **strokes** is greater than or equal to **par + 3**.
</details>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
## Alternative code solution:
```javascript
var names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"];
var names = [
"Hole-in-one!",
"Eagle",
"Birdie",
"Par",
"Bogey",
"Double Bogey",
"Go Home!"
];
function golfScore(par, strokes) {
// Only change code below this line
if (strokes == 1){
if (strokes == 1) {
return names[0];
}
else if (strokes <= par-2){
} else if (strokes <= par - 2) {
return names[1];
}
else if (strokes == par -1){
} else if (strokes == par - 1) {
return names[2];
}
else if (strokes == par){
} else if (strokes == par) {
return names[3];
}
else if (strokes == par +1){
} else if (strokes == par + 1) {
return names[4];
}
else if (strokes == par +2){
} else if (strokes == par + 2) {
return names[5];
} else {
return names[6];
}
else {return names[6];}
// Only change code above this line
}
@@ -111,25 +106,35 @@ function golfScore(par, strokes) {
golfScore(5, 4);
```
## Code explanation
#### Code Explanation
Since we already have an array defined in the variable `names` we can take advantage of it and use it for our return statements using indexes (eg: `names[0] is the first one`). That way, if you ever need to change a specific result you wouldn't need to look for it inside the function, it'd be at the beginning, in your array.
</details>
<details><summary>Solution 3 (Click to Show/Hide)</summary>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
(Using Multiple Conditional (Ternary) Operators)
```js
function golfScore(par, strokes) {
return (strokes == 1) ? names[0] :
(strokes <= par - 2) ? names[1] :
(strokes == par - 1) ? names[2] :
(strokes == par) ? names[3] :
(strokes == par + 1) ? names[4] :
(strokes == par + 2) ? names[5] :
(strokes >= par + 3) ? names[6] :
"Change Me";
}
function golfScore(par, strokes) {
return strokes == 1
? names[0]
: strokes <= par - 2
? names[1]
: strokes == par - 1
? names[2]
: strokes == par
? names[3]
: strokes == par + 1
? names[4]
: strokes == par + 2
? names[5]
: strokes >= par + 3
? names[6]
: "Change Me";
}
```
### Resources
#### Relevant Links
* <a href='https://en.wikipedia.org/wiki/Golf' target='_blank' rel='nofollow'>Golf</a>
* <a href='http://www.freecodecamp.com/challenges/chaining-if-else-statements' target='_blank' rel='nofollow'>Challenge: Chaining If Else Statements</a>
@@ -137,3 +142,5 @@ Since we already have an array defined in the variable `names` we can take advan
* <a href='http://www.freecodecamp.com/challenges/comparison-with-the-less-than-equal-to-operator' target='_blank' rel='nofollow'>Challenge: Comparison with the Less Than Equal To Operator</a>
* ["Array" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
* <a href='https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/use-multiple-conditional-ternary-operators/' target='_blank' rel='nofollow'>Use Multiple Conditional (Ternary) Operators</a>
</details>

View File

@@ -1,11 +1,17 @@
---
title: Increment a Number with JavaScript
---
## Increment a Number with JavaScript
# Increment a Number with JavaScript
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
You can easily increment (add one) to a number variable by using the '++' increment operator. For example:
var a = 6;
a++; // Now, 'a' is equal to 7 -- post-fixing
++a; // Now, 'a' is equal to 8 -- pre-fixing
```javascript
var a = 6;
a++; // Now, 'a' is equal to 7 -- post-fixing
++a; // Now, 'a' is equal to 8 -- pre-fixing
```

View File

@@ -1,13 +1,11 @@
---
title: Basic JavaScript
---
## Basic JavaScript
# Basic JavaScript
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/quadratic-equations/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@@ -1,9 +1,15 @@
---
title: Initializing Variables with the Assignment Operator
---
## Initializing Variables with the Assignment Operator
# Initializing Variables with the Assignment Operator
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Hints
### Hint 1
To <strong>initialize</strong> a variable is to give it an initial value. You can declare and initialize a variable like so:
var num = 5; // This is equal to 5
```javascript
var num = 5; // This is equal to 5
```

View File

@@ -1,70 +1,51 @@
---
title: Introducing Else If statements
---
## Introducing Else If statements
# Introducing Else If statements
Remember to use Read-Search-Ask if you get stuck. Try to pair program and write your own code.
---
## Problem Explanation
### Problem explanation:
```javascript
function testElseIf(val) {
if (val > 10) {
return "Greater than 10";
}
if (val < 5) {
return "Smaller than 5";
}
return "Between 5 and 10";
}
// Change this value to test
testElseIf(7);
```
We'll be modifying the existing code above so that it follows the flow of logic that an **else-if** statement has.
### Hint: 1
``` javascript
### Hint 1
```javascript
if (val > 10) {
return "Greater than 10";
}
```
```
All `if` statements and their variants start off with an `if` statement.
> _try to solve the problem now_
### Hint: 2
``` javascript
### Hint 2
```javascript
else if (val < 5) {
return "Smaller than 5";
}
```
```
Statements between the `if` statement and the `else` statement in an **else-if** flow are in the else-if format
> _try to solve the problem now_
### Hint: 3
``` javascript
### Hint 3
```javascript
else {
return "Between 5 and 10";
}
```
```
The last statement in an **else-if** flow is in the `else` format
### Spoiler alert!
![spoiler](http://discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
Solution ahead!
## Basic code solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function testElseIf(val) {
if (val > 10) {
return "Greater than 10";
}
else if (val < 5) {
} else if (val < 5) {
return "Smaller than 5";
}
else {
return "Between 5 and 10";
} else {
return "Between 5 and 10";
}
}
@@ -72,9 +53,10 @@ function testElseIf(val) {
testElseIf(7);
```
## Code explanation
#### Code Explanation
The structure of an **else-if logic flow** is an initial `if` statement, one more `if-else` statements, and one final `else` statement.
### Resources
#### Relevant Links
- ["if...else" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else)
</details>

View File

@@ -1,40 +1,36 @@
---
title: Introducing Else statements
---
## Introducing Else statements
# Introducing Else statements
### Problem explanation:
· _Combine the `if` statements into a single `if/else` statement._
#### Hint 1
---
## Hints
### Hint 1
When the first `if` statement returns `false` the next piece of code is executed/evaluated (like `return`, `if` or `else` statements).
> _try to solve the problem now_
>
#### Hint 2
### Hint 2
Sometimes `if` (`condition`) statements can be replaced by `else {code to execute instead} ` statements (in essence you are telling your function to do _"y"_ if it can't do _"x"_ instead of specifying _"x"_ several times) .
> _try to solve the problem now_
>
## Spoiler alert!
**Solution ahead!**
## Basic code solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function testElse(val) {
var result = "";
// Only change code below this line
if (val > 5) {
result = "Bigger than 5";
}
else {
} else {
result = "5 or smaller";
}
// Only change code above this line
return result;
}
@@ -43,9 +39,10 @@ function testElse(val) {
testElse(4);
```
### Code explanation
#### Code Explanation
The function first evaluates `if` the condition `val > 5` evaluates to `true`. If it doesn't, it executes the next statement (`else { return "5 or smaller";})`.
### Resources
#### Relevant Links
- ["if...else" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else)
</details>

View File

@@ -1,10 +1,35 @@
---
title: Iterate Odd Numbers With a For Loop
---
## Iterate Odd Numbers With a For Loop
# Iterate Odd Numbers With a For Loop
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
Heres the example:
---
## Hints
### Hint 1
After string `// Only change code below this line.` we add `for` loop. You need to copy loop from the top:
```javascript
for (var i = 0; i < 10; i += 2) {
ourArray.push(i);
}
```
### Hint 2
And change `initialization` `var i = 0` to `var i = 1`, also you need change name of the array `ourArray` to `myArray`:
```javascript
for (var i = 1; i < 10; i += 2) {
myArray.push(i);
}
```
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
var ourArray = [];
@@ -16,39 +41,10 @@ for (var i = 0; i < 10; i += 2) {
// Setup
var myArray = [];
// Only change code below this line.
```
Heres a solution:
After string `// Only change code below this line.` we add `for` loop. You need to copy loop from the top:
```javascript
for (var i = 0; i < 10; i += 2) {
ourArray.push(i);
}
```
And change `initialization` `var i = 0` to `var i = 1`, also you need change name of the array `ourArray` to `myArray`:
```javascript
for (var i = 1; i < 10; i += 2) {
myArray.push(i);
}
```
Heres a full solution:
```javascript
var ourArray = [];
for (var i = 0; i < 10; i += 2) {
ourArray.push(i);
}
// Setup
var myArray = [];
// Only change code below this line.
for (var i = 1; i < 10; i += 2) {
myArray.push(i);
}
```
</details>

View File

@@ -1,11 +1,13 @@
---
title: Iterate Through an Array with a For Loop
---
## Iterate Through an Array with a For Loop
### Problem explanation:
_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`._
# Iterate Through an Array with a For Loop
#### Hint 1
---
## Hints
### Hint 1
Remember the structure of a `for` loop:
`for ([initialization]; [condition]; [final-expression])
statement`
@@ -13,22 +15,20 @@ Remember the structure of a `for` loop:
- The `[initialization]` part is executed only once (the first time).
- The `[condition]` is checked on every iteration.
- The `[final-expression]` is executed along the `statement` if `[condition]` resolves to `true`.
> _try to solve the problem now_
#### Hint 2
### Hint 2
Remember how accumulators work:
`var x += i`
- The variable `x` is going to act as the accumulator.
- The variable `i` is the one which value will be stored (and accumulated) inside `x`
- The expression `+=` is an just abreviation of `x = x + i`
> _try to solve the problem now_
## Spoiler alert!
**Solution ahead!**
---
## Solutions
## Code solution:
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
var total = 0;
@@ -37,21 +37,22 @@ for (var i = 0; i < myArr.length; i++) {
}
```
### Code explanation
#### Code Explanation
- Inititialization: `i` gets a value of `0` and its used as a counter.
- Condition: the subsequent code is executed as long as `i` is lower than the length of `myArr` (which is 5; five numbers but arrays are zero based).
- Final-expression: `i` is incremented by `1`.
- Statement: The function adds `myArr[i]`'s value to `total` until the condition isn't met like so:
```text
```
total + myArr[0] -> 0 + 2 = 2
total + myArr[1] -> 2 + 3 = 5
total + myArr[2] -> 5 + 4 = 9
total + myArr[3] -> 9 + 5 = 14
total + myArr[4] -> 14 + 6 = 20
```
</details>
## Alternative code solution:
<details><summary>Solution 2 (Click to Show/Hide)</summary>
```javascript
for (var y = myArr.length - 1; y >= 0; y--) {
@@ -59,23 +60,24 @@ for (var y = myArr.length - 1; y >= 0; y--) {
}
```
### Code explanation
#### Code Explanation
This works similarly to the last solution but it's faster<sup><a href="#cite1">1</a></sup> although it might not meet your requirements if order is important.
- Initialization: `y` gets the `myArr.length`'s value once so the function doesn't need to check it at `condition` every time the loop is executed.
- Condition: the loop is executed as long as `y` is greater than `0`.
- Final-expression: `y` is decremented by `1`.
- Statement: The function adds `myArr[y]`'s value to `total` until the condition isn't met like so:
```text
```
total + myArr[4] -> 0 + 6 = 6
total + myArr[3] -> 6 + 5 = 11
total + myArr[2] -> 11 + 4 = 15
total + myArr[1] -> 15 + 3 = 18
total + myArr[0] -> 18 + 2 = 20
```
### Sources
#### Relevant Links
<span id="cite1">1</span>. ["Are loops really faster in reverse?", *stackoverflow.com*](https://stackoverflow.com/questions/1340589/are-loops-really-faster-in-reverse)
### Resources
#### Relevant Links
- ["for" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for)
</details>

View File

@@ -1,11 +1,18 @@
---
title: Iterate with JavaScript Do...While Loops
---
## Iterate with JavaScript Do...While Loops
# Iterate with JavaScript Do...While Loops
* `Do...While` loops makes sure that the code is executed at least once, and after the execution, if the condition inside the `while()` is **true**, it continues with the loop, otherwise it stop.
---
## Problem Explanation
`Do...While` loops makes sure that the code is executed at least once, and after the execution, if the condition inside the `while()` is **true**, it continues with the loop, otherwise it stop.
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
## Solution
```javascript
var myArray = [];
var i = 10;
@@ -13,5 +20,7 @@ var i = 10;
do {
myArray.push(i);
i++;
} while(i <= 10);
} while (i <= 10);
```
</details>

View File

@@ -1,10 +1,9 @@
---
title: Iterate with JavaScript For Loops
---
## Iterate with JavaScript For Loops
# Iterate with JavaScript For Loops
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-for-loops/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@@ -1,26 +1,35 @@
---
title: Iterate with JavaScript While Loops
---
## Iterate with JavaScript While Loops
# Iterate with JavaScript While Loops
---
## Problem Explanation
While loops will run as long as the condition inside the ( ) is true.
Example:
```javascript
while(condition){
code...
while (condition) {
//code...
}
```
## Hint 1:
---
## Hints
### Hint 1
Use a iterator variable such as i in your condition
```javascript
var i = 0;
while(i <= 4){
}
while (i <= 4) {}
```
## Spoiler Alert Solution Ahead!
## Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
// Setup
@@ -28,9 +37,9 @@ var myArray = [];
// Only change code below this line.
var i = 0;
while (i <= 4){
myArray.push(i);
i++;
while (i <= 4) {
myArray.push(i);
i++;
}
```
</details>

View File

@@ -1,12 +1,17 @@
---
title: Local Scope and Functions
---
## Local Scope and Functions
# Local Scope and Functions
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
---
## Problem Explanation
Local scope means that the variable is available within a certain area. In the case of this exercise, `myVar` is only available within the function, and not anywhere outside.
Here is the basic code solution to create a local `myVar` variable.
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function myLocalScope() {
@@ -15,4 +20,7 @@ function myLocalScope() {
}
myLocalScope();
```
The variable only exists in the function. Outside the function, it is non-existent.
#### Code Explanation
* The variable only exists in the function. Outside the function, it is non-existent.
</details>

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