fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@ -0,0 +1,67 @@
---
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:")
### 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.
#### Relevant Links
* <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.
> _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
* To check for the type of a parameter, you can use `typeof`.
> _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
* 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_
## Spoiler Alert!
![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';
}
// test here
booWho(null);
```
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLnK/0' target='_blank' rel='nofollow'>Run Code</a>
# 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`.
#### Relevant Links
* <a>Using typeof</a>
* <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:")
* Please add your username only if you have added any **relevant main contents**. (![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **_DO NOT_** _remove any existing usernames_)
> See ![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 ":point_right:") <a href='http://forum.freecodecamp.com/t/algorithm-article-template/14272' target='_blank' rel='nofollow'>**`Wiki Challenge Solution Template`**</a> for reference.

View File

@ -0,0 +1,203 @@
---
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:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") 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:
1. `(['a', 'b', 'c', 'd'], 2)` is expected to be `[['a', 'b'], ['c', 'd']]`
2. `([0, 1, 2, 3, 4, 5], 3)` is expected to be `[[0, 1, 2], [3, 4, 5]]`
3. `([0, 1, 2, 3, 4, 5], 2)` is expected to be `[[0, 1], [2, 3], [4, 5]]`
4. `([0, 1, 2, 3, 4, 5], 4)` is expected to be `[[0, 1, 2, 3], [4, 5]]`
#### Relevant Links
* <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
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
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
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!
![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 chunkArrayInGroups(arr, size) {
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;
}
```
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/24' target='_blank' rel='nofollow'>Run Code</a>
### 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.
* Inside our loop, we push to `temp` using `temp.push(arr[a]);` if the remainder of `a / size` is not equal to `size - 1`.
* Otherwise, we push to `temp`, push `temp` to the `result` variable and reset `temp` to an empty array.
* Next, if `temp` isn't an empty array, we push it to `result`.
* Finally, we return the value of `result`.
#### Relevant Links
* <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:
```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;
}
```
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/Cj9x/3' target='_blank' rel='nofollow'>Run Code</a>
### 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`.
* Note that this for loop does not loop through `arr`. Instead, we are using the loop to generate numbers we can use as indices to slice the array in the right locations.
* Inside our loop, we create each chunk using `arr.slice(i, i+size)`, and add this value to `arr2` with `arr2.push()`.
* Finally, we return the value of `arr2`.
#### Relevant Links
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push' target='_blank' 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>
* <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;
while (i < arr.length) {
newArr.push(arr.slice(i, i+size));
i += size;
}
return newArr;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
```
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/26' target='_blank' rel='nofollow'>Run Code</a>
### 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.
* Inside our loop, we push to the `newArr` array using `arr.slice(i, i+size)`. For the first time it loops, it will look something like:
newArr.push(arr.slice(1, 1+2))
* After we push to `newArr`, we add the variable of `size` onto `i`.
* Finally, we return the value of `newArr`.
#### Relevant Links
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push' target='_blank' 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>
* <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:
```javascript
function chunkArrayInGroups(arr, size) {
var newArr = [];
while (arr.length) {
newArr.push(arr.splice(0,size));
}
return newArr;
}
```
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/579' target='_blank' rel='nofollow'>Run Code</a>
### 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.
* Inside our loop, we push to the `newArr` array using `arr.splice(0, size)`.
* For each iteration of `while` loop, it deletes `size` number of elements from the front of `arr` and push them as an array to `newArr`.
* Finally, we return the value of `newArr`.
#### Relevant Links
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push' target='_blank' rel='nofollow'>Array.push()</a>
* <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:
```javascript
function chunkArrayInGroups(arr, size) {
if (arr.length <= size){
return [arr];
}
else {
return [arr.slice(0,size)].concat(chunkArrayInGroups(arr.slice(size),size));
}
}
```
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/579' target='_blank' rel='nofollow'>Run Code</a>
### Code Explanation:
* Array smaller than size is returned nested.
* For any array larger than size, it's splited in two. First segment is nested and concatnated with second second segment which makes a recursive call.
#### Relevant Links
* <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/splice' target='_blank' rel='nofollow'>Array.splice()</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:")
* Please add your username only if you have added any **relevant main contents**. (![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **_DO NOT_** _remove any existing usernames_)
> See ![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 ":point_right:") <a href='http://forum.freecodecamp.com/t/algorithm-article-template/14272' target='_blank' rel='nofollow'>**`Wiki Challenge Solution Template`**</a> for reference.

View File

@ -0,0 +1,35 @@
---
title: Confirm the Ending
---
## Confirm the Ending
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
# 🌻 Intermediate Code Solution:
(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");
```
#### 🚀 [Run Code](https://repl.it/repls/SardonicRoundAfkgaming)
# 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.
- For example `str.slice(10, 17)` would return `give me`.
- In this case we only include one parameter which it will copy everything from the starting index.
- 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
- [String.prototype.slice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice)

View File

@ -0,0 +1,64 @@
---
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:
The algorithm to convert from Celsius to Fahrenheit is the temperature in Celsius times `9/5`, plus `32`.
You are given a variable **celsius** representing a temperature in Celsius. Use the variable **fahrenheit** already defined and apply the algorithm to assign it the corresponding temperature in Fahrenheit.
#### Relevant Links
* <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
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
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!
![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 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';
}
}
// Change the inputs below to test your code
convertToF(30);
```
### 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:")
* Please add your username only if you have added any **relevant main contents**. (![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **_DO NOT_** _remove any existing usernames_)
> See ![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 ":point_right:") <a href='http://forum.freecodecamp.com/t/algorithm-article-template/14272' target='_blank' rel='nofollow'>**`Wiki Challenge Solution Template`**</a> for reference.

View File

@ -0,0 +1,113 @@
---
title: Factorialize a Number
---
![Recursion](//discourse-user-assets.s3.amazonaws.com/original/2X/d/dcf927a2e8c3beb7a9c28770153821982398bd99.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:
Return the factorial of the provided integer. If the integer is represented with the letter n, a factorial is the product of all positive integers less than or equal to n.
Factorials are often represented with the shorthand notation n!
For example: `5! = 1 * 2 * 3 * 4 * 5 = 120`
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
This one starts easily since `0! = 1`, so you can go ahead and simply `return 1` there.
We can use that as an `if` in order to break the loop we're going to create using a **recursive function**. It will check if the number you gave the function is 0 (which would be the end of your factorial chain). Functions "end" when they return anything. In fact, **all** functions without an explicit `return` statement will return `undefined`.
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:
[**num** = 5]
Is 5 _equal_ to 1 or 0? **No** ---> Oki doki, let's continue...
**Returns:**
(**5** _(_second execution_: **4** _(_third execution_: **3** _(_fourth execution_: **2** __fifth execution_: **1**))))
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:
**Second Execution**: _num_ = 5-1 = **4** -> is _num_ 0 or 1? No
--> return the multiplication between 4 and the next result when _num_ is now 4-1.
**Third Execution**: _num_ = 4 - 1 = **3** -> is _num_ 0 or 1? No
--> return the multiplication between 3 and the next result when _num_ is now 3-1.
**Fourth Execution**: _num_ = 3-1 = **2** -> is _num_ 0 or 1? No
--> return the multiplication between 2 and the next result when _num_ is now 2-1.
**Fifth Execution**: _num_ = 2-1 = **1** -> is _num_ 0 or 1? Yep
--> 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
* <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)
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Code Solution:
function factorialize(num) {
if (num === 0) { return 1; }
return num * factorialize(num-1);
}
factorialize(5);
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/1' target='_blank' rel='nofollow'>Run Code</a>
## 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
* <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>
## ![: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:")
* Please add your username only if you have added any **relevant main contents**. (![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **_DO NOT_** _remove any existing usernames_)
> See ![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 ":point_right:") <a href='http://forum.freecodecamp.com/t/algorithm-article-template/14272' target='_blank' rel='nofollow'>**`Wiki Challenge Solution Template`**</a> for reference.

View File

@ -0,0 +1,71 @@
---
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:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
Remove all <a href='https://guide.freecodecamp.org/javascript/falsy-values/' target='_blank' rel='nofollow'>falsy</a> values from an array.
#### Relevant Links
* <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
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
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
Then we need to add a `filter()` with the falsy values function...
> _try to solve the problem now_
## Spoiler Alert!
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**Solution ahead!**
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
function bouncer(arr) {
return arr.filter(Boolean);
}
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/32' target='_blank' rel='nofollow'>Run Code</a>
### 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.
#### 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:
**`Thanks @renelis @abhisekp @Rafase282 for your help with Algorithm: Falsy Bouncer`**
## ![: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:")
* Please add your username only if you have added any **relevant main contents**. (![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **_DO NOT_** _remove any existing usernames_)
> See ![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 ":point_right:") <a href='http://forum.freecodecamp.com/t/algorithm-article-template/14272' target='_blank' rel='nofollow'>**`Wiki Challenge Solution Template`**</a> for reference.

View File

@ -0,0 +1,139 @@
---
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:
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.
#### Relevant Links
* <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
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
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
Remember how to get the length of elements on the array? `Array[index].length`.
> _try to solve the problem now_
## Spoiler Alert!
![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:
function findLongestWordLength(str) {
var words = str.split(' ');
var maxLength = 0;
for (var i = 0; i < words.length; i++) {
if (words[i].length > maxLength) {
maxLength = words[i].length;
}
}
return maxLength;
}
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/5' target='_blank' rel='nofollow'>Run Code</a>
### 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.
Then check for the longest word by comparing the current word to the previous one and storing the new longest word. At the end of the loop just return the number value of the variable maxLength.
#### Relevant Links
* <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:
**Using `.reduce()`**
function findLongestWordLength(s) {
return s.split(' ')
.reduce(function(x, y) {
return Math.max(x, y.length)
}, 0);
}
![: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:
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>
In case you're wondering about that `0` after the callback function, it is used to give an initial value to the `x`, so that `Math.max` will know where to start.
#### Relevant Links
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-reduce/14299' target='_blank' rel='nofollow'>JS Reduce</a>
* <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>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
**Using recursiveness**
function findLongestWordLength(str) {
//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;
}
//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(" "));
}
}
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/7' target='_blank' rel='nofollow'>Run Code</a>
### 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.
#### 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 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:")
* Please add your username only if you have added any **relevant main contents**. (![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **_DO NOT_** _remove any existing usernames_)
> See ![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 ":point_right:") <a href='http://forum.freecodecamp.com/t/algorithm-article-template/14272' target='_blank' rel='nofollow'>**`Wiki Challenge Solution Template`**</a> for reference.

View File

@ -0,0 +1,41 @@
---
title: 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
`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
Do not forget, if none of the numbers in the array pass the test, it should return `undefined`.
>*try to solve the problem now*
## Basic Solution
```javascript
function findElement(arr, func) {
let num = 0;
for(var i = 0; i < arr.length; i++) {
num = arr[i];
if (func(num)) {
return num;
}
}
return undefined;
}
```
## 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.

View File

@ -0,0 +1,13 @@
---
title: 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

@ -0,0 +1,99 @@
---
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:
* 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..
#### Relevant Links
* <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
* 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
* 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
* 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!
![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:
**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;
}
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/30' target='_blank' rel='nofollow'>Run Code</a>
### 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`.
If they are _all_ found, the loop will finish without returning anything and we get to `return true`.
#### Relevant Links
* <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:
**Declarative**
function mutation(arr) {
return arr[1].toLowerCase()
.split('')
.every(function(letter) {
return arr[0].toLowerCase()
.indexOf(letter) != -1;
});
}
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/31' target='_blank' rel='nofollow'>Run Code</a>
### 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.
`Every` will basically give you letter by letter to compare, which we do by using `indexOf` on the first string. `indexOf` will give you -1 if the current `letter` is missing. We check that not to be the case, for if this happens even once `every` will be false.
#### Relevant Links
* <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:")
* Please add your username only if you have added any **relevant main contents**. (![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **_DO NOT_** _remove any existing usernames_)
> See ![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 ":point_right:") <a href='http://forum.freecodecamp.com/t/algorithm-article-template/14272' target='_blank' rel='nofollow'>**`Wiki Challenge Solution Template`**</a> for reference.

View File

@ -0,0 +1,115 @@
---
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:
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.
#### Relevant Links
* <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
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
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
Make the variable created store the current value and append the word to it.
> _try to solve the problem now_
## Spoiler Alert!
![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:
function repeatStringNumTimes(str, num) {
var accumulatedStr = '';
while (num > 0) {
accumulatedStr += str;
num--;
}
return accumulatedStr;
}
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/19' target='_blank' rel='nofollow'>Run Code</a>
### 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`
* Then we just have to add the string to the variable created on step one, and increase or decrease `num` depending on how you set the loop.
* At the end of the loop, return the variable for the repeated word.
#### Relevant Links
* <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>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
function repeatStringNumTimes(str, num) {
if(num < 0)
return "";
if(num === 1)
return str;
else
return str + repeatStringNumTimes(str, num - 1);
}
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/21' target='_blank' rel='nofollow'>Run Code</a>
### Code Explanation:
* This solution uses recursion.
* We check if `num` is negative and return an empty string if true.
* Then we check if it's equal to 1 and in that case we return the string itself.
* If not, we add the string to a call of our function with `num` being decreased by 1, which will add another `str` and another.. until eventually `num` is 1\. And return that whole process.
#### Relevant Links
* <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:
function repeatStringNumTimes(str, num) {
return num > 0 ? str.repeat(num) : '';
}
repeatStringNumTimes("abc", 3);
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/85' target='_blank' rel='nofollow'>Run Code</a>
### 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.
#### 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:")
* Please add your username only if you have added any **relevant main contents**. (![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **_DO NOT_** _remove any existing usernames_)
> See ![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 ":point_right:") <a href='https://forum.freecodecamp.com/t/algorithm-article-template/14272' target='_blank' rel='nofollow'>**`Wiki Challenge Solution Template`**</a> for reference.

View File

@ -0,0 +1,151 @@
---
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:
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.
> _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
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
Pay close attention to the timing of the storing of variables when working with loops
> _try to solve the problem now_
## Spoiler Alert!
![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:
**(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;
}
return results;
}
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/734' target='_blank' rel='nofollow'>Run Code</a>
### Code Explanation:
* Create a variable to store the _results_ as an array.
* Create an outer loop to iterate through the outer array.
* Create a second variable to hold the largest number and initialise it with the first number. This must be outside an inner loop so it won't be reassigned until we find a larger number.
* Create said inner loop to work with the sub-arrays.
* Check if the element of the sub array is larger than the currently stored largest number. If so, then update the number in the variable.
* After the inner loop, save the largest number in the corresponding position inside of the `results` array.
* And finally return said array.
#### Relevant Links
* <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:
**(Declarative approach)**
function largestOfFour(arr) {
return arr.map(function(group){
return group.reduce(function(prev, current) {
return (current > prev) ? current : prev;
});
});
}
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/733' target='_blank' rel='nofollow'>Run Code</a>
### 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()`
* the callback function passed to the reduce method takes the previous value and the current value and compares the two values
* if the current value is higher than the previous value we set it as the new previous value for comparison with the next item within the array or returns it to the map method callback if it's the last item
#### Relevant Links
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-map/14294' target='_blank' rel='nofollow'>Array.prototype.map()</a>
* <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:
**(Declarative approach)**
function largestOfFour(arr) {
return arr.map(Function.apply.bind(Math.max, null));
}
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/17' target='_blank' rel='nofollow'>Run Code</a>
### 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:")
* 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.
So we want to create a function that does the work of `Math.max` and accepts input as an array (which by it doesn't by default).
In other words, it would be really nice and simple if this worked by itself:
`Math.max([9, 43, 20, 6]); // Resulting in 43`
Alas, it doesn't.
* To do the work of accepting arguments in the shape of an array, there is this `Function.prototype.apply` method, but it complicates things a bit by _invoking_ the _context_ function.
i.e. `Math.max.apply(null, [9, 43, 20, 6]);` would invoke something like a `Max.max` method. What we're looking for... almost.
Here we're passing `null` as the _context_ of the `Function.prototype.apply` method as `Math.max` doesn't need any context.
* Since `arr.map` expects a callback function, not just an expression, we create a function out of the previous expression by using the `Function.bind` method.
* Since, `Function.prototype.apply` is a static _method_ of the same `Function` _object_, we can call `Function.prototype.bind` on `Function.prototype.apply` i.e. `Function.prototype.apply.bind`.
* Now we pass the _context_ for the `Function.prototype.apply.bind` call (in this case we want `Math.max`so we can gain its functionality).
* Since the embedded `Function.prototype.apply` method will also require a context as it's 1st argument, we need to pass it a bogus _context_.
* So, we pass `null` as the 2nd param to `Function.prototype.apply.bind` which gives a _context_ to the `Math.max` method.
* Since, `Math.max` is independent of any _context_, hence, it ignores the bogus _context_ given by `Function.prototype.apply` method call.
* Thus, our `Function.prototype.apply.bind(Math.max, null)` makes a new function accepting the `arr.map` values i.e. the inner arrays.
#### Relevant Links
* <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:")
* Please add your username only if you have added any **relevant main contents**. (![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **_DO NOT_** _remove any existing usernames_)
> See ![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 ":point_right:") <a href='http://forum.freecodecamp.com/t/algorithm-article-template/14272' target='_blank' rel='nofollow'>**`Wiki Challenge Solution Template`**</a> for reference.

View File

@ -0,0 +1,65 @@
---
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:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
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.
#### 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>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
Start by splitting the string by 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: 2
Look up the built in function to reverse a 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: 3
Do not forget to join the characters back together after you reverse them.
> _try to solve the problem now_
## Spoiler Alert!
![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:
function reverseString(str) {
return str.split('').reverse().join('');
}
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU' target='_blank' rel='nofollow'>Run Code</a>
### 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.
* Using the `split()` function will turn our string into an array of characters, keep that in mind as we move forward.
* Next we _chain_ the `reverse()` function, which takes our array of characters and reverses them.
* 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.
## ![: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:")
* Please add your username only if you have added any **relevant main contents**. (![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **_DO NOT_** _remove any existing usernames_)
> See ![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 ":point_right:") <a href='http://forum.freecodecamp.com/t/algorithm-article-template/14272' target='_blank' rel='nofollow'>**`Wiki Challenge Solution Template`**</a> for reference.

View File

@ -0,0 +1,92 @@
---
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:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") 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.
#### Relevant Links
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice' target='_blank' rel='nofollow'>str.slice()</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice' target='_blank' rel='nofollow'>str.splice()</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") 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
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
Increment the index after performing the splice.
> _try to solve the problem now_
## Spoiler Alert!
![warning sign](https://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:
```js
function frankenSplice(arr1, arr2, n) {
// It's alive. It's alive!
let localArray = arr2.slice();
for (let i = 0; i < arr1.length; i++) {
localArray.splice(n, 0, arr1[i]);
n++;
}
return localArray;
}
```
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/repls/RedundantGrossGenres' target='_blank' rel='nofollow'>Run Code</a>
### 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.
* Using the `slice()` function we can create an exact replica of `arr2` and assign the result of the operation to a variable, `localArray`.
* Now that we have an array that we can mutate on, we can iterate through every item in the first array. For each item in the first array we can use the `splice()` function to insert the item into index `n` of `localArray`.
* We increment the index `n` by one. This will ensure that every item from the `arr1` is inserted into `localArray` in the proper index position.
* Finally, we return the `localArray` and end the function.
## 🌻 Intermediate Code Solution:
```js
function frankenSplice(arr1, arr2, n) {
// It's alive. It's alive!
let localArr = arr2.slice();
localArr.splice(n, 0, ...arr1);
return localArr;
}
```
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/repls/BelovedNegativeMoto' target='_blank' rel='nofollow'>Run Code</a>
* Since our goal is to return the new array with out altering `arr1` or `arr2` we create a `localArr` and add all the items from `arr2` using the `slice()` function
* Since the `splice()` function will mutate (alter) arrays and can be used to add new elements we will use it to add the contents of `arr1` into `localArr`. `n` is the starting position where our content will be inserted. We won't be deleting any elements so the next argument is `0`. Then we add the entire contents of `arr1` using spread syntax `...`.
* `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:")
* Please add your username only if you have added any **relevant main contents**. (![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **_DO NOT_** _remove any existing usernames_)
> See ![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 ":point_right:") <a href='http://forum.freecodecamp.com/t/algorithm-article-template/14272' target='_blank' rel='nofollow'>**`Wiki Challenge Solution Template`**</a> for reference.

View File

@ -0,0 +1,132 @@
---
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:
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.
#### Relevant Links
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String' target='_blank' rel='nofollow'>Global String Object</a>
* <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-tolowercase/15948' target='_blank' rel='nofollow'>JS String Prototype ToLowerCase</a>
* <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
* 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
* 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
* 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!
![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:
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(' ');
}
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/8' target='_blank' rel='nofollow'>Run Code</a>
### Code Explanation:
We are modifying the `replaceAt` function using prototype to facilitate the use of the program.
Split the string by white spaces, and create a variable to track the updated title. Then we use a loop to turn turn the first character of the word to uppercase and the rest to lowercase. by creating concatenated string composed of the whole word in lowercase with the first character replaced by it's uppercase.
#### Relevant Links
* <a href='http://forum.freecodecamp.com/t/javascript-for-loop/14666s-Explained' target='_blank' rel='nofollow'>JS For Loops Explained</a>
* <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>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
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");
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/9' target='_blank' rel='nofollow'>Run Code</a>
### 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.
#### Relevant Links
* <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:
function titleCase(str) {
return str.toLowerCase().replace(/(^|\s)\S/g, (L) => L.toUpperCase());
}
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/14' target='_blank' rel='nofollow'>Run Code</a>
### 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()`.
- Replace every word' first character to uppercase using `.replace`.
- Search for character at the beginning of each word i.e. matching any character following a `space` or matching the first character of the whole string, by using the following pattern.
- Regex explanation:
* Find all non-whitespace characters `(\S`)
* At the beginning of string `(^)`
* Or after any whitespace character `(\s)`
* The `g` modifier searches for other such word pattern in the whole string and replaces them.
* This solution works with national symbols and accented letters as illustrated by following examples
`international characters:` 'бабушка курит трубку' // -> 'Бабушка Курит Трубку'
`accented characters:` 'località àtilacol' // -> 'Località Àtilacol'
#### Relevant Links
* <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:")
* Please add your username only if you have added any **relevant main contents**. (![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **_DO NOT_** _remove any existing usernames_)
> See ![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 ":point_right:") <a href='http://forum.freecodecamp.com/t/algorithm-article-template/14272' target='_blank' rel='nofollow'>**`Wiki Challenge Solution Template`**</a> for reference.

View File

@ -0,0 +1,100 @@
---
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:
We need to reduce the length of the string or **truncate** it if it is longer than the given maximum lengths specified and add `...` to the end. If it is not that long then we keep it as is.
#### Relevant Links
* <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
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
You will need to use the slice() method and specify where to start and where to stop.
> _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
Do not forget that when we truncate the word, we also must count the length added by `...`
> _try to solve the problem now_
## Spoiler Alert!
![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:
function truncateString(str, num) {
// Clear out that junk in your trunk
if (str.length > num && num > 3) {
return str.slice(0, (num - 3)) + '...';
} else if (str.length > num && num <= 3) {
return str.slice(0, num) + '...';
} else {
return str;
}
}
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/55' target='_blank' rel='nofollow'>Run Code</a>
### Code Explanation:
* First we start off with a simple `if` statement to determine one of three outcomes...
* If our string length is greater than the `num` we want to truncate at, and our truncate point is at least three characters or more into the string, we return a slice of our string starting at character 0, and ending at `num - 3`. We then append our `'...'` to the end of the string.
* However, if our string length is greater than the `num` but `num` is within the first three characters, we don't have to count our dots as characters. Therefore, we return the same string as above, with one difference: The endpoint of our slice is now just `num`.
* Finally, if none of the above situations are 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:
function truncateString(str, num) {
if (str.length <= num) {
return str;
} else {
return str.slice(0, num > 3 ? num - 3 : num) + '...';
}
}
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/54' target='_blank' rel='nofollow'>Run Code</a>
### Code Explanation:
* First we need an if-statement to test if the length of the full string passed in as the first argument already fits within the size limit passed in as the second argument. If so we can just return the string that was passed in.
if (str.length <= num)
return str;
* If our `if` statement above fails, we move to the `else`, where we are going to return a "slice" of the string. The slice method extracts a section of a string and returns a new string. Here we pass 0 as the starting point for our slice. To determine the endpoint, we use a ternary operator: `num > 3 ? num - 3 : num`. In our ternary, if `num` is larger than 3, we must factor in the three dots to our total length, and thus we end our slice at `num-3`. If num is less than or equal to 3, our slice gets an end variable of just `num`. Finally, the `'...'` is appended to the end of our new string and is returned.
} else {
return str.slice(0, num > 3 ? num - 3 : num) + '...';
}
* **NOTE** In order to understand the above code, you need to understand how a Ternary Operator works. The Ternary Operator is frequently used as a shortcut for the `if` statement and follows this format: `condition ? expr1 : expr2`. If the `condition` evaluates to true, the operator returns the value of `expr1`. Otherwise, it returns the value of `expr2`.
#### Relevant Links
* <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:")
* Please add your username only if you have added any **relevant main contents**. (![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **_DO NOT_** _remove any existing usernames_)
> See ![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 ":point_right:") <a href='http://forum.freecodecamp.com/t/algorithm-article-template/14272' target='_blank' rel='nofollow'>**`Wiki Challenge Solution Template`**</a> for reference.

View File

@ -0,0 +1,198 @@
---
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:
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.
#### Relevant Links
* <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
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
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
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!
![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:
function getIndexToIns(arr, num) {
arr.sort(function(a, b) {
return a - b;
});
for (var a = 0; a < arr.length; a++) {
if (arr[a] >= num)
return a;
}
return arr.length;
}
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/36' target='_blank' rel='nofollow'>Run Code</a>
## Code Explanation:
* First I sort the array using `.sort(callbackFuntion)` 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:
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);
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/2547' target='_blank' rel='nofollow'>Run Code</a>
## 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:
by [@HarinaPana](/u/harinapana)
function getIndexToIns(arr, num) {
arr.sort(function(a, b) {
return a - b;
});
var i = 0;
while (num > arr[i]) {
i++;
}
return i;
}
getIndexToIns([40, 60], 50);
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/4135' target='_blank' rel='nofollow'>Run Code</a>
## 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:
by [@faustodc](/u/faustodc)
function getIndexToIns(arr, num) {
arr.push(num);
arr.sort(function(a, b){return a-b});
return arr.indexOf(num);
}
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/EB10/1' target='_blank' rel='nofollow'>Run Code</a>
## 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.
* Lastly we return the postion or index of `num` in the array with the `indexOf()` function.
#### Relevant Links
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-push/14298' target='_blank' rel='nofollow'>push()</a>
* <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:
**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;
}
getIndexToIns([40, 60], 500);
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/63' target='_blank' rel='nofollow'>Run Code</a>
## 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.
* Then we use ternary operations to check whether we got an index returned or `-1`. We only get `-1` when the index was not found meaning when we get a false for all elements int he array, and for such case, it would mean that `num` should be inserted at the end of the list hence why we use `arr.length`.
#### Relevant Links
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex' target='_blank' rel='nofollow'>Array.findIndex()</a>
* <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:
by [@nivrith](/u/nivrith)
function getIndexToIns(arr, num) {
return arr.concat(num).sort((a,b) => a-b).indexOf(num);
}
getIndexToIns([1,3,4],2);
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/IUJE/0' target='_blank' rel='nofollow'>Run Code</a>
## 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
* Lastly we return the postion or index of `num` in the array with the `indexOf()` method
#### Relevant Links
* <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:")
* Please add your username only if you have added any **relevant main contents**. (![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **_DO NOT_** _remove any existing usernames_)
> See ![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 ":point_right:") <a href='http://forum.freecodecamp.com/t/algorithm-article-template/14272' target='_blank' rel='nofollow'>**`Wiki Challenge Solution Template`**</a> for reference.

View File

@ -0,0 +1,71 @@
---
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
Method:
- 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:
```javascript
for (let user in obj) {
if(obj.user.online === true) {
//code
}
}
```
- 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) {
//code
}
}
```
### Solution:
```javascript
let users = {
Alan: {
age: 27,
online: false
},
Jeff: {
age: 32,
online: true
},
Sarah: {
age: 48,
online: false
},
Ryan: {
age: 19,
online: true
}
};
function countOnline(obj) {
// change code below this line
let result = 0;
for (let user in obj) {
if(obj[user].online === true) {
result++;
}
}
return result;
// change code above this line
}
console.log(countOnline(users));
```

View File

@ -0,0 +1,11 @@
---
title: Access an Array's Contents Using Bracket Notation
---
## Access an Array's Contents Using Bracket Notation
- Remember the arrays index begins at 0 so the postion of b will be located in `myArray[1]`.
## Solution
```javascript
myArray[1] = "anything we want";
```

View File

@ -0,0 +1,43 @@
---
title: Access Property Names with Bracket Notation
---
## Access Property Names with Bracket Notation
Method:
- 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
};
function checkInventory(scannedItem) {
return juice[scannedItem];
}
```
## Solution:
```javascript
let foods = {
apples: 25,
oranges: 32,
plums: 28,
bananas: 13,
grapes: 35,
strawberries: 27
};
// do not change code above this line
function checkInventory(scannedItem) {
// change code below this line
return foods[scannedItem];
}
// change code below this line to test different cases:
console.log(checkInventory("apples"));
```

View File

@ -0,0 +1,20 @@
---
title: Add Items to an Array with push() and unshift()
---
## Add Items to an Array with push() and unshift()
- 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:
```javascript
function mixedNumbers(arr) {
// change code below this line
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']));
```

View File

@ -0,0 +1,29 @@
---
title: Add Items Using splice()
---
## Add Items Using splice()
- 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:
```javascript
arr.splice(0, 1, "Two");
/* The first two paramemters are the same as they were in the previous challenge.
`0` will start the `splice()` function off at index 0.
The second parameter `1` will remove only 1 variable from the array.
The final variable "Two" will replace the variable in arr[0].
Note: The final parameter can take more than 1 arguement.
*/
```
## Solution:
```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']));
```

View File

@ -0,0 +1,27 @@
---
title: Add Key-Value Pairs to JavaScript Objects
---
## Add Key-Value Pairs to JavaScript Objects
- 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}
```
- The above code will create a ney `key-value` within the object.
## Solution
```javascript
let foods = {
apples: 25,
oranges: 32,
plums: 28
};
// change code below this line
foods['bananas'] = 13;
foods['grapes'] = 35;
foods['strawberries'] = 27;
// change code above this line
console.log(foods);
```

View File

@ -0,0 +1,28 @@
---
title: 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:
```javascript
function quickCheck(arr, elem) {
if(arr.indexOf(elem)>=0) {
return true;
}
return false;
}
console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
```
- `Solution-2` demonstrates how the problem can be solved using the `? : (conditional)` operator.
## Solution-2:
```javascript
function quickCheck(arr, elem) {
return arr.indexOf(elem) >= 0 ? true : false;
}
console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
```

View File

@ -0,0 +1,54 @@
---
title: Check if an Object has a Property
---
## Check if an Object has a Property
Method:
- The simplest way to complete this challenge is to create an `ìf-statement` to check wether or not the object contains all useres, then to return a true or false statement. The first solution does just this.
- The second solution works in exactly the same way, only it uses 1 line of code - `Conditional(ternary)-Operator` - within the function.
[developer.mozilla.org](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) provides a more in depth analysis of the ternary operator.
### Solution-1:
```javascript
let users = {
Alan: {
age: 27,
online: true
},
Jeff: {
age: 32,
online: true
},
Sarah: {
age: 48,
online: true
},
Ryan: {
age: 19,
online: true
}
};
function isEveryoneHere(obj) {
// change code below this line
if(users.hasOwnProperty('Alan','Jeff','Sarah','Ryan')) {
return true;
}
return false;
// change code above this line
}
console.log(isEveryoneHere(users));
```
### Solution-2:
```javascript
function isEveryoneHere(obj) {
return (users.hasOwnProperty('Alan','Jeff','Sarah','Ryan')) ? true : false;
}
```

View File

@ -0,0 +1,18 @@
---
title: 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:
```javascript
function spreadOut() {
let fragment = ['to', 'code'];
let sentence = ["learning", ...fragment, "is", "fun"]; // change this line
return sentence;
}
// do not change code below this line
console.log(spreadOut());
```

View File

@ -0,0 +1,34 @@
---
title: Copy an Array with the Spread Operator
---
## Copy an Array with the Spread Operator
- The final hint in the example tells you to use a recently learned method.
- The spread operator copies all elements into a new empty object.
```javascript
while (num >= 1) {
newArr = [...arr]
num--;
}
```
- 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:
```javascript
function copyMachine(arr, num) {
let newArr = [];
while (num >= 1) {
// change code below this line
newArr.push([...arr]);
// change code above this line
num--;
}
return newArr;
}
// change code here to test different cases:
console.log(copyMachine([true, false, true], 2));
```

View File

@ -0,0 +1,24 @@
---
title: 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.
```
## Solution:
```javascript
function forecast(arr) {
// change code below this line
return arr.slice(2,4);
}
// do not change code below this line
console.log(forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']));
```

View File

@ -0,0 +1,24 @@
---
title: Create complex multi-dimensional arrays
---
## Create complex multi-dimensional arrays
- 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"]]];
```
- Using this logic insert strings `deep` , `deeper` and `deepest` in the matrix three levels deep, four levels deep and five levels deep respectively.
## Solution:
```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"]]] ]
// change code above this line
];
```

View File

@ -0,0 +1,42 @@
---
title: Generate an Array of All Object Keys with Object.keys()
---
## Generate an Array of All Object Keys with Object.keys()
### Method:
- 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:
```javascript
let users = {
Alan: {
age: 27,
online: false
},
Jeff: {
age: 32,
online: true
},
Sarah: {
age: 48,
online: false
},
Ryan: {
age: 19,
online: true
}
};
function getArrayOfUsers(obj) {
// change code below this line
return Object.keys(obj);
// change code above this line
}
console.log(getArrayOfUsers(users));
```

View File

@ -0,0 +1,13 @@
---
title: 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

@ -0,0 +1,40 @@
---
title: 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.
```javascript
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){
```
## 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:
```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
};
};
// 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));
```

View File

@ -0,0 +1,45 @@
---
title: Modify an Array Stored in an Object
---
## Modify an Array Stored in an Object
### Method:
- 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:
```javascript
let user = {
name: 'Kenneth',
age: 28,
data: {
username: 'kennethCodesAllDay',
joinDate: 'March 26, 2016',
organization: 'freeCodeCamp',
friends: [
'Sam',
'Kira',
'Tomo'
],
location: {
city: 'San Francisco',
state: 'CA',
country: 'USA'
}
}
};
function addFriend(userObj, friend) {
// change code below this line
userObj.data.friends.push(friend);
return userObj.data.friends;
// change code above this line
}
console.log(addFriend(user, 'Pete'));
```

View File

@ -0,0 +1,40 @@
---
title: Modify an Object Nested Within an Object
---
## Modify an Object Nested Within an Object
Method:
- 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',
first_level_object: {
level_2: '2 levels deep',
second_level_object: {
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';
```
## Solution:
```javascript
let userActivity = {
id: 23894201352,
date: 'January 1, 2017',
data: {
totalUsers: 51,
online: 42
}
};
// change code below this line
userActivity.data.online = 45;
// change code above this line
console.log(userActivity);
```

View File

@ -0,0 +1,18 @@
---
title: Remove Items from an Array with pop() and shift()
---
## Remove Items from an Array with pop() and shift()
- 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:
```javascript
function popShift(arr) {
let popped = arr.pop();
let shifted = arr.shift();
return [shifted, popped];
}
// do not change code below this line
console.log(popShift(['challenge', 'is', 'not', 'complete']));
```

View File

@ -0,0 +1,20 @@
---
title: Remove Items Using splice()
---
## Remove Items Using splice()
- 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:
```javascript
function sumOfTen(arr) {
// change code below this line
arr.splice(1,2);
// change code above this line
return arr.reduce((a, b) => a + b);
}
// do not change code below this line
console.log(sumOfTen([2, 5, 1, 5, 2, 1]));
```

View File

@ -0,0 +1,33 @@
---
title: Use an Array to Store a Collection of Data
---
## Use an Array to Store a Collection of Data
### Method:
- 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:
1. Array literals
2. Array constructors
- 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"]
```
- We can also initialize the values in the array when we declare it, example:
```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:
```js
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).

View File

@ -0,0 +1,24 @@
---
title: 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:
```javascript
let foods = {
apples: 25,
oranges: 32,
plums: 28,
bananas: 13,
grapes: 35,
strawberries: 27
};
// change code below this line
delete foods.oranges;
delete foods.plums;
delete foods.strawberries;
// change code above this line
console.log(foods);
```

View File

@ -0,0 +1,17 @@
---
title: 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 -->
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
```
Notice that the length of the array is 4, and the position of the last element of the array is 3.

View File

@ -0,0 +1,33 @@
---
title: 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 -->
Consider the following multi-dimensional array:
```javascript
var arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]];
```
This is what it looks like in tabular form.
| Position | 0 | 1 | 2 | 3 |
| --- |---|---|---|---|
| **0** | 1 | 4 | 7 | 10|
| **1** | 2 | 5 | 8 | 11|
| **2** | 3 | 6 | 9 | 12|
Now all you have to do, is choose the coordinates of the data you desire! For examples, if we want `myNum` to equal 8, then...
```javascript
var myNum = arr[2][1]; // Equal to 8
```
Or, if you want it to equal 1. You do...
```javascript
var myNum = arr[0][0]; // Equal to 1
```
You first start off by choosing what column the number is in, then you choose the row. It's kind of like the x-y coordinate plane!

View File

@ -0,0 +1,66 @@
---
title: Accessing Nested Arrays
---
## Accessing Nested Arrays
### Accessing elements within an array using bracket notation `[]`
```js
var fruitBasket = ['apple', 'banana' 'orange', 'melon'];
var favoriteFruit = fruitBasket[2];
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
```js
var garage = [
{
type: 'car',
color: 'red',
make: 'Ford'
},
{
type: 'motorbike',
color: 'black',
make: 'Yamaha'
},
{
type: 'bus',
color: 'yellow',
make: 'Blue Bird'
}
];
var busColor = garage[2].color; // 'yellow'
```
## Solution:
```js
// Setup
var myPlants = [
{
type: "flowers",
list: [
"rose",
"tulip",
"dandelion"
]
},
{
type: "trees",
list: [
"fir",
"pine",
"birch"
]
}
];
// Only change code below this line
var secondTree = myPlants[1].list[1];
```

View File

@ -0,0 +1,52 @@
---
title: Accessing Nested Objects
---
## Accessing Nested Objects
Clue: ***" Use bracket notation for properties with a space in their name."***
If we look at our object:
```javascript
var myStorage = {
"car": {
"inside": {
"glove box": "maps",
"passenger seat": "crumbs"
},
"outside": {
"trunk": "jack"
}
}
};
```
Our object name is `myStorage`.
|-- Inside that we have a nested object called `car`.
|--- Inside that we have two more called `inside` and `outside` each with their
own properties
You can visualize the object structure like this, if it helps:
```
myStorage
|-- car
|--- inside
|----- glove box: maps
|----- passenger seat: crumbs
|--- outside
|----- trunk: jack
```
We are asked to assign the contents of `glove box` ,
which we can see is nested in the `inside` object,
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'
```
You must replace `complete here` with the correct way to access the property.
See clue above if you get stuck.

View File

@ -0,0 +1,19 @@
---
title: Accessing Object Properties with Bracket Notation
---
## Accessing Object Properties with Bracket Notation
Here's one possible solution:
```js
var testObj = {
"an entree": "hamburger",
"my side": "veggies",
"the drink": "water"
};
// Only change code below this line
var entreeValue = testObj["an entree"]; // Change this line
var drinkValue = testObj["the drink"]; // Change this line
```

View File

@ -0,0 +1,18 @@
---
title: Accessing Object Properties with Dot Notation
---
## Accessing Object Properties with Dot Notation
Here's one possible solution:
```js
var testObj = {
"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
```

View File

@ -0,0 +1,21 @@
---
title: Accessing Object Properties with Variables
---
## Accessing Object Properties with Variables
Here's a working solution in case you are stuck:
```js
// Setup
var testObj = {
12: "Namath",
16: "Montana",
19: "Unitas"
};
// Only change code below this line;
var playerNumber = 16; // Change this Line
var player = testObj[playerNumber]; // Change this Line
```

View File

@ -0,0 +1,31 @@
---
title: 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!"]
};
ourDog.bark = "bow-wow";
```
Here's a solution:
```js
var myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"]
};
// Only change code below this line.
myDog.bark = "woof";
```

View File

@ -0,0 +1,9 @@
---
title: Add Two Numbers with JavaScript
---
# Add Two Numbers with JavaScript
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 -->

View File

@ -0,0 +1,26 @@
---
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:
```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';
}
return answer;
}
```

View File

@ -0,0 +1,11 @@
---
title: 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 -->
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!"

View File

@ -0,0 +1,13 @@
---
title: 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 -->
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:
```javascript
processed = processArg(7); // Equal to 2
```

View File

@ -0,0 +1,19 @@
---
title: Build JavaScript Objects
---
# Build JavaScript Objects
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"]
};
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

@ -0,0 +1,64 @@
---
title: Chaining If Else Statements
---
## Chaining If Else Statements
* ```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"_
#### 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
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:
```javascript
function testSize(num) {
// Only change code below this line
if (num < 5){
return "Tiny";
}
else if (num < 10) {
return "Small";
}
else if (num < 15){
return "Medium";
}
else if (num < 20){
return "Large";
}
else {
return "Huge";
}
// Only change code above this line
}
```
· Run code at [repl.it](https://repl.it/@AdrianSkar/Basic-JS-Chaining-ifelse-statements)
### 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
- ["if...else" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else)

View File

@ -0,0 +1,19 @@
---
title: 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 -->
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!
Now, if you want to comment an entire paragraph, that can be easily accomplished with...
/*
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

@ -0,0 +1,43 @@
---
title: Comparison with the Equality Operator
---
## Comparison with the equality operator
### 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
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!**
## Basic code solution:
```javascript
function testEqual(val) {
if (val == 12) { // Change this line
return "Equal";
}
return "Not equal";
}
// Change this value to test
testEqual(10);
```
· [Run code at repl.it](https://repl.it/@AdrianSkar/Basic-JS-Equality-operator)
### 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
- ["Equality operator" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Equality_())

View File

@ -0,0 +1,20 @@
---
title: Comparison with the Greater Than Operator
---
## Comparison with the Greater Than Operator
`>` (Greater Than) is a logical operator that returns true case the value on the left is higher than the one on the right.
## Basic Solution
```javascript
function testGreaterThan(val) {
if (val > 100)
return "Over 100";
if (val > 10)
return "Over 10";
return "10 or Under";
}
```

View File

@ -0,0 +1,20 @@
---
title: 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
```javascript
function testGreaterOrEqual(val) {
if (val >= 20)
return "20 or Over";
if (val >= 10)
return "10 or Over";
return "Less than 10";
}
```

View File

@ -0,0 +1,17 @@
---
title: Comparison with the Inequality Operator
---
## Comparison with the Inequality Operator
* `!=` (Inequality) is a logical operator that returns true case the value on the left is different from the one on the right.
* The inequality operator considers `7` and `"7"` to be the same because it doesn't compare the type of the variable.
## Basic Solution
```javascript
function testNotEqual(val) {
if (val != 99)
return "Not Equal";
return "Equal";
}
```

View File

@ -0,0 +1,20 @@
---
title: Comparison with the Less Than Operator
---
## Comparison with the Less Than Operator
**`<`** (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
```javascript
function testLessThan(val) {
if (val < 25)
return "Under 25";
if (val < 55)
return "Under 55";
return "55 or Over";
}
```

View File

@ -0,0 +1,20 @@
---
title: Comparison with the Less Than Or Equal To Operator
---
## Comparison with the Less Than Or Equal To Operator
**`<=`** (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
```javascript
function testLessOrEqual(val) {
if (val <= 12)
return "Smaller Than or Equal to 12";
if (val <= 24)
return "Smaller Than or Equal to 24";
return "More Than 24";
}
```

View File

@ -0,0 +1,53 @@
---
title: Comparison with the strict equality operator
---
## Comparison with the strict equality operator
### 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
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
_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!**
## Basic code solution:
```javascript
// Setup
function testStrict(val) {
if (val === 7) { // Change this line
return "Equal";
}
return "Not equal";
}
// Change this value to test
testStrict(10);
```
### 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
<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
- ["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)

View File

@ -0,0 +1,38 @@
---
title: Comparison with the Strict Inequality Operator
---
## Comparison with the Strict Inequality Operator
### 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
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:
```javascript
function testStrictNotEqual(val) {
if (val !== 17) {
return "Not equal";
}
return "Equal";
}
// Change this value to test
testStrictNotEqual(10);
```
### 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
- ["Non-identity / strict inequality (!==)" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Non-identity_strict_inequality_(!))

View File

@ -0,0 +1,47 @@
---
title: Comparisons with the && (logical AND) operator
---
## Comparisons with the && (logical AND) operator
### 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
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
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:
```javascript
function testLogicalAnd(val) {
// Only change code below this line
if (val <= 50 && val >= 25) {
return "Yes";
}
// Only change code above this line
return "No";
}
// Change this value to test
testLogicalAnd(10);
```
· [Run code at repl.it](https://repl.it/@AdrianSkar/Basic-JS-Comparison-with-the-and-operator)
### 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
- ["Logical operators" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators)

View File

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

View File

@ -0,0 +1,11 @@
---
title: 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 -->
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

View File

@ -0,0 +1,10 @@
---
title: 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 -->
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

View File

@ -0,0 +1,10 @@
---
title: 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 -->
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

View File

@ -0,0 +1,10 @@
---
title: 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 -->
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

View File

@ -0,0 +1,10 @@
---
title: 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 -->
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!"

View File

@ -0,0 +1,11 @@
---
title: 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 -->
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!"

View File

@ -0,0 +1,12 @@
---
title: 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 -->
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.

View File

@ -0,0 +1,44 @@
---
title: Count Backwards With a For Loop
---
## Count Backwards With a For Loop
Heres the example:
```javascript
// Example
var ourArray = [];
for (var i = 10; i > 0; i -= 2) {
ourArray.push(i);
}
// Setup
var myArray = [];
// Only change code below this line.
```
#### HINT: 1
* create a new for loop for myArray
#### HINT: 2
* start from the first odd number just before 9
# SPOILER WARNING: SOLUTION AHEAD
```javascript
var ourArray = [];
for (var i = 10; i > 0; i -= 2) {
ourArray.push(i);
}
// Setup
var myArray = [];
// Only change code below this line.
for (var i = 9; i > 0; i-=2){
myArray.push(i)
}
```

View File

@ -0,0 +1,134 @@
---
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
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") 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
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
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)
**Solution ahead!**
## ![: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
}
```
### Code Explanation:
* Check the value of each card via a `switch` statement.
* The variable **count**:
* Increases by 1 if the card is a 2, 3, 4, 5, or 6.
* Since 7, 8, and 9 aren't worth anything, we ignore those cards in our `switch` statement.
* Decreases by 1 if the card is a 10, 'J', 'Q', 'K', or 'A'.
* Check the value of **count** and return the appropriate response.
**Example Run**
* `cc(2);` runs.
* The `switch` statement hits `case 2`, jumps down and adds 1 to the variable `count`.
* The `switch` statement then hits the `break` and `cc(3);` runs.
* This cycle continues until the final call is made, `cc('A');`.
* After the `switch` statement, the `if` statement checks `count`, which is now 0.
* 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.
## Additional code solution:
```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 (count > 0) return count + " Bet";
return count + " Hold";
// Only change code above this line
}
```
· Run code at [repl.it](https://repl.it/@AdrianSkar/Basic-JS-Counting-cards).
### 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
* <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>

View File

@ -0,0 +1,10 @@
---
title: Create Decimal Numbers with JavaScript
---
# Create Decimal Numbers with JavaScript
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 -->

View File

@ -0,0 +1,32 @@
---
title: Declare JavaScript Variables
---
# Declare JavaScript Variables
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";
```
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;
```
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";
```
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@ -0,0 +1,13 @@
---
title: 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 -->
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;
Then, using single or double quotation marks, declare the string:
a = "Hello Camper!";

View File

@ -0,0 +1,11 @@
---
title: 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 -->
Decrement a number using the '--' operator:
var a = 5;
a--; // Now, 'a' is 4
--a; // Now, 'a' is 3

View File

@ -0,0 +1,35 @@
---
title: Delete Properties from a JavaScript Object
---
## Delete Properties from a JavaScript Object
### HINT:1
* change the properties of myDog by using dot notation
# SPOILER WARNING: SOLUTION AHEAD
```javascript
var ourDog = {
"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"
};
// Only change code below this line.
delete myDog.tails;
```
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@ -0,0 +1,10 @@
---
title: Divide One Decimal by Another with JavaScript
---
# Divide One Decimal by Another with JavaScript
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 -->

View File

@ -0,0 +1,10 @@
---
title: Divide One Number by Another with JavaScript
---
# Divide One Number by Another with JavaScript
Javascript uses the `/` symbol for division.
var quotient = 6 / 3; //quotient will get value 2
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@ -0,0 +1,10 @@
---
title: Escape Sequences in Strings
---
## Escape Sequences in Strings
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/javascript-algorithms-and-data-structures/basic-javascript/escape-sequences-in-strings/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

@ -0,0 +1,16 @@
---
title: Escaping Literal Quotes in Strings
---
## Escaping Literal Quotes in Strings
* 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
```javascript
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.';
```

View File

@ -0,0 +1,12 @@
---
title: 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 -->
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.

View File

@ -0,0 +1,10 @@
---
title: Finding a Remainder in JavaScript
---
# Finding a Remainder in JavaScript
The remainder operator `%` gives the remainder of the division of two numbers.
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

@ -0,0 +1,36 @@
---
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.
## Note
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.
## 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 -->

View File

@ -0,0 +1,42 @@
---
title: Generate Random Whole Numbers with JavaScript
---
## Generate Random Whole Numbers with JavaScript
Heres the setup:
```javascript
var randomNumberBetween0and19 = Math.floor(Math.random() * 20);
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:
```javascript
var randomNumberBetween0and19 = Math.floor(Math.random() * 20);
function randomWholeNum() {
// Only change code below this line.
return Math.floor(Math.random()*10);
}
```

View File

@ -0,0 +1,9 @@
---
title: Generate Random Whole Numbers within a Range
---
## Generate Random Whole Numbers within a Range
**Help for passing the final test:**
*`randomRange` should use both `myMax` and `myMin`, and return a random number in your range.*
You cannot pass the final 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.

View File

@ -0,0 +1,61 @@
---
title: 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 -->
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
* **Local scope**: Available in only a certain area (like only within function)
* **Block scope**: Available within an *even more* certain area (like an if-statement)
Your task is to understand how adding `var` (and not adding) before a variable name, can change the variable's scope.
When you add `var` before the variable name, its scope is determined by where it is placed. Like so:
```javascript
var num1 = 18; // Global scope
function fun() {
var num2 = 20; // Local (Function) Scope
if (true) {
var num3 = 22; // Block Scope (within an if-statement)
}
}
```
When you don't, this is the result:
```javascript
num1 = 18; // Global scope
function fun() {
num2 = 20; // Global Scope
if (true) {
num3 = 22; // Global Scope
}
}
```
Alright, here is the basic code solution.
```javascript
// Declare your variable here
var myGlobal = 10;
function fun1() {
oopsGlobal = 5;
}
// Only change code above this line
function fun2() {
var output = "";
if (typeof myGlobal != "undefined") {
output += "myGlobal: " + myGlobal;
}
if (typeof oopsGlobal != "undefined") {
output += " oopsGlobal: " + oopsGlobal;
}
console.log(output);
}
```

View File

@ -0,0 +1,21 @@
---
title: 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 -->
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 it's value. You should now create another variable named `outerWear`, but this time within the function `myOutfit()`. The basic code solution as follows:
```javascript
var outerWear = "T-shirt";
function myOutfit() {
var outerWear = "sweater";
return outerWear;
}
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".

View File

@ -0,0 +1,124 @@
---
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.
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") 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
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
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)
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
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:
* 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**.
## Alternative code solution:
```javascript
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){
return names[0];
}
else if (strokes <= par-2){
return names[1];
}
else if (strokes == par -1){
return names[2];
}
else if (strokes == par){
return names[3];
}
else if (strokes == par +1){
return names[4];
}
else if (strokes == par +2){
return names[5];
}
else {return names[6];}
// Only change code above this line
}
// Change these values to test
golfScore(5, 4);
```
·Run at [repl.it](https://repl.it/@AdrianSkar/Basic-JS-Golf-code)
## 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.
### Resources
* <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>
* <a href='http://www.freecodecamp.com/challenges/comparison-with-the-greater-than-equal-to-operator' target='_blank' rel='nofollow'>Challenge: Comparison with the Greater Than Equal To Operator</a>
* <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)

View File

@ -0,0 +1,11 @@
---
title: 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 -->
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

View File

@ -0,0 +1,13 @@
---
title: 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

@ -0,0 +1,9 @@
---
title: 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 -->
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

View File

@ -0,0 +1,80 @@
---
title: 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:
```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
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
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
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:
```javascript
function testElseIf(val) {
if (val > 10) {
return "Greater than 10";
}
else if (val < 5) {
return "Smaller than 5";
}
else {
return "Between 5 and 10";
}
}
// Change this value to test
testElseIf(7);
```
:rocket: [Run code](https://repl.it/@RyanPisuena/GoldenWorriedRuntime)
## 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
- ["if...else" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else)

View File

@ -0,0 +1,52 @@
---
title: Introducing Else statements
---
## Introducing Else statements
### Problem explanation:
· _Combine the `if` statements into a single `if/else` statement._
#### 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
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:
```javascript
function testElse(val) {
var result = "";
// Only change code below this line
if (val > 5) {
result = "Bigger than 5";
}
else {
result = "5 or smaller";
}
// Only change code above this line
return result;
}
// Change this value to test
testElse(4);
```
· [Run code at repl.it](https://repl.it/@AdrianSkar/Introducing-else-statements)
### 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
- ["if...else" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else)

View File

@ -0,0 +1,54 @@
---
title: 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:
```javascript
var ourArray = [];
for (var i = 0; i < 10; i += 2) {
ourArray.push(i);
}
// 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);
}
```

View File

@ -0,0 +1,74 @@
---
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`._
#### Hint 1
Remember the structure of a `for` loop:
`for ([initialization]; [condition]; [final-expression])
statement`
- 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_
## Spoiler alert!
**Solution ahead!**
## Code solution:
```javascript
for (var i = 0; i < myArr.length; i++) {
total += myArr[i];
}
```
· Run code at [repl.it](https://repl.it/@AdrianSkar/Basic-JS-iterate-for-loop).
### 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
```
## Alternative code solution:
```javascript
for (var y = myArr.length - 1; y >= 0; y--) {
total += myArr[y];
}
```
· Run code at [repl.it](https://repl.it/@AdrianSkar/Basic-JS-iterate-for-loop).
### 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
<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
- ["for" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for)

View File

@ -0,0 +1,17 @@
---
title: 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.
## Solution
```javascript
var myArray = [];
var i = 10;
do {
myArray.push(i);
i++;
} while(i <= 10);
```

View File

@ -0,0 +1,10 @@
---
title: 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

@ -0,0 +1,36 @@
---
title: Iterate with JavaScript While Loops
---
## Iterate with JavaScript While Loops
While loops will run as long as the condition inside the ( ) is true.
Example:
```javascript
while(condition){
code...
}
```
## Hint 1:
Use a iterator variable such as i in your condition
```javascript
var i = 0;
while(i <= 4){
}
```
## Spoiler Alert Solution Ahead!
## Solution:
```javascript
// Setup
var myArray = [];
// Only change code below this line.
var i = 0;
while (i <= 4){
myArray.push(i);
i++;
}
```

View File

@ -0,0 +1,18 @@
---
title: 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 -->
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.
```javascript
function myLocalScope() {
var myVar;
console.log(myVar);
}
myLocalScope();
```
The variable only exists in the function. Outside the function, it is non-existent.

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