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,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.

View File

@ -0,0 +1,10 @@
---
title: Logical Order in If Else Statements
---
## Logical Order in If Else Statements
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/javascript-algorithms-and-data-structures/basic-javascript/logical-order-in-if-else-statements/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,28 @@
---
title: Manipulate Arrays With pop()
---
## Manipulate Arrays With pop()
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
## Problem Explanation
Get rid of the last element in the array. Then, assign that ridden element to `removedFromMyArray`.
## Hint 1:
Call `.pop()` on the array, and assign it to `removedFromMyArray`.
## Spoiler! Code Solution:
```javascript
var removedFromMyArray = myArray.pop();
=======
Remove the last element of an array with the pop() method, like so:
```javascript
var arr = [1, 2, 3, 4, 5];
arr.pop(); // This got rid of 5
```

View File

@ -0,0 +1,12 @@
---
title: Manipulate Arrays With push()
---
## Manipulate Arrays With push()
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
The `push()` method allows you to append (add to the end) an element to an array. Like so...
```javascript
var arr = [1, 2, 3, 4];
arr.push(5); // Now, the array is [1, 2, 3, 4, 5]
```

View File

@ -0,0 +1,12 @@
---
title: Manipulate Arrays With shift()
---
## Manipulate Arrays With shift()
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
While `pop()` was used to get rid of the last element of an array, `shift()` is used to get rid of the first element. It's like you are shifting the elements down one position. Check this out:
```javascript
var arr = [1, 2, 3, 4, 5];
arr.shift(); // Gets rid of the 1
```

View File

@ -0,0 +1,12 @@
---
title: Manipulate Arrays With unshift()
---
## Manipulate Arrays With unshift()
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
While `push()` added elements to the back of the array, `unshift()` adds them to the front. All you have to do is:
```javascript
var arr = [2, 3, 4, 5];
arr.unshift(1); // Now, the array has 1 in the front
```

View File

@ -0,0 +1,108 @@
---
title: Manipulating Complex Objects
---
## Manipulating Complex Objects
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
Heres the example:
```javascript
var myMusic = [
{
"artist": "Billy Joel",
"title": "Piano Man",
"release_year": 1973,
"formats": [
"CD",
"8T",
"LP"
],
"gold": true
}
// Add record here
];
```
Heres a solution:
After string `// Add record here` we add new album to the `myMusic`. You need to start from `,`. And you can just copy already created album:
```javascript
{
"artist": "Billy Joel",
"title": "Piano Man",
"release_year": 1973,
"formats": [
"CD",
"8T",
"LP"
],
"gold": true
}
```
and paste after `,`:
```javascript
// Add record here
,
{
"artist": "Billy Joel",
"title": "Piano Man",
"release_year": 1973,
"formats": [
"CD",
"8T",
"LP"
],
"gold": true
}
];
```
Now, you can change values your album:
```javascript
// Add record here
,
{
"artist": "Deep Purple",
"title": "Smoke on the water",
"release_year": 1976,
"formats": [
"CD",
"8T",
"LP"
],
"gold": true
}
];
```
Heres a full solution:
```javascript
var myMusic = [
{
"artist": "Billy Joel",
"title": "Piano Man",
"release_year": 1973,
"formats": [
"CD",
"8T",
"LP"
],
"gold": true
},
// Add record here
{
"artist": "Deep Purple",
"title": "Smoke on the water",
"release_year": 1976,
"formats": [
"CD",
"8T",
"LP"
],
}
];
```

View File

@ -0,0 +1,16 @@
---
title: Modify Array Data With Indexes
---
## Modify Array Data With Indexes
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
Access the position of the array, and change it, like so:
```javascript
var arr = [1, 2, 3, 4, 5];
arr[0] = 6; // Now, the array is [6, 2, 3, 4, 5]
arr[4] = 10 // Now, the array is [6, 2, 3, 4, 10]
```
The important concept here is that arrays are **mutable**. This means that they can be changed easily.

View File

@ -0,0 +1,92 @@
---
title: Multiple Identical Options in Switch Statements
---
## Multiple Identical Options in Switch Statements
### Problem Explanation
_If the break statement is omitted from a switch statement's case, the following case statement(s) are executed until a break is encountered. If you have multiple inputs with the same output, you can represent them in a switch statement like this:_
```javascript
switch(val) {
case 1:
case 2:
case 3:
result = "1, 2, or 3";
break;
case 4:
result = "4 alone";
}
```
_Cases for 1, 2, and 3 will all produce the same result._
_Write a switch statement to set answer for the following ranges:_
`1-3`- "Low"
`4-6`- "Mid"
`7-9`- "High"
_Note:
You will need to have a case statement for each number in the range._
## Spoiler alert!
**Solution ahead!**
## Code Solution:
```javascript
function sequentialSizes(val) {
var answer = "";
// Only change code below this line
switch(val) {
case 1:
case 2:
case 3:
return "Low";
break;
case 4:
case 5:
case 6:
return "Mid";
break;
case 7:
case 8:
case 9:
return "High";
break;
}
// Only change code above this line
return answer;
}
// Change this value to test
sequentialSizes(1);
```
## Alternative code solution:
```javascript
function sequentialSizes(val) {
var answer = "";
// Only change code below this line
switch(val){
case 1: case 2: case 3:
answer = "Low";
break;
case 4: case 5: case 6:
answer = "Mid";
break;
case 7: case 8: case 9:
answer = "High";
}
// Only change code above this line
return answer;
}
// Change this value to test
sequentialSizes(1);
```
· Run code at [repl.it](https://repl.it/@AdrianSkar/Basic-JS-Multiple-opts-in-switch).
### Code explanation
Since you already have a variable named `answer` defined and the function returns it, you can just modify its value on each group of case statements to fit the exercise requirements.
### Resources
- ["Switch: Methods for multi-criteria case" - *MDN Javascript Reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch)

View File

@ -0,0 +1,10 @@
---
title: Multiply Two Decimals with JavaScript
---
## Multiply Two Decimals with JavaScript
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/javascript-algorithms-and-data-structures/basic-javascript/multiply-two-decimals-with-javascript/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,9 @@
---
title: Multiply Two Numbers with JavaScript
---
# Multiply Two Numbers with JavaScript
JavaScript uses the `*` symbol for multiplication.
var product = 8 * 10; //product gets the value 80
<!-- 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: Nest one Array within Another Array
---
## Nest one Array within Another Array
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
Arrays are one-dimensional; that means they store only one row of data. But you can make an array multi-dimensional by putting arrays inside arrays! Like so:
```javascript
var arr = [["Two-dimensional", 2], ["Two rows", 12]];
```
The above array has two dimensions.

View File

@ -0,0 +1,101 @@
---
title: Nesting For Loops
---
## Nesting For Loops
<strong>Remember to use Read-Search-Ask if you get stuck. Try to pair program :busts_in_silhouette: and write your own code :pencil:</strong>
:checkered_flag: <strong>Problem Explanation:</strong>
If you have a multi-dimensional array, you can use the same logic as the prior waypoint to loop through both the array and any sub-arrays.
Here is an example:
```
var arr = [
[1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) {
console.log(arr[i][j]);
}
}
```
This outputs each sub-element in <code>arr</code> one at a time. Note that for the inner loop, we are checking the length of arr[i], since arr[i] is itself an array.
<ul>
<li>Modify function <code>multiplyAll</code> so that it multiplies the <code>product</code> variable by each number in the sub-arrays of <code>arr</code>.</li>
<li>Make sure the second for loop is nested inside the first.</li>
</ul>
<strong>Relevant Links</strong>
<ul>
<li><a href="https://guide.freecodecamp.org/certifications/javascript-algorithms-and-data-structures/basic-javascript/nest-one-array-within-another-array">Nest One Array Within Another Array</a></li>
<li><a href="https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/iterate-through-an-array-with-a-for-loop">Iterate Through An Array With A For Loop</a></li>
<li><a href="https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays">Accessing Nested Arrays</a></li>
</ul>
:speech_balloon: Hint: 1
Make sure to check with <code>length</code> and not the overall array.
<em>try to solve the problem now</em>
:speech_balloon: Hint 2<br>
Use both <code>i</code> and <code>j</code> when multiplying the product.
<em>try to solve the problem now</em>
:speech_balloon: Hint 3<br>
Remember to use <code>arr[i]</code> when you multiply the sub-arrays with the <code>product</code> variable.
<em>try to solve the problem now</em>
<em>Spoiler Alert!</em>
<img src="https://discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif">
<br>
<strong>Solution Ahead!</strong>
:beginner: <strong>Basic Code Solution:</strong>
```
function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for(var i=0; i < arr.length; i++){
for (var j=0; j < arr[i].length; j++){
product = product * arr[i][j];
}
}
// Only change code above this line
return product;
}
// Modify values below to test your code
multiplyAll([[1,2],[3,4],[5,6,7]]);
```
:rocket: <strong><a href="https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/nesting-for-loops/">Run Code</a></strong>
<strong>Code Explanation:</strong>
<ul>
<li>We check the length of <code>arr</code> in the <code>i</code> for loop and the <code>arr[i]</code> length in the <code>j</code> for loop.</li>
<li>We multiply the <code>product</code> variable by itself because it equals 1, and then multiply it by the sub-arrays.</li>
<li>The two sub-arrays to multiply are <code>arr[i]</code> and <code>j</code>.</li>
</ul>
:clipboard: <strong>NOTES FOR CONTRIBUTIONS:</strong>
<ul>
<li>:warning: <strong>DO NOT</strong> 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.</li>
<li>Add an explanation of your solution.</li>
<li>Categorize the solution in one of the following categories — Basic, Intermediate and Advanced. :traffic_light:</li>
<li>Please add your username only if you have added any relevant main contents. (:warning: <em><strong>DO NOT</strong></em> remove any existing usernames)</li>
</ul>
See :point_right: <a href="http://forum.freecodecamp.com/t/algorithm-article-template/14272"> Wiki Challenge Solution Template</a> for reference.

View File

@ -0,0 +1,19 @@
---
title: Passing Values to Functions with Arguments
---
## Passing Values to Functions with Arguments
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
Our task is to create a function that has **parameters**. These are inputs that determine the function's output. You place paramaters inside the `()`, like so:
```javascript
function functionWithArgs(one, two) {
console.log(one + two);
}
```
We now have to add code inside the brackets. Our task is to add `one` and `two`, and print the sum to the console. Here is the basic code solution:
```javascript
functionWithArgs(7, 3);
//This will console log 10.
```

View File

@ -0,0 +1,43 @@
---
title: Practice comparing different values
---
## Practice comparing different values
### Problem explanation:
· _Modify the function so that it returns "Equal" only when the values are **strictly** equal._
#### Hint 1
Remember from last exercises that _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="#cite1">1</a></sup>
> _try to solve the problem now_
>
## Spoiler alert!
**Solution ahead!**
## Basic code solution:
```javascript
// Setup
function compareEquality(a, b) {
if (a === b) { // Change this line
return "Equal";
}
return "Not Equal";
}
// Change this value to test
compareEquality(10, "10");
```
### Code explanation
The function first evaluates `if` the condition `(a === b)` evaluates to `true` considering both type and value. 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 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
- ["Using the Equality Operators" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Using_the_Equality_Operators)

View File

@ -0,0 +1,111 @@
---
title: Profile Lookup
---
## Profile Lookup
![: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 `Read-Search-Ask` 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 an array of objects representing different people in our contacts lists.
A `lookUpProfile()` function that takes **firstName** and a property (**prop**) as arguments has been pre-written for you.
The function should check if **firstName** is an actual contact's **firstName** and the given property (**prop**) is a property of that contact.
If both are true, then return the _value_ of that property.
If **firstName** does not correspond to any contacts then return `No such contact`.
If **prop** does not correspond to any valid properties then return `No such property`.
* 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 `lookUpProfile()` function.
* This function includes two parameters, **firstName** and **prop**.
* The function should look through the **contacts** list for the given **firstName** parameter.
* If there is a match found, the function should then look for the given **prop** parameter.
* If both **firstName** and the associated **prop** are found, you should return the value of the **prop**.
* If **firstName** is found and no associated **prop** is found, you should return `No such property`.
* If **firstName** isn't found anywhere, you should return `No such contact`.
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
Use a `for` loop to cycle through the **contacts** list.
> _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
Use a nested `if` statement to first check if the **firstName** matches, and then checks `if` the **prop** matches.
> _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
Leave your `return "No such contact"` out of the `for` loop as a final catch-all.
> _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
for (var x = 0; x < contacts.length; x++){
if (contacts[x].firstName === name) {
if (contacts[x].hasOwnProperty(prop)) {
return contacts[x][prop];
} else {
return "No such property";
}
}
}
return "No such contact";
```
### Code Explanation:
* The `for` loop runs, starting at the first object in the **contacts** list.
* If the **firstName** parameter passed into the function matches the value of the `"firstName"` key in the first object, the `if` statement passes.
* Then, we use `.hasOwnProperty()` method (checks if there's a given property and returns a boolean) with **prop** as an argument. If it's true, the value of **prop** is returned.
* If the second `if` statement fails, `No such property` is returned.
* If the first `if` statement fails, the `for` loop continues on to the next object in the **contacts** list.
* If the **firstName** parameter isn't matched by the final **contacts** object, the `for` loop exits and `No such contact` is returned.
**Example Run**
* `lookUpProfile("Akira","likes");` runs.
* `"Akira"` is matched to the `"firstName"` key in the first object, so the `if` statement returns true.
* `"likes"` is found within the first object, so the second `if` statement returns true.
* The value of `"likes"` is returned - `"Pizza", "Coding", "Brownie Points"`.
## Alternative code solution:
```javascript
for (var i = 0; i < contacts.length; i++){
if (contacts[i].firstName === name){
if (prop in contacts[i]){
return contacts[i][prop];
}
else return "No such property";
}
}
return "No such contact";
}
```
· Run code at [repl.it](https://repl.it/@AdrianSkar/Basic-JS-Profile-lookup).
### Code explanation
This works as the last example but uses the `in` operator to look for `prop` instead of the `hasOwnProperty()` method.
### Resources
- ["Iterate with JavaScript For Loops" - *fCC's challenge*](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-for-loops/)
- ["Object.prototype.hasOwnProperty()" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty)
- ["in operator" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in)

View File

@ -0,0 +1,10 @@
---
title: Quoting Strings with Single Quotes
---
## Quoting Strings with Single Quotes
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/javascript-algorithms-and-data-structures/basic-javascript/quoting-strings-with-single-quotes/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,96 @@
---
title: Record Collection
---
![: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 are given a JSON object representing (a small part of) your record collection. Each album is identified by a unique id number and has several properties. Not all albums have complete information.
Write a function which takes an **id**, a property (**prop**), and a **value**.
For the given **id** in **collection**:
If **value** is non-blank (**value !== ""**), then update or set the **value** for the **prop**.
If the **prop** is **"tracks"** and **value** is non-blank, check to see if the given element in the array has the property of "tracks". If the element has the property of "tracks", push the **value** onto the end of the "tracks" array. If the element does not have the **property**, create the property and value pair.
If **value** is blank, delete that **prop**.
Always return the entire collection object.
* Change the code below `// Only change code below this line` and up to `// Alter values below to test your code`.
* Take note that you are editing the inside of the `updateRecords` function.
* For the given **id** parameter, which is associated to the **collection** object:
* If the **value** parameter isn't an empty string, update (or set) the **value** parameter for the **prop** parameter.
* If the **prop** parameter is equal to `"tracks"` and the **value** isn't an empty string, push the **value** onto the end of the **tracks** array.
* If **value** is an empty string, delete that **prop** from the object.
* Finally, return the **collection** object.
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
Use an `else if` statement to check the needed steps.
> _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
The second step listed in the instructions should be first in your `else if` statement.
> _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
To access the value of a key in this object, you will use `collection[id][prop]`.
> _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 updateRecords(id, prop, value) {
if (prop === "tracks" && value !== "") {
if(collection[id][prop]) {
collection[id][prop].push(value);
}
else {
collection[id][prop]=[value];
}
} else if (value !== "") {
collection[id][prop] = value;
} else {
delete collection[id][prop];
}
return collection;
}
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/C2AZ/0' target='_blank' rel='nofollow'>Run Code</a>
### Code Explanation:
* First checks if **prop** is equal to **tracks** AND if **value** isn't a blank string. If both tests pass, **value** is pushed into the **tracks** array.
* If that first check doesn't pass, it next checks only if **value** isn't a blank string. If that test passes, either a new key (**prop**) and value (**value**) are added to the object, or an existing key is updated if the **prop** already exists.
* If both these checks fail (meaning **value** must be an empty string), then the key (**prop**) is removed from the object.
**Example Run**
* `updateRecords(5439, "artist", "ABBA");` runs.
* **prop** is equal to "artist", not "tracks", so the first part of the `else if` statement fails.
* **value** is not a blank string, so the second part of the else if statement passes.
* `artist: "ABBA"` is added to the `5439` `id`.
### Resources:
* [fCC's challenge: Accessing Objects Properties with Bracket Notation](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-bracket-notation/)
* [fCC's challenge: Add New Properties to a JavaScript Object](http://www.freecodecamp.com/challenges/add-new-properties-to-a-javascript-object)
* [fCC's challenge: Delete Properties from a JavaScript Object](http://www.freecodecamp.com/challenges/delete-properties-from-a-javascript-object)
* [fCC's challenge: Accessing Nested Objects](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-objects/)
* ["Array.prototype.push()" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push)
* ["delete operator" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete)

View File

@ -0,0 +1,116 @@
## Replacing If Else Chains with Switch
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
Heres the setup:
```javascript
function chainToSwitch(val) {
var answer = "";
// Only change code below this line
switch(val) {
case "bob":
answer = "Marley";
break;
case 42:
answer = "The Answer";
break;
case 1:
answer = "There is no #1";
break;
case 99:
answer = "Missed me by this much!";
break;
case 7:
answer = "Ate Nine";
break;
}
// Only change code above this line
return answer;
}
// Change this value to test
chainToSwitch(7);
```
We need to change the chained ```if/else if``` statements into a ```switch``` statement.
Heres a solution:
Now, we need to comment (```//``` - select all lines and ```ctrl+/```) all chained ```if/else if``` statements:
```javascript
// if (val === "bob") {
// answer = "Marley";
// } else if (val === 42) {
// answer = "The Answer";
// } else if (val === 1) {
// answer = "There is no #1";
// } else if (val === 99) {
// answer = "Missed me by this much!";
// } else if (val === 7) {
// answer = "Ate Nine";
// }
```
Next, we need to create simple ```switch``` statement:
```javascript
switch(val) {
}
```
and add in this ```switch``` statement ```case``` - for all ```if/else if``` statement (just copy it from our commented code above):
```javascript
switch(val) {
case "bob":
answer = "Marley";
break;
case 42:
answer = "The Answer";
break;
case 1:
answer = "There is no #1";
break;
case 99:
answer = "Missed me by this much!";
break;
case 7:
answer = "Ate Nine";
break;
}
```
Dont forget to use ```break``` in each ```case```!
Now, we can delete commented code with ```if/else if``` statement above.
Heres a full solution:
```javascript
function chainToSwitch(val) {
var answer = "";
// Only change code below this line
switch(val) {
case "bob":
answer = "Marley";
break;
case 42:
answer = "The Answer";
break;
case 1:
answer = "There is no #1";
break;
case 99:
answer = "Missed me by this much!";
break;
case 7:
answer = "Ate Nine";
break;
}
// Only change code above this line
return answer;
}
// Change this value to test
chainToSwitch(7);
```

View File

@ -0,0 +1,13 @@
---
title: Return a Value from a Function with Return
---
## Return a Value from a Function with Return
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
Using `return`, you can make functions output data. Here is the basic code solution:
```javascript
function timesFive(num) {
return num * 5;
}
```

View File

@ -0,0 +1,54 @@
## Return Early Pattern for Functions
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
Heres a setup:
```javascript
// Setup
function abTest(a, b) {
// Only change code below this line
// Only change code above this line
return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
}
// Change values below to test your code
abTest(2,2);
```
We need to modify the function ```abTest``` so that if ```a``` or ```b``` are less than ```0``` the function will immediately exit with a value of ```undefined```.
We add in body of function simple ```if``` statement, which, under the conditions "if ```a``` or ```b``` are less than ```0``` - immediately exit with a value of ```undefined```":
```javascript
if (a < 0 || b < 0) {
return undefined;
}
```
Now, if ```a``` or ```b``` are less than ```0``` - function exit with a value of ```undefined```, in other cases -
```javascript
return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
}
```
Heres a full solution:
```javascript
// Setup
function abTest(a, b) {
// Only change code below this line
if (a < 0 || b < 0) {
return undefined;
}
// Only change code above this line
return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
}
// Change values below to test your code
abTest(2,2);
```

View File

@ -0,0 +1,44 @@
---
title: Returning Boolean Values from Functions
---
## Returning Boolean Values from Functions
Instead of using an if/else block to compare variable we can do it right inside the return statement with a comparison operator and minmal code.
### Problem explanation
_Fix the function `isLess` to remove the `if...else` statements._
```js
// Fix this code
if (a < b) {
return true;
} else {
return false;
}
```
#### Hint 1
As with the [previous exercise](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/replacing-if-else-chains-with-switch) you are about to change how the function returns the correct value, meaning you don't have to reuse or modify that code but to substitute it.
> _try to solve the problem now_
#### Hint 2
In order to return `true` or `false` you don't need two statements nor use `if` ones. The correct [comparison operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators) is all you need.
> _try to solve the problem now_
## Spoiler alert!
**Solution ahead!**
## Code Solution:
```javascript
function isLess(a, b) {
// Fix this code
return a <= b;
}
// Change these values to test
isLess(10, 15);
```
Run code at [repl.it](https://repl.it/@AdrianSkar/Basic-Js-Returning-boolean-from-function).
### Resources
- ["Less than or equal operator (<=)" - *MDN Javascript Reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Less_than_or_equal_operator_(%3C))

View File

@ -0,0 +1,115 @@
---
title: Selecting from Many Options with Switch Statements
---
## Selecting from Many Options with Switch Statements
_If you have many options to choose from, use a `switch` statement. A `switch` statement tests a value and can have many `case` statements which define various possible values. Statements are executed from the first matched `case` value until a `break` is encountered._
_Here is a pseudocode example:_
```js
switch(num) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
case valueN:
statementN;
break;
}
```
### A bit more explanation
A switch statement first evaluates its expression. It then looks for the first `case` clause whose expression evaluates to the same value as the result of the input expression (using the [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators), (`===`) and transfers control to that clause, executing the associated statements. (If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.)
If no matching `case` clause is found, the program looks for the optional `default` clause, and if found, transfers control to that clause, executing the associated statements. If no `default` clause is found, the program continues execution at the statement following the end of `switch`. By convention, the `default` clause is the last clause, but it does not need to be so.
The optional `break` statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If `break` is omitted, the program continues execution at the next statement in the `switch` statement.<sup><a href="#cite1">1</a></sup>
### Problem Explanation:
_Write a switch statement which tests `val` and sets `answer` for the following conditions:_
- `1` - "alpha",
- `2` - "beta",
- `3` - "gamma",
- `4` - "delta".
## Hint 1
Remember that `case` values are tested with strict equality (`===`).
> Try to solve the problem now!
## Hint 2
Do not see _"following conditions"_ as an ordered list as it looks in the original freeCodeCamp demo, but as values and statements, as shown here
>Try to solve the problem now!
## Spoiler Alert!
### Are you completely sure what you want a look? ...
## Basic Code Solution
```js
function caseInSwitch(val) {
var answer = "";
// Only change code below this line
switch(val) {
case 1:
return "alpha";
break;
case 2:
return "beta";
break;
case 3:
return "gamma";
break;
case 4:
return "delta";
break;
}
// Only change code above this line
return answer;
}
// Change this value to test
caseInSwitch(1);
```
### Code Explanation
It is common to ignore that `case` values are tested with strict equality with any need of other expression, like so:
`case === value`
## Alternative code solution:
```javascript
function caseInSwitch(val) {
var answer = "";
// Only change code below this line
switch (val){
case 1:
answer="alpha";
break;
case 2:
answer="beta";
break;
case 3:
answer="gamma";
break;
case 4:
answer="delta";
break;
}
// Only change code above this line
return answer;
}
// Change this value to test
caseInSwitch(1);
```
· Run code at [repl.it](https://repl.it/@AdrianSkar/Basic-JS-Switch-statements).
### Code explanation
Since you already have a variable defined at the beginning of the function named `answer` and it's defined as the last return statement, you can assign new values to it for each case and will return the expected answer depending on the value you pass to the function.
### Sources
<span id="cite1">1</span>. [Description of "switch" - *MDN JavaScript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch#Description).

View File

@ -0,0 +1,63 @@
---
title: Shopping List
---
![: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:
Create a shopping list in the variable **myList**. The list should be a multi-dimensional array containing several sub-arrays.
The first element in each sub-array should contain a string with the name of the item. The second element should be a number representing the quantity i.e. `["Chocolate Bar", 15]`.
There should be at least 5 sub-arrays in the list.
* **myList** should be an array.
* The first elements in each of your sub-arrays must all be strings.
* The second elements in each of your sub-arrays must all be numbers.
* You must have at least 5 items in your list.
#### Relevant Links
* <a href='https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/nest-one-array-within-another-array/' target='_blank' rel='nofollow'>Challenge:Nest one Array within Another Array</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
A multi-dimensional array would have the following outline `[[]]`.
> _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
Each sub-array should be separated by `,` as would any item in an 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: 3
Don't forget the `;` at the end of your declaration.
> _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:
var myList = [["Canned Beans", 3],["Milk Galon", 1],["Cereal", 2],["Toilet Paper", 12],["Sack of Rice", 1]];
### Code Explanation:
* A multi-dimensional array is created.
* The array consists five arrays inside, each composed of a string and an integer, in the same order.
## ![: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,73 @@
---
title: Stand in Line
---
![: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 Computer Science a _queue_ is an abstract **data structure** where items are kept in order. New items can be added at the back of the **queue** and old items are taken off from the front of the **queue**.
Write a function `nextInLine` which takes an array (**arr**) and a number (**item**) as arguments. Add the number to the end of the array, then remove the first element of array. The `nextInLine` function should then return the element that was removed.
* Change the code below `//Your Code here` and up to `//Change this line`.
* Ensure that you are editing the inside of the `nextInLine` function.
* Use an array function you learned to add the **item** to the end of the array **arr**.
* Use an array function you learned to remove the first element from array **arr**.
* Return the element removed.
#### Relevant Links
* <a href='http://www.freecodecamp.com/challenges/manipulate-arrays-with-push' target='_blank' rel='nofollow'>Challenge: Manipulate Arrays With push()</a>
* <a href='http://www.freecodecamp.com/challenges/manipulate-arrays-with-shift' target='_blank' rel='nofollow'>Challenge: Manipulate Arrays With shift()</a>
* <a href='http://www.freecodecamp.com/challenges/passing-values-to-functions-with-arguments' target='_blank' rel='nofollow'>Challenge: Passing Values to Functions with Arguments</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
The `push()` method adds an item to the end of an 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
The `shift()` method removes the first element of an array. It also returns the element removed.
> _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
The function `nextInLine` uses **arr** and **item**. Those are what the tests will use to pass the array elements they will test with. It allows the function to be reusable. Do not hardcode any of the tests inside the function.
> _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 nextInLine(arr, item) {
// Your code here
arr.push(item);
var removed = arr.shift();
return removed; // Change this line
}
### Code Explanation:
* Push **item** at the end of **arr**.
* Call the `shift()` method on **arr** to get the first item and store it in **removed**.
* Return **removed**.
**Example Run**
* Test `nextInLine([2,1]);` runs.
* The `nextInLine` function is called. **arr** becomes [2]. **item** becomes 1.
* `arr.push(item);` Pushes 1 to [2]. So **arr** is now [2,1].
* `var removed = arr.shift();` removes the first element. So **arr** is now [1]. 2 has been removed and is stored in **removed**.
* `return removed;` 2 is returned.
**_Note_**: You don't actually need the variable **removed**. The element removed can be returned directly using `return arr.shift();`.

View File

@ -0,0 +1,17 @@
---
title: Store Multiple Values in one Variable using JavaScript Arrays
---
## Store Multiple Values in one Variable using JavaScript Arrays
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
Arrays allow you to store lots of different data, within a single variable. All you have to do is put the data in the array, seperated by commas. Like so...
```javascript
var arr = ["Code for change", 123];
```
Remember, an array is defined as a row of things. You're storing different data in a single 'row' (variable).
Check this link out if you need more help:
[JavaScript Arrays on W3 Schools](https://www.w3schools.com/js/js_arrays.asp)

View File

@ -0,0 +1,13 @@
---
title: Storing Values with the Assignment Operator
---
## Storing Values with the Assignment Operator
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
It's just like math! You can set a variable to act as a placeholder for data by using the '=' assignment operator. In other words, the variable will store the data.
var a;
a = 5; // The variable 'a' is equal to 5
var zxcv;
zxcv = 123; // The variable 'abc' is equal to 123

View File

@ -0,0 +1,10 @@
---
title: Subtract One Number from Another with JavaScript
---
## Subtract One Number from Another with JavaScript
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
Using the '-' subtraction operator, you can get the difference of two numbers...
var diff1 = 30 - 14; // Difference is 16
var diff2 = 90 - 60; // Difference is 30

View File

@ -0,0 +1,79 @@
---
title: Testing Objects for Properties
---
## Testing Objects for Properties
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
Heres the example:
```javascript
// Setup
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};
function checkObj(checkProp) {
// Your Code Here
return "Change Me!";
}
// Test your code by modifying these values
checkObj("gift");
```
Heres a solution:
We do not change anything here:
```javascript
// Setup
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};
```
further, in the body of the function we use `.hasOwnProperty(propname)` method of objects to determine if that object has the given property name. `if/else` statement with Boolean Values will help us in this:
```javascript
function checkObj(checkProp) {
// Your Code Here
if (myObj.hasOwnProperty(checkProp) == true) {
return myObj[checkProp];
}
else {
```
and change the value of `return` in `else` statement:
```javascript
return "Not Found"
}
}
```
Now, you can change `checkObj` values:
```javascript
// Test your code by modifying these values
checkObj("gift");
```
Heres a full solution:
```javascript
function checkObj(checkProp) {
// Your Code Here
if (myObj.hasOwnProperty(checkProp) == true) {
return myObj[checkProp];
}
else {
return "Not Found"
}
}
// Test your code by modifying these values
checkObj("gift");
```

View File

@ -0,0 +1,10 @@
---
title: Understand String Immutability
---
## Understand String Immutability
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/javascript-algorithms-and-data-structures/basic-javascript/understand-string-immutability/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: Understanding Boolean values
---
## Understanding Boolean values
### Problem explanation:
Modify the `welcomeToBooleans` function so that it returns `true` instead of `false` when the run button is clicked.
### Hint 1
You just need to edit line 5 so the function returns `true` instead of `false`.
> _try to solve the problem now_
## Spoiler Alert!
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic code solution:
```javascript
function welcomeToBooleans() {
// Only change code below this line.
return true; // Change this line
// Only change code above this line.
}
```
### Code explanation
Just modifying the `Boolean` value you wan't the function to return from `false` to `true` will meet the requirements.
### Resources
[MDN glossary - Boolean](https://developer.mozilla.org/en-US/docs/Glossary/Boolean)
[Wikipedia - Boolean data type](https://en.wikipedia.org/wiki/Boolean_data_type)

View File

@ -0,0 +1,11 @@
---
title: Understanding Case Sensitivity in Variables
---
## Understanding Case Sensitivity in Variables
A popular programming norm is to use <strong>Camel case</strong> when creating variable names. Notice the first word is lowercase and every following word is uppercase. Here are some examples:
var camelCase;
var someNumber;
var theBestVariableEver;
var weWillStoreNumbersInThisVariable;

View File

@ -0,0 +1,20 @@
---
title: Understanding Undefined Value returned from a Function
---
## Understanding Undefined Value returned from a Function
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
A function with no `return` statement, has an output of `undefined`. So, if you try to equal a varaible to the output of a function with no `return` statement, that variable will equal `undefined`.
Go ahead and define `addFive()` like so...
```javascript
function addFive() {
sum += 5;
}
```
As you can see, `sum` is added by 5 with no issues, but since there is no return statement, there is an `undefined` output.
```javascript
var result = addFive(); // This is undefined
```

View File

@ -0,0 +1,7 @@
---
title: Understanding Uninitialized Variables
---
## Understanding Uninitialized Variables
Make sure that the variable has the correct data value. Leaving a variable uninitialized, meaning you do not give it a value, can cause problems if you want to do operations on it.

View File

@ -0,0 +1,26 @@
---
title: Updating Object Properties
---
## Updating Object Properties
## Hint:
Use dot ** . ** notation to access the object property.
## Spoiler Alert: Solution Ahead!
## Solution:
```javascript
// Setup
var myDog = {
"name": "Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"]
};
// Only change code below this line.
myDog.name = "Happy Coder"; // Solution
```

View File

@ -0,0 +1,12 @@
---
title: Use Bracket Notation to Find the First Character in a String
---
## Use Bracket Notation to Find the First Character in a String
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
Remember that the first character of a string is at the zero-th position. For example:
var str = "Hello";
var letter = str[0]; // This equals "H"

View File

@ -0,0 +1,17 @@
---
title: Use Bracket Notation to Find the Last Character in a String
---
## Use Bracket Notation to Find the Last Character in a String
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
Consider the following string:
var str = "Coding";
This string has a length of 6 characters, so if you use .length on the string, it will give you 6. But remember that the first character is at the zero-th position. The second character is at the first position. The third character is at the second position.
Keep on going, and you eventually get that the sixth character (which, based on the above string, is 'g') is at the fifth position. That's why you obtain the last character of a string, with:
var lastChar = str[str.length - 1]; // This is 6 - 1, which is 5
This will be 'g'.

View File

@ -0,0 +1,8 @@
---
title: Use Bracket Notation to Find the Nth Character in a String
---
## Use Bracket Notation to Find the Nth Character in a String
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
Remember that the first character of a string is at the 0-th position. So the second character should be at the 1st position. Then the third character, should be in the...hmmm?

View File

@ -0,0 +1,12 @@
---
title: Use Bracket Notation to Find the Nth-to-Last Character in a String
---
## Use Bracket Notation to Find the Nth-to-Last Character in a String
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
Remember that the position of any character, is the <strong>length of the string, minus one, minus the number of characters after it</strong>. For example, if you are trying to find the third-to-last character of the following string:
var str = "Programming";
var secondToLastChar = str[str.length - 2]; // This is 'i'
As you can see, there is one extra character after 'n' (and that is 'g').

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