freeCodeCamp/seed/challenges/01-front-end-development-ce.../basic-javascript.json

5427 lines
284 KiB
JSON
Raw Blame History

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

{
"name": "Basic JavaScript",
"time": "10 hours",
"order": 6,
"helpRoom": "HelpJavaScript",
"challenges": [
{
"id": "bd7123c9c441eddfaeb4bdef",
"title": "Comment your JavaScript Code",
"description": [
"Comments are lines of code that JavaScript will intentionally ignore. Comments are a great way to leave notes to yourself and to other people who will later need to figure out what that code does.",
"There are two ways to write comments in JavaScript:",
"Using <code>//</code> will tell JavaScript to ignore the remainder of the text on the current line:",
"<blockquote>// This is an in-line comment.</blockquote>",
"You can make a multi-line comment beginning with <code>/*</code> and ending with <code>*/</code>:",
"<blockquote>/* This is a <br> multi-line comment */</blockquote>",
"<strong>Best Practice</strong><br>As you write code, you should regularly add comments to clarify the function of parts of your code. Good commenting can help communicate the intent of your code&mdash;both for others <em>and</em> for your future self.",
"<h4>Instructions</h4>",
"Try creating one of each type of comment."
],
"challengeSeed": [
""
],
"solutions": [
"// Fake Comment\n/* Another Comment */"
],
"tests": [
"assert(code.match(/(\\/\\/)...../g), 'message: Create a <code>//</code> style comment that contains at least five letters.');",
"assert(code.match(/(\\/\\*)[\\w\\W]{5,}(?=\\*\\/)/gm), 'message: Create a <code>/* */</code> style comment that contains at least five letters.');",
"assert(code.match(/(\\*\\/)/g), 'message: Make sure that you close the comment with a <code>*/</code>.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Agrega comentarios a tu código JavaScript",
"descriptionEs": [
"Los comentarios son líneas de código que el computador ignorará intencionalmente. Los comentarios son una gran forma de dejarte notas a ti mismo y a otras personas que luego tendrán que averiguar lo que hace que el código. ",
"Vamos a echar un vistazo a las dos maneras en las que puedes agregar tus comentarios en JavaScript.",
"El comentario de doble barra comentará el resto del texto en la línea donde se ubica:",
"<code>// Este es un comentario.</code>",
"El comentario de barra-estrella-estrella-barra, comentará todo lo que haya entre los caracteres <code>/*</code> y <code>*/</code>:",
"<code>/* Este es también un comentario */</code>",
"Trata de crear uno de cada uno."
]
},
{
"id": "bd7123c9c443eddfaeb5bdef",
"title": "Declare JavaScript Variables",
"description": [
"In computer science, <code>data</code> is anything that is meaningful to the computer. JavaScript provides seven different <dfn>data types</dfn> which are <code>undefined</code>, <code>null</code>, <code>Boolean</code>, <code>string</code>, <code>symbol</code>, <code>number</code>, and <code>object</code>.",
"For example, computers distinguish between numbers, such as the number <code>12</code>, and <code>strings</code>, such as <code>\"12\"</code>, <code>\"dog\"</code>, or <code>\"123 cats\"</code>, which are collections of characters. Computers can perform mathematical operations on a number, but not on a string.",
"<code>Variables</code> allow computers to store data in a dynamic fashion, rather than updating a formula every time the data changes. Any of the seven different data types may be stored in a variable.",
"<code>Variables</code> are similar to the x and y variables you use in mathematics, which means they're a simple name to represent the data we want to refer to. Computer <code>variables</code> differ from mathematical variables in that they can store different values at different times.",
"We tell JavaScript to create or <dfn>declare</dfn> a variable by putting the keyword <code>var</code> in front of it, like so:",
"<blockquote>var ourName;</blockquote>",
"creates a <code>variable</code> called <code>ourName</code>. In JavaScript we end statements with semicolons.",
"<code>Variable</code> names can be made up of numbers, letters, and <code>$</code> or <code>_</code>, but may not contain spaces or start with a number.",
"<h4>Instructions</h4>",
"Use the <code>var</code> keyword to create a variable called <code>myName</code>.",
"<strong>Hint</strong><br>Look at the <code>ourName</code> example if you get stuck."
],
"challengeSeed": [
"// Example",
"var ourName;",
"",
"// Define myName below this line",
""
],
"tail": [
"if(typeof myName !== \"undefined\"){(function(v){return v;})(myName);}"
],
"solutions": [
"var myName;"
],
"tests": [
"assert(/var\\s+myName\\s*;/.test(code), 'message: You should declare <code>myName</code> with the <code>var</code> keyword, ending with a semicolon');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Declara variables en JavaScript",
"descriptionEs": [
"Cuando almacenamos datos en una <code>estructura de datos</code>, la llamamos una <code>variable</code>. Estas variables no son diferentes de las variables x e y que utilizas en matemáticas. ",
"Vamos a crear nuestra primera variable y a llamarla \"myName\".",
"Te darás cuenta que en <code>myName</code>, no usamos un espacio, y que la \" N\"se escribe con mayúscula. Las variables en JavaScript se escriben con <code>capitalización camello (camel case)</code>. Un ejemplo de capitalización camello: capitalizacionCamello.",
"Ahora, utiliza la palabra clave <code>var</code> para crear una variable llamada <code>myName</code>. Establecele como valor tu nombre, entre comillas dobles. ",
"Mira el ejemplo con <code>ourName</code> si te quedas atascado."
]
},
{
"id": "56533eb9ac21ba0edf2244a8",
"title": "Storing Values with the Equal Operator",
"description": [
"In JavaScript, you can store a value in a variable with the <dfn>assignment</dfn> or <code>equal</code> (<code>=</code>) operator.",
"<code>myVariable = 5;</code>",
"Assigns the <code>Number</code> value <code>5</code> to <code>myVariable</code>.",
"Assignment always goes from right to left. Everything to the right of the <code>=</code> operator is resolved before the value is assigned to the variable to the left of the operator.",
"<blockquote>myVar = 5;<br>myNum = myVar;</blockquote>",
"Assigns <code>5</code> to <code>myVar</code> and then resolves <code>myVar</code> to <code>5</code> again and assigns it to <code>myNum</code>.",
"<h4>Instructions</h4>",
"Assign the value <code>7</code> to variable <code>a</code>.",
"Assign the contents of <code>a</code> to variable <code>b</code>."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Setup",
"var a;",
"var b = 2;",
"",
"// Only change code below this line",
""
],
"tail": [
"(function(a,b){return \"a = \" + a + \", b = \" + b;})(a,b);"
],
"solutions": [
"var a;\nvar b = 2;\na = 7;\nb = a;"
],
"tests": [
"assert(/var a;/.test(code) && /var b = 2;/.test(code), 'message: Do not change code above the line');",
"assert(typeof a === 'number' && a === 7, 'message: <code>a</code> should have a value of 7');",
"assert(typeof b === 'number' && b === 7, 'message: <code>b</code> should have a value of 7');",
"assert(/b\\s*=\\s*a\\s*;/g.test(code), 'message: <code>a</code> should be assigned to <code>b</code> with <code>=</code>');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244a9",
"title": "Initializing Variables with the Equal Operator",
"description": [
"It is common to <dfn>initialize</dfn> a variable to an initial value in the same line as it is declared.",
"<code>var myVar = 0;</code>",
"Creates a new variable called <code>myVar</code> and assigns it an initial value of <code>0</code>.",
"<h4>Instructions</h4>",
"Define a variable <code>a</code> with <code>var</code> and initialize it to a value of <code>9</code>."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Example",
"var ourVar = 19;",
"",
"// Only change code below this line",
""
],
"tail": [
"if(typeof a !== 'undefined') {(function(a){return \"a = \" + a;})(a);} else { (function() {return 'a is undefined';})(); }"
],
"solutions": [
"var a = 9;"
],
"tests": [
"assert(/var\\s+a\\s*=\\s*9\\s*/.test(code), 'message: Initialize <code>a</code> to a value of <code>9</code>');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244aa",
"title": "Understanding Uninitialized Variables",
"description": [
"When JavaScript variables are declared, they have an initial value of <code>undefined</code>. If you do a mathematical operation on an <code>undefined</code> variable your result will be <code>NaN</code> which means <dfn>\"Not a Number\"</dfn>. If you concatenate a string with an <code>undefined</code> variable, you will get a literal <dfn>string</dfn> of <code>\"undefined\"</code>.",
"<h4>Instructions</h4>",
"Initialize the three variables <code>a</code>, <code>b</code>, and <code>c</code> with <code>5</code>, <code>10</code>, and <code>\"I am a\"</code> respectively so that they will not be <code>undefined</code>."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Initialize these three variables",
"var a;",
"var b;",
"var c;",
"",
"// Do not change code below this line",
"",
"a = a + 1;",
"b = b + 5;",
"c = c + \" String!\";",
""
],
"tail": [
"(function(a,b,c){ return \"a = \" + a + \", b = \" + b + \", c = '\" + c + \"'\"; })(a,b,c);"
],
"solutions": [
"var a = 5;\nvar b = 10;\nvar c = \"I am a\";\na = a + 1;\nb = b + 5;\nc = c + \" String!\";"
],
"tests": [
"assert(typeof a === 'number' && a === 6, 'message: <code>a</code> should be defined and have a value of <code>6</code>');",
"assert(typeof b === 'number' && b === 15, 'message: <code>b</code> should be defined and have a value of <code>15</code>');",
"assert(!/undefined/.test(c) && c === \"I am a String!\", 'message: <code>c</code> should not contain <code>undefined</code> and should have a value of \"I am a String!\"');",
"assert(/a = a \\+ 1;/.test(code) && /b = b \\+ 5;/.test(code) && /c = c \\+ \" String!\";/.test(code), 'message: Do not change code below the line');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244ab",
"title": "Understanding Case Sensitivity in Variables",
"description": [
"In JavaScript all variables and function names are case sensitive. This means that capitalization matters.",
"<code>MYVAR</code> is not the same as <code>MyVar</code> nor <code>myvar</code>. It is possible to have multiple distinct variables with the same name but different casing. It is strongly recommended that for the sake of clarity, you <em>do not</em> use this language feature.",
"<h4>Best Practice</h4>",
"Write variable names in Javascript in <dfn>camelCase</dfn>. In <dfn>camelCase</dfn>, multi-word variable names have the first word in lowercase and the first letter of each subsequent word is capitalized.",
"<strong>Examples:</strong>",
"<blockquote>var someVariable;<br>var anotherVariableName;<br>var thisVariableNameIsTooLong;</blockquote>",
"<h4>Instructions</h4>",
"Fix the variable declarations and assignments so their names use <dfn>camelCase</dfn>."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Declarations",
"var StUdLyCapVaR;",
"var properCamelCase;",
"var TitleCaseOver;",
"",
"// Assignments",
"STUDLYCAPVAR = 10;",
"PRoperCAmelCAse = \"A String\";",
"tITLEcASEoVER = 9000;"
],
"solutions": [
"var studlyCapVar;\nvar properCamelCase;\nvar titleCaseOver;\n\nstudlyCapVar = 10;\nproperCamelCase = \"A String\";\ntitleCaseOver = 9000;"
],
"tests": [
"assert(typeof studlyCapVar !== 'undefined' && studlyCapVar === 10, 'message: <code>studlyCapVar</code> is defined and has a value of <code>10</code>');",
"assert(typeof properCamelCase !== 'undefined' && properCamelCase === \"A String\", 'message: <code>properCamelCase</code> is defined and has a value of <code>\"A String\"</code>');",
"assert(typeof titleCaseOver !== 'undefined' && titleCaseOver === 9000, 'message: <code>titleCaseOver</code> is defined and has a value of <code>9000</code>');",
"assert(code.match(/studlyCapVar/g).length === 2, 'message: <code>studlyCapVar</code> should use camelCase in both declaration and assignment sections.');",
"assert(code.match(/properCamelCase/g).length === 2, 'message: <code>properCamelCase</code> should use camelCase in both declaration and assignment sections.');",
"assert(code.match(/titleCaseOver/g).length === 2, 'message: <code>titleCaseOver</code> should use camelCase in both declaration and assignment sections.');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "cf1111c1c11feddfaeb3bdef",
"title": "Add Two Numbers with JavaScript",
"description": [
"<code>Number</code> is a data type in JavaScript which represents numeric data.",
"Now let's try to add two numbers using JavaScript.",
"JavaScript uses the <code>+</code> symbol as addition operation when placed between two numbers.",
"",
"<strong>Example</strong>",
"<blockquote>myVar = 5 + 10; // assigned 15</blockquote>",
"",
"<h4>Instructions</h4>",
"Change the <code>0</code> so that sum will equal <code>20</code>."
],
"challengeSeed": [
"var sum = 10 + 0;",
""
],
"tail": [
"(function(z){return 'sum='+z;})(sum);"
],
"solutions": [
"var sum = 10 + 10;"
],
"tests": [
"assert(sum === 20, 'message: <code>sum</code> should equal <code>20</code>');",
"assert(/\\+/.test(code), 'message: Use the <code>+</code> operator');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Suma dos números con JavaScript",
"descriptionEs": [
"Intentemos sumar dos números con JavaScript.",
"JavaScript utiliza el símbolo <code>+</code> para la adición.",
"Cambie el <code>0</code> para que la suma seá igual a <code>20</code>."
]
},
{
"id": "cf1111c1c11feddfaeb4bdef",
"title": "Subtract One Number from Another with JavaScript",
"description": [
"We can also subtract one number from another.",
"JavaScript uses the <code>-</code> symbol for subtraction.",
"",
"<strong>Example</strong>",
"<blockquote>myVar = 12 - 6; // assigned 6</blockquote>",
"",
"<h4>Instructions</h4>",
"Change the <code>0</code> so the difference is <code>12</code>."
],
"challengeSeed": [
"var difference = 45 - 0;",
"",
""
],
"tail": [
"(function(z){return 'difference='+z;})(difference);"
],
"solutions": [
"var difference = 45 - 33;"
],
"tests": [
"assert(difference === 12, 'message: Make the variable <code>difference</code> equal 12.');",
"assert((code).match(/difference/g).length === 1,'message: Only change the first line');",
"assert(/\\d+\\s*-\\s*\\d+/.test(code),'message: Use the <code>-</code> operator');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Resta un número de otro con JavaScript",
"descriptionEs": [
"También podemos restar un número de otro.",
"JavaScript utiliza el símbolo <code>-</code> de sustracción",
"Cambia el <code>0</code> para que la diferencia sea <code>12</code>."
]
},
{
"id": "cf1231c1c11feddfaeb5bdef",
"title": "Multiply Two Numbers with JavaScript",
"description": [
"We can also multiply one number by another.",
"JavaScript uses the <code>*</code> symbol for multiplication of two numbers.",
"",
"<strong>Example</strong>",
"<blockquote>myVar = 13 * 13; // assigned 169</blockquote>",
"",
"<h4>Instructions</h4>",
"Change the <code>0</code> so that product will equal <code>80</code>."
],
"challengeSeed": [
"var product = 8 * 0;",
"",
""
],
"tail": [
"(function(z){return 'product = '+z;})(product);"
],
"solutions": [
"var product = 8 * 10;"
],
"tests": [
"assert(product === 80,'message: Make the variable <code>product</code> equal 80');",
"assert(/\\*/.test(code), 'message: Use the <code>*</code> operator');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Multiplica dos números con JavaScript",
"descriptionEs": [
"También podemos multiplicar un número por otro.",
"JavaScript utiliza el símbolo <code>*</code> de la multiplicación.",
"Cambie el <code>0</code> para que el producto sea igual a <code>80</code>."
]
},
{
"id": "cf1111c1c11feddfaeb6bdef",
"title": "Divide One Number by Another with JavaScript",
"description": [
"We can also divide one number by another.",
"JavaScript uses the <code>/</code> symbol for division.",
"",
"<strong>Example</strong>",
"<blockquote>myVar = 16 / 2; // assigned 8</blockquote>",
"",
"<h4>Instructions</h4>",
"Change the <code>0</code> so that the <code>quotient</code> is equal to <code>2</code>."
],
"challengeSeed": [
"var quotient = 66 / 0;",
"",
""
],
"tail": [
"(function(z){return 'quotient = '+z;})(quotient);"
],
"solutions": [
"var quotient = 66 / 33;"
],
"tests": [
"assert(quotient === 2, 'message: Make the variable <code>quotient</code> equal to 2.');",
"assert(/\\d+\\s*\\/\\s*\\d+/.test(code), 'message: Use the <code>/</code> operator');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Divide un número por otro con JavaScript",
"descriptionEs": [
"También podemos dividir un número por otro.",
"JavaScript utiliza el símbolo <code>/</code> para dividir.",
"Cambia el <code>0</code> para que el cociente sea igual a <code>2</code>."
]
},
{
"id": "56533eb9ac21ba0edf2244ac",
"title": "Increment a Number with Javascript",
"description": [
"You can easily <dfn>increment</dfn> or add one to a variable with the <code>++</code> operator.",
"<code>i++;</code>",
"is the equivalent of",
"<code>i = i + 1;</code>",
"<strong>Note</strong><br>The entire line becomes <code>i++;</code>, eliminating the need for the equal sign.",
"<h4>Instructions</h4>",
"Change the code to use the <code>++</code> operator on <code>myVar</code>."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"var myVar = 87;",
"",
"// Only change code below this line",
"myVar = myVar + 1;",
""
],
"tail": [
"(function(z){return 'myVar = ' + z;})(myVar);"
],
"solutions": [
"var myVar = 87;\nmyVar++;"
],
"tests": [
"assert(myVar === 88, 'message: <code>myVar</code> should equal <code>88</code>');",
"assert(/myVar\\s*[+]{2}/.test(code), 'message: Use the <code>++</code> operator');",
"assert(/var myVar = 87;/.test(code), 'message: Do not change code above the line');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244ad",
"title": "Decrement a Number with Javascript",
"description": [
"You can easily <dfn>decrement</dfn> or decrease a variable by one with the <code>--</code> operator.",
"<code>i--;</code>",
"is the equivalent of",
"<code>i = i - 1;</code>",
"<strong>Note</strong><br>The entire line becomes <code>i--;</code>, eliminating the need for the equal sign.",
"<h4>Instructions</h4>",
"Change the code to use the <code>--</code> operator on <code>myVar</code>."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"var myVar = 11;",
"",
"// Only change code below this line",
"myVar = myVar - 1;",
""
],
"tail": [
"(function(z){return 'myVar = ' + z;})(myVar);"
],
"solutions": [
"var myVar = 11;\nmyVar--;"
],
"tests": [
"assert(myVar === 10, 'message: <code>myVar</code> should equal <code>10</code>');",
"assert(/myVar\\s*[-]{2}/.test(code), 'message: Use the <code>--</code> operator on <code>myVar</code>');",
"assert(/var myVar = 11;/.test(code), 'message: Do not change code above the line');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "cf1391c1c11feddfaeb4bdef",
"title": "Create Decimal Numbers with JavaScript",
"description": [
"We can store decimal numbers in variables too. Decimal numbers are sometimes referred to as <dfn>floating point</dfn> numbers or <dfn>floats</dfn>.",
"<strong>Note</strong><br>Not all real numbers can accurately be represented in <dfn>floating point</dfn>. This can lead to rounding errors. <a href=\"https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems\" target=\"_blank\">Details Here</a>.",
"<h4>Instructions</h4>",
"Create a variable <code>myDecimal</code> and give it a decimal value with a fractional part (e.g. <code>5.7</code>)."
],
"challengeSeed": [
"var ourDecimal = 5.7;",
"",
"// Only change code below this line",
"",
""
],
"tail": [
"(function(){if(typeof myDecimal !== \"undefined\"){return myDecimal;}})();"
],
"solutions": [
"var myDecimal = 9.9;"
],
"tests": [
"assert(typeof myDecimal === \"number\", 'message: <code>myDecimal</code> should be a number.');",
"assert(myDecimal % 1 != 0, 'message: <code>myDecimal</code> should have a decimal point'); "
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Crea números decimales con JavaScript",
"descriptionEs": [
"Las variables tipo número en JavaScript también pueden tener decimales.",
"Vamos a crear una variable <code>myDecimal</code> y a darle un valor decimal."
]
},
{
"id": "bd7993c9c69feddfaeb7bdef",
"title": "Multiply Two Decimals with JavaScript",
"description": [
"In JavaScript, you can also perform calculations with decimal numbers, just like whole numbers.",
"Let's multiply two decimals together to get their product.",
"<h4>Instructions</h4>",
"Change the <code>0.0</code> so that product will equal <code>5.0</code>."
],
"challengeSeed": [
"var product = 2.0 * 0.0;",
"",
""
],
"tail": [
"(function(y){return 'product = '+y;})(product);"
],
"solutions": [
"var product = 2.0 * 2.5;"
],
"tests": [
"assert(product === 5.0, 'message: The variable <code>product</code> should equal <code>5.0</code>.');",
"assert(/\\*/.test(code), 'message: You should use the <code>*</code> operator');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Multiplica dos decimales con JavaScript",
"descriptionEs": [
"En JavaScript, también puedes realizar cálculos con números decimales, al igual que con números enteros.",
"Vamos a multiplicar dos números decimales para obtener su producto.",
"Cambia el <code>0.0</code> para que el producto sea igual a <code>5.0</code>."
]
},
{
"id": "bd7993c9ca9feddfaeb7bdef",
"title": "Divide one Decimal by Another with JavaScript",
"description": [
"Now let's divide one decimal by another.",
"<h4>Instructions</h4>",
"Change the <code>0.0</code> so that <code>quotient</code> will equal to <code>2.2</code>."
],
"challengeSeed": [
"var quotient = 0.0 / 2.0;",
"",
""
],
"tail": [
"(function(y){return 'quotient = '+y;})(quotient);"
],
"solutions": [
"var quotient = 4.4 / 2.0;"
],
"tests": [
"assert(quotient === 2.2, 'message: The variable <code>quotient</code> should equal <code>2.2</code>.');",
"assert(/\\//.test(code), 'message: You should use the <code>/</code> operator');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Divide un número decimal por otro con JavaScript",
"descriptionEs": [
"Ahora vamos a dividir un decimal por otro.",
"Cambia el <code>0.0</code> para que tu cociente sea igual a <code>2.2</code>."
]
},
{
"id": "56533eb9ac21ba0edf2244ae",
"title": "Finding a Remainder in Javascript",
"description": [
"The <dfn>remainder</dfn> operator <code>%</code> gives the remainder of the division of two numbers.",
"<strong>Example</strong>",
"<blockquote>5 % 2 = 1 because<br>Math.floor(5 / 2) = 2 (Quotient)<br>2 * 2 = 4<br>5 - 4 = 1 (Remainder)</blockquote>",
"<strong>Usage</strong><br>In mathematics, a number can be checked even or odd by checking the remainder of the division of the number by <code>2</code>.",
"<blockquote>17 % 2 = 1 (17 is Odd)<br>48 % 2 = 0 (48 is Even)</blockquote>",
"<strong>Note</strong><br>The <dfn>remainder</dfn> operator is sometimes incorrectly referred to as the \"modulus\" operator. It is very similar to modulus, but does not work properly with negative numbers.",
"<h4>Instructions</h4>",
"Set <code>remainder</code> equal to the remainder of <code>11</code> divided by <code>3</code> using the <dfn>remainder</dfn> (<code>%</code>) operator."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Only change code below this line",
"",
"var remainder;",
""
],
"tail": [
"(function(y){return 'remainder = '+y;})(remainder);"
],
"solutions": [
"var remainder = 11 % 3;"
],
"tests": [
"assert(remainder === 2, 'message: The value of <code>remainder</code> should be <code>2</code>');",
"assert(/\\d+\\s*%\\s*\\d+/.test(code), 'message: You should use the <code>%</code> operator');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244af",
"title": "Assignment with Plus Equals",
"description": [
"In programming, it is common to use assignments to modify the contents of a variable. Remember that everything to the right of the equals sign is evaluated first, so we can say:",
"<code>myVar = myVar + 5;</code>",
"to add <code>5</code> to <code>myVar</code>. Since this is such a common pattern, there are operators which do both a mathematical operation and assignment in one step.",
"One such operator is the <code>+=</code> operator.",
"<code>myVar += 5;</code> will add <code>5</code> to <code>myVar</code>.",
"<h4>Instructions</h4>",
"Convert the assignments for <code>a</code>, <code>b</code>, and <code>c</code> to use the <code>+=</code> operator."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"var a = 3;",
"var b = 17;",
"var c = 12;",
"",
"// Only modify code below this line",
"",
"a = a + 12;",
"b = 9 + b;",
"c = c + 7;",
""
],
"tail": [
"(function(a,b,c){ return \"a = \" + a + \", b = \" + b + \", c = \" + c; })(a,b,c);"
],
"solutions": [
"var a = 3;\nvar b = 17;\nvar c = 12;\n\na += 12;\nb += 9;\nc += 7;"
],
"tests": [
"assert(a === 15, 'message: <code>a</code> should equal <code>15</code>');",
"assert(b === 26, 'message: <code>b</code> should equal <code>26</code>');",
"assert(c === 19, 'message: <code>c</code> should equal <code>19</code>');",
"assert(code.match(/\\+=/g).length === 3, 'message: You should use the <code>+=</code> operator for each variable');",
"assert(/var a = 3;/.test(code) && /var b = 17;/.test(code) && /var c = 12;/.test(code), 'message: Do not modify the code above the line');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244b0",
"title": "Assignment with Minus Equals",
"description": [
"Like the <code>+=</code> operator, <code>-=</code> subtracts a number from a variable.",
"<code>myVar = myVar - 5;</code>",
"will subtract <code>5</code> from <code>myVar</code>. This can be rewritten as: ",
"<code>myVar -= 5;</code>",
"<h4>Instructions</h4>",
"Convert the assignments for <code>a</code>, <code>b</code>, and <code>c</code> to use the <code>-=</code> operator."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"var a = 11;",
"var b = 9;",
"var c = 3;",
"",
"// Only modify code below this line",
"",
"a = a - 6;",
"b = b - 15;",
"c = c - 1;",
"",
""
],
"tail": [
"(function(a,b,c){ return \"a = \" + a + \", b = \" + b + \", c = \" + c; })(a,b,c);"
],
"solutions": [
"var a = 11;\nvar b = 9;\nvar c = 3;\n\na -= 6;\nb -= 15;\nc -= 1;\n\n"
],
"tests": [
"assert(a === 5, 'message: <code>a</code> should equal <code>5</code>');",
"assert(b === -6, 'message: <code>b</code> should equal <code>-6</code>');",
"assert(c === 2, 'message: <code>c</code> should equal <code>2</code>');",
"assert(code.match(/-=/g).length === 3, 'message: You should use the <code>-=</code> operator for each variable');",
"assert(/var a = 11;/.test(code) && /var b = 9;/.test(code) && /var c = 3;/.test(code), 'message: Do not modify the code above the line');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244b1",
"title": "Assignment with Times Equals",
"description": [
"The <code>*=</code> operator multiplies a variable by a number.",
"<code>myVar = myVar * 5;</code>",
"will multiply <code>myVar</code> by <code>5</code>. This can be rewritten as: ",
"<code>myVar *= 5;</code>",
"<h4>Instructions</h4>",
"Convert the assignments for <code>a</code>, <code>b</code>, and <code>c</code> to use the <code>*=</code> operator."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"var a = 5;",
"var b = 12;",
"var c = 4.6;",
"",
"// Only modify code below this line",
"",
"a = a * 5;",
"b = 3 * b;",
"c = c * 10;",
"",
""
],
"tail": [
"(function(a,b,c){ return \"a = \" + a + \", b = \" + b + \", c = \" + c; })(a,b,c);"
],
"solutions": [
"var a = 5;\nvar b = 12;\nvar c = 4.6;\n\na *= 5;\nb *= 3;\nc *= 10;"
],
"tests": [
"assert(a === 25, 'message: <code>a</code> should equal <code>25</code>');",
"assert(b === 36, 'message: <code>b</code> should equal <code>36</code>');",
"assert(c === 46, 'message: <code>c</code> should equal <code>46</code>');",
"assert(code.match(/\\*=/g).length === 3, 'message: You should use the <code>*=</code> operator for each variable');",
"assert(/var a = 5;/.test(code) && /var b = 12;/.test(code) && /var c = 4\\.6;/.test(code), 'message: Do not modify the code above the line');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244b2",
"title": "Assignment with Divided by Equals",
"description": [
"The <code>/=</code> operator divides a variable by another number.",
"<code>myVar = myVar / 5;</code>",
"Will divide <code>myVar</code> by <code>5</code>. This can be rewritten as: ",
"<code>myVar /= 5;</code>",
"<h4>Instructions</h4>",
"Convert the assignments for <code>a</code>, <code>b</code>, and <code>c</code> to use the <code>/=</code> operator."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"var a = 48;",
"var b = 108;",
"var c = 33;",
"",
"// Only modify code below this line",
"",
"a = a / 12;",
"b = b / 4;",
"c = c / 11;",
""
],
"tail": [
"(function(a,b,c){ return \"a = \" + a + \", b = \" + b + \", c = \" + c; })(a,b,c);"
],
"solutions": [
"var a = 48;\nvar b = 108;\nvar c = 33;\n\na /= 12;\nb /= 4;\nc /= 11;"
],
"tests": [
"assert(a === 4, 'message: <code>a</code> should equal <code>4</code>');",
"assert(b === 27, 'message: <code>b</code> should equal <code>27</code>');",
"assert(c === 3, 'message: <code>c</code> should equal <code>3</code>');",
"assert(code.match(/\\/=/g).length === 3, 'message: You should use the <code>/=</code> operator for each variable');",
"assert(/var a = 48;/.test(code) && /var b = 108;/.test(code) && /var c = 33;/.test(code), 'message: Do not modify the code above the line');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244b3",
"title": "Convert Celsius to Fahrenheit",
"description": [
"To test your learning you will create a solution \"from scratch\". Place your code between the indicated lines and it will be tested against multiple test cases.",
"The algorithm to convert from Celsius to Fahrenheit is the temperature in Celsius times 9/5, plus 32.",
"You are given a variable <code>celsius</code> representing a temperature in Celsius. Create a variable <code>fahrenheit</code> and apply the algorithm to assign it the corresponding temperature in Fahrenheit."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"function convert(celsius) {",
" // Only change code below this line",
" ",
"",
" // Only change code above this line",
" if ( typeof fahrenheit !== 'undefined' ) {",
" return fahrenheit;",
" } else {",
" return 'fahrenheit not defined';",
" }",
"}",
"",
"// Change the inputs below to test your code",
"convert(30);"
],
"solutions": [
"function convert(celsius) {\n var fahrenheit = celsius * 9/5 + 32;\n if ( typeof fahrenheit !== 'undefined' ) {\n return fahrenheit;\n } else {\n return 'fahrenheit not defined';\n }\n}"
],
"tests": [
"assert(typeof convert(0) === 'number', 'message: <code>convert(0)</code> should return a number');",
"assert(convert(-30) === -22, 'message: <code>convert(-30)</code> should return a value of <code>-22</code>');",
"assert(convert(-10) === 14, 'message: <code>convert(-10)</code> should return a value of <code>14</code>');",
"assert(convert(0) === 32, 'message: <code>convert(0)</code> should return a value of <code>32</code>');",
"assert(convert(20) === 68, 'message: <code>convert(20)</code> should return a value of <code>68</code>');",
"assert(convert(30) === 86, 'message: <code>convert(30)</code> should return a value of <code>86</code>');"
],
"type": "checkpoint",
"challengeType": 1
},
{
"id": "bd7123c9c444eddfaeb5bdef",
"title": "Declare String Variables",
"description": [
"Previously we have used the code",
"<code>var myName = \"your name\";</code>",
"<code>\"your name\"</code> is called a <dfn>string</dfn> <dfn>literal</dfn>. It is a string because it is a series of zero or more characters enclosed in single or double quotes.",
"<h4>Instructions</h4>",
"Create two new <code>string</code> variables: <code>myFirstName</code> and <code>myLastName</code> and assign them the values of your first and last name, respectively."
],
"challengeSeed": [
"// Example",
"var firstName = \"Alan\";",
"var lastName = \"Turing\";",
"",
"// Only change code below this line",
"",
"",
""
],
"tail": [
"if(typeof myFirstName !== \"undefined\" && typeof myLastName !== \"undefined\"){(function(){return myFirstName + ', ' + myLastName;})();}"
],
"solutions": [
"var myFirstName = \"Alan\";\nvar myLastName = \"Turing\";"
],
"tests": [
"assert((function(){if(typeof myFirstName !== \"undefined\" && typeof myFirstName === \"string\" && myFirstName.length > 0){return true;}else{return false;}})(), 'message: <code>myFirstName</code> should be a string with at least one character in it.');",
"assert((function(){if(typeof myLastName !== \"undefined\" && typeof myLastName === \"string\" && myLastName.length > 0){return true;}else{return false;}})(), 'message: <code>myLastName</code> should be a string with at least one character in it.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Declara variables tipo cadena",
"descriptionEs": [
"En el reto anterior, se utilizó el código <code>myName var = \"su nombre\"</code>. Esto es lo que llamamos una variable tipo <code>cadena</code>. No es nada más que una \"cadena\" de caracteres. Las cadenas en JavaScript siempre se encierran entre comillas. ",
"Ahora vamos a crear dos nuevas variables tipo cadena: <code>myFirstName</code> y <code>myLastName</code> y asignarles los valores de tu nombre y tu apellido, respectivamente."
]
},
{
"id": "56533eb9ac21ba0edf2244b5",
"title": "Escaping Literal Quotes in Strings",
"description": [
"When you are defining a string you must start and end with a single or double quote. What happens when you need a literal quote: <code>\"</code> or <code>'</code> inside of your string?",
"In JavaScript, you can <dfn>escape</dfn> a quote from considering it as an end of string quote by placing a <dfn>backslash</dfn> (<code>\\</code>) in front of the quote.",
"<code>var sampleStr = \"Alan said, \\\"Peter is learning JavaScript\\\".\";</code>",
"This signals to JavaScript that the following quote is not the end of the string, but should instead appear inside the string. So if you were to print this to the console, you would get:",
"<code>Alan said, \"Peter is learning JavaScript\".</code>",
"<h4>Instruction</h4>",
"Use <dfn>backslashes</dfn> to assign a string to the <code>myStr</code> variable so that <em>if</em> you were to print it to the console, you would see:",
"<code>I am a \"double quoted\" string inside \"double quotes\"</code>"
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"var myStr; // Change this line",
"",
""
],
"tail": [
"(function(){",
" if(typeof myStr === 'string') {",
" return \"myStr = \" + myStr;",
" } else {",
" return \"myStr is undefined\";",
" }",
"})();"
],
"solutions": [
"var myStr = \"I am a \\\"double quoted\\\" string inside \\\"double quotes\\\"\";"
],
"tests": [
"assert(code.match(/\\\\\"/g).length === 4 && code.match(/[^\\\\]\"/g).length === 2, 'message: You should use two double quotes (<code>&quot;</code>) and four escaped double quotes (<code>&#92;&quot;</code>) ');",
"assert(myStr === \"I am a \\\"double quoted\\\" string inside \\\"double quotes\\\"\", 'message: Variable myStr should equal to (<code>\"I am a \"double quoted\" string inside \"double quotes\"\"</code>).');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244b4",
"title": "Quoting Strings with Single Quotes",
"description": [
"<dfn>String</dfn> values in JavaScript may be written with single or double quotes, so long as you start and end with the same type of quote. Unlike some languages, single and double quotes are functionally identical in Javascript.",
"<code>\"This string has \\\"double quotes\\\" in it\"</code>",
"The value in using one or the other has to do with the need to <dfn>escape</dfn> quotes of the same type. If you have a string with many double quotes, this can be difficult to read and write. Instead, use single quotes:",
"<code>'This string has \"double quotes\" in it. And \"probably\" lots of them.'</code>",
"<h4>Instructions</h4>",
"Change the provided string from double to single quotes and remove the escaping."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"var myStr = \"<a href=\\\"http://www.example.com\\\" target=\\\"_blank\\\">Link</a>\";",
"",
""
],
"tail": [
"(function() { return \"myStr = \" + myStr; })();"
],
"solutions": [
"var myStr = '<a href=\"http://www.example.com\" target=\"_blank\">Link</a>';"
],
"tests": [
"assert(!/\\\\/g.test(code), 'message: Remove all the <code>backslashes</code> (<code>\\</code>)');",
"assert(code.match(/\"/g).length === 4 && code.match(/'/g).length === 2, 'message: You should have two single quotes <code>&#39;</code> and four double quotes <code>&quot;</code>');",
"assert(myStr === '<a href=\"http://www.example.com\" target=\"_blank\">Link</a>', 'message: Only remove the backslashes <code>\\</code> used to escape quotes.');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244b6",
"title": "Escape Sequences in Strings",
"description": [
"Quotes are not the only characters that can be <dfn>escaped</dfn> inside a string. Here is a table of common escape sequences:",
"<table class=\"table table-striped\"><thead><tr><th>Code</th><th>Output</th></tr></thead><tbody><tr><td>\\'</td><td>single quote</td></tr><tr><td>\\\"</td><td>double quote</td></tr><tr><td>\\\\</td><td>backslash</td></tr><tr><td>\\n</td><td>new line</td></tr><tr><td>\\r</td><td>carriage return</td></tr><tr><td>\\t</td><td>tab</td></tr><tr><td>\\b</td><td>backspace</td></tr><tr><td>\\f</td><td>form feed</td></tr></tbody></table>",
"<em>Note that the backslash itself must be escaped in order to display as a backslash.</em>",
"<h4>Instructions</h4>",
"Encode the following sequence, separated by spaces:<br><code>backslash tab tab carriage-return new-line</code> and assign it to <code>myStr</code>"
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"var myStr; // Change this line",
"",
""
],
"tail": [
"(function(){",
"if (myStr !== undefined){",
"return 'myStr = '+ JSON.stringify(myStr);}",
"else{return null;}})();"
],
"solutions": [
"var myStr = \"\\\\ \\t \\t \\r \\n\";"
],
"tests": [
"assert(myStr === \"\\\\ \\t \\t \\r \\n\", 'message: <code>myStr</code> should have the escape sequences for <code>backslash tab tab carriage-return new-line</code> separated by spaces');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244b7",
"title": "Concatenating Strings with Plus Operator",
"description": [
"In JavaScript, when the <code>+</code> operator is used with a <code>String</code> value, it is called the <dfn>concatenation</dfn> operator. You can build a new string out of other strings by <dfn>concatenating</dfn> them together.",
"<strong>Example</strong>",
"<blockquote>'My name is Alan,' + ' I concatenate.'</blockquote>",
"<strong>Note</strong><br>Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.",
"<h4>Instructions</h4>",
"Build <code>myStr</code> from the strings <code>\"This is the start. \"</code> and <code>\"This is the end.\"</code> using the <code>+</code> operator."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Example",
"var ourStr = \"I come first. \" + \"I come second.\";",
"",
"// Only change code below this line",
"",
"var myStr;",
"",
""
],
"tail": [
"(function(){",
" if(typeof myStr === 'string') {",
" return 'myStr = \"' + myStr + '\"';",
" } else {",
" return 'myStr is not a string';",
" }",
"})();"
],
"solutions": [
"var ourStr = \"I come first. \" + \"I come second.\";\nvar myStr = \"This is the start. \" + \"This is the end.\";"
],
"tests": [
"assert(myStr === \"This is the start. This is the end.\", 'message: <code>myStr</code> should have a value of <code>This is the start. This is the end.</code>');",
"assert(code.match(/([\"']).*([\"'])\\s*\\+\\s*([\"']).*([\"'])/g).length > 1, 'message: Use the <code>+</code> operator to build <code>myStr</code>');",
"assert(/var\\s+myStr/.test(code), 'message: <code>myStr</code> should be created using the <code>var</code> keyword.');",
"assert(/myStr\\s*=/.test(code), 'message: Make sure to assign the result to the <code>myStr</code> variable.');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244b8",
"title": "Concatenating Strings with the Plus Equals Operator",
"description": [
"We can also use the <code>+=</code> operator to <dfn>concatenate</dfn> a string onto the end of an existing string variable. This can be very helpful to break a long string over several lines.",
"<strong>Note</strong><br>Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.",
"<h4>Instructions</h4>",
"Build <code>myStr</code> over several lines by concatenating these two strings:<br><code>\"This is the first sentence. \"</code> and <code>\"This is the second sentence.\"</code> using the <code>+=</code> operator."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Example",
"var ourStr = \"I come first. \";",
"ourStr += \"I come second.\";",
"",
"// Only change code below this line",
"",
"var myStr;",
"",
""
],
"tail": [
"(function(){",
" if(typeof myStr === 'string') {",
" return 'myStr = \"' + myStr + '\"';",
" } else {",
" return 'myStr is not a string';",
" }",
"})();"
],
"solutions": [
"var ourStr = \"I come first. \";\nourStr += \"I come second.\";\n\nvar myStr = \"This is the first sentence. \";\nmyStr += \"This is the second sentence.\";"
],
"tests": [
"assert(myStr === \"This is the first sentence. This is the second sentence.\", 'message: <code>myStr</code> should have a value of <code>This is the first sentence. This is the second sentence.</code>');",
"assert(code.match(/\\w\\s*\\+=\\s*[\"']/g).length > 1 && code.match(/\\w\\s*\\=\\s*[\"']/g).length > 1, 'message: Use the <code>+=</code> operator to build <code>myStr</code>');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244b9",
"title": "Constructing Strings with Variables",
"description": [
"Sometimes you will need to build a string, <a href=\"https://en.wikipedia.org/wiki/Mad_Libs\" target=\"_blank\">Mad Libs</a> style. By using the concatenation operator (<code>+</code>), you can insert one or more variables into a string you're building.",
"<h4>Instructions</h4>",
"Set <code>myName</code> to a string equal to your name and build <code>myStr</code> with <code>myName</code> between the strings <code>\"My name is \"</code> and <code>\" and I am swell!\"</code>"
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Example",
"var ourName = \"Free Code Camp\";",
"var ourStr = \"Hello, our name is \" + ourName + \", how are you?\";",
"",
"// Only change code below this line",
"var myName;",
"var myStr;",
"",
""
],
"tail": [
"(function(){",
" var output = [];",
" if(typeof myName === 'string') {",
" output.push('myName = \"' + myName + '\"');",
" } else {",
" output.push('myName is not a string');",
" }",
" if(typeof myStr === 'string') {",
" output.push('myStr = \"' + myStr + '\"');",
" } else {",
" output.push('myStr is not a string');",
" }",
" return output.join('\\n');",
"})();"
],
"solutions": [
"var myName = \"Bob\";\nvar myStr = \"My name is \" + myName + \" and I am swell!\";"
],
"tests": [
"assert(typeof myName !== 'undefined' && myName.length > 2, 'message: <code>myName</code> should be set to a string at least 3 characters long');",
"assert(code.match(/[\"']\\s*\\+\\s*myName\\s*\\+\\s*[\"']/g).length > 0, 'message: Use two <code>+</code> operators to build <code>myStr</code> with <code>myName</code> inside it');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244ed",
"title": "Appending Variables to Strings",
"description": [
"Just as we can build a string over multiple lines out of string <dfn>literals</dfn>, we can also append variables to a string using the plus equals (<code>+=</code>) operator.",
"<h4>Instructions</h4>",
"Set <code>someAdjective</code> and append it to <code>myStr</code> using the <code>+=</code> operator."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Example",
"var anAdjective = \"awesome!\";",
"var ourStr = \"Free Code Camp is \";",
"ourStr += anAdjective;",
"",
"// Only change code below this line",
"",
"var someAdjective;",
"var myStr = \"Learning to code is \";",
""
],
"tail": [
"(function(){",
" var output = [];",
" if(typeof someAdjective === 'string') {",
" output.push('someAdjective = \"' + someAdjective + '\"');",
" } else {",
" output.push('someAdjective is not a string');",
" }",
" if(typeof myStr === 'string') {",
" output.push('myStr = \"' + myStr + '\"');",
" } else {",
" output.push('myStr is not a string');",
" }",
" return output.join('\\n');",
"})();"
],
"solutions": [
"var anAdjective = \"awesome!\";\nvar ourStr = \"Free Code Camp is \";\nourStr += anAdjective;\n\nvar someAdjective = \"neat\";\nvar myStr = \"Learning to code is \";\nmyStr += someAdjective;"
],
"tests": [
"assert(typeof someAdjective !== 'undefined' && someAdjective.length > 2, 'message: <code>someAdjective</code> should be set to a string at least 3 characters long');",
"assert(code.match(/\\w\\s*\\+=\\s*someAdjective\\s*;/).length > 0, 'message: Append <code>someAdjective</code> to <code>myStr</code> using the <code>+=</code> operator');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "bd7123c9c448eddfaeb5bdef",
"title": "Find the Length of a String",
"description": [
"You can find the length of a <code>String</code> value by writing <code>.length</code> after the string variable or string literal.",
"<code>\"Alan Peter\".length; // 10</code>",
"For example, if we created a variable <code>var firstName = \"Charles\"</code>, we could find out how long the string <code>\"Charles\"</code> is by using the <code>firstName.length</code> property.",
"<h4>Instructions</h4>",
"Use the <code>.length</code> property to count the number of characters in the <code>lastName</code> variable and assign it to <code>lastNameLength</code>."
],
"challengeSeed": [
"// Example",
"var firstNameLength = 0;",
"var firstName = \"Ada\";",
"",
"firstNameLength = firstName.length;",
"",
"// Setup",
"var lastNameLength = 0;",
"var lastName = \"Lovelace\";",
"",
"// Only change code below this line.",
"",
"lastNameLength = lastName;",
"",
""
],
"tail": [
"if(typeof lastNameLength !== \"undefined\"){(function(){return lastNameLength;})();}"
],
"solutions": [
"var firstNameLength = 0;\nvar firstName = \"Ada\";\nfirstNameLength = firstName.length;\n\nvar lastNameLength = 0;\nvar lastName = \"Lovelace\";\nlastNameLength = lastName.length;"
],
"tests": [
"assert((function(){if(typeof lastNameLength !== \"undefined\" && typeof lastNameLength === \"number\" && lastNameLength === 8){return true;}else{return false;}})(), 'message: <code>lastNameLength</code> should be equal to eight.');",
"assert((function(){if(code.match(/\\.length/gi) && code.match(/\\.length/gi).length >= 2 && code.match(/var lastNameLength \\= 0;/gi) && code.match(/var lastNameLength \\= 0;/gi).length >= 1){return true;}else{return false;}})(), 'message: You should be getting the length of <code>lastName</code> by using <code>.length</code> like this: <code>lastName.length</code>.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Comprueba la propiedad longitud (length) de una variable tipo cadena",
"descriptionEs": [
"Las <code>estructuras de datos</code> tienen <code>propiedades</code>. Por ejemplo, las <code>cadenas</code> tienen una propiedad llamada <code>.length </code> que te dirá cuántos caracteres hay en la cadena.",
"Por ejemplo, si creamos una variable <code>var firstName=\"Charles\"</code>, podemos averiguar la longitud de la cadena \"Charles\" usando la propiedad <code>firstName.length</code>. ",
"Usa la propiedad <code>.length</code> para contar el número de caracteres en el variable <code>lastName</code>."
]
},
{
"id": "bd7123c9c549eddfaeb5bdef",
"title": "Use Bracket Notation to Find the First Character in a String",
"description": [
"<code>Bracket notation</code> is a way to get a character at a specific <code>index</code> within a string.",
"Most modern programming languages, like JavaScript, don't start counting at 1 like humans do. They start at 0. This is referred to as <dfn>Zero-based</dfn> indexing.",
"For example, the character at index 0 in the word \"Charles\" is \"C\". So if <code>var firstName = \"Charles\"</code>, you can get the value of the first letter of the string by using <code>firstName[0]</code>.",
"<h4>Instructions</h4>",
"Use <dfn>bracket notation</dfn> to find the first character in the <code>lastName</code> variable and assign it to <code>firstLetterOfLastName</code>.",
"<strong>Hint</strong><br>Try looking at the <code>firstLetterOfFirstName</code> variable declaration if you get stuck."
],
"challengeSeed": [
"// Example",
"var firstLetterOfFirstName = \"\";",
"var firstName = \"Ada\";",
"",
"firstLetterOfFirstName = firstName[0];",
"",
"// Setup",
"var firstLetterOfLastName = \"\";",
"var lastName = \"Lovelace\";",
"",
"// Only change code below this line",
"firstLetterOfLastName = lastName;",
""
],
"tail": [
"(function(v){return v;})(firstLetterOfLastName);"
],
"solutions": [
"var firstLetterOfLastName = \"\";\nvar lastName = \"Lovelace\";\n\n// Only change code below this line\nfirstLetterOfLastName = lastName[0];"
],
"tests": [
"assert(firstLetterOfLastName === 'L', 'message: The <code>firstLetterOfLastName</code> variable should have the value of <code>L</code>.');",
"assert(code.match(/firstLetterOfLastName\\s*=\\s*lastName\\s*\\[\\s*\\d+\\s*\\]/), 'message: You should use bracket notation.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Usa la notación de corchetes para encontrar el primer acaracter de una cadena",
"descriptionEs": [
"La <code>notación de corchetes</code> es una forma de obtener el caracter en un <code>índice</code> específico de una cadena.",
"Los computadoras no empiezan a contar desde 1 como hacen los humanos. Comienzan en 0 ",
"Por ejemplo, el caracter en el índice 0 en la palabra \"Charles \" es \"C\". Entonces si <code>var firstName = \"Charles\"</code>, puedes obtener la primera letra de la cadena usando <code>firstName[0]</code> .",
"Usa la <code>notación de corchetes</code> para encontrar el primer caracter en la variable <code>lastName</code> y asignarlo a <code>firstLetterOfLastName</code>.",
"Si te atascas intenta mirar la declaración de la variable <code>firstLetterOfFirstName</code>."
]
},
{
"id": "56533eb9ac21ba0edf2244ba",
"title": "Understand String Immutability",
"description": [
"In Javascript, <code>String</code> values are <dfn>immutable</dfn>, which means that they cannot be altered once created.",
"For example, the following code:",
"<blockquote>var myStr = \"Bob\";<br>myStr[0] = \"J\";</blockquote>",
"cannot change the value of <code>myStr</code> to \"Job\", because the contents of <code>myStr</code> cannot be altered. Note that this does <em>not</em> mean that <code>myStr</code> cannot be changed, just that the individual characters of a <dfn>string literal</dfn> cannot be changed. The only way to change <code>myStr</code> would be to assign it with a new string, like this:",
"<blockquote>var myStr = \"Bob\";<br>myStr = \"Job\";</blockquote>",
"<h4>Instructions</h4>",
"Correct the assignment to <code>myStr</code> to achieve the desired effect."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Setup",
"var myStr = \"Jello World\";",
"",
"// Only change code below this line",
"",
"myStr[0] = \"H\"; // Fix Me",
"",
""
],
"tail": [
"(function(v){return \"myStr = \" + v;})(myStr);"
],
"solutions": [
"var myStr = \"Jello World\";\nmyStr = \"Hello World\";"
],
"tests": [
"assert(myStr === \"Hello World\", 'message: <code>myStr</code> should have a value of <code>Hello World</code>');",
"assert(/myStr = \"Jello World\"/.test(code), 'message: Do not change the code above the line');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "bd7123c9c450eddfaeb5bdef",
"title": "Use Bracket Notation to Find the Nth Character in a String",
"description": [
"You can also use <dfn>bracket notation</dfn> to get the character at other positions within a string.",
"Remember that computers start counting at <code>0</code>, so the first character is actually the zeroth character.",
"<h4>Instructions</h4>",
"Let's try to set <code>thirdLetterOfLastName</code> to equal the third letter of the <code>lastName</code> variable using bracket notation.",
"<strong>Hint</strong><br>Try looking at the <code>secondLetterOfFirstName</code> variable declaration if you get stuck."
],
"challengeSeed": [
"// Example",
"var firstName = \"Ada\";",
"var secondLetterOfFirstName = firstName[1];",
"",
"// Setup",
"var lastName = \"Lovelace\";",
"",
"// Only change code below this line.",
"var thirdLetterOfLastName = lastName;",
"",
""
],
"tail": [
"(function(v){return v;})(thirdLetterOfLastName);"
],
"solutions": [
"var lastName = \"Lovelace\";\nvar thirdLetterOfLastName = lastName[2];"
],
"tests": [
"assert(thirdLetterOfLastName === 'v', 'message: The <code>thirdLetterOfLastName</code> variable should have the value of <code>v</code>.');",
"assert(code.match(/thirdLetterOfLastName\\s*=\\s*lastName\\s*\\[\\s*\\d+\\s*\\]/), 'message: You should use bracket notation.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Usa la notación de corchetes para encontrar el n-ésimo caracter en una cadena",
"descriptionEs": [
"También puede usar <code>notación de corchetes</code> para obtener el caracter en otras posiciones dentro de una cadena.",
"Recuerda que los computadores empiezan a contar a 0, por lo que el primer caracter es en realidad el caracter cero.",
"Vamos a tratar de asignar a <code>thirdLetterOfLastName</code> la <code>tercera letra</code> de la variable <code>lastName</code>.",
"Si te atascas intenta mirar la declaración de la variable <code>secondLetterOfFirstName</code>."
]
},
{
"id": "bd7123c9c451eddfaeb5bdef",
"title": "Use Bracket Notation to Find the Last Character in a String",
"description": [
"In order to get the last letter of a string, you can subtract one from the string's length.",
"For example, if <code>var firstName = \"Charles\"</code>, you can get the value of the last letter of the string by using <code>firstName[firstName.length - 1]</code>.",
"<h4>Instructions</h4>",
"Use <dfn>bracket notation</dfn> to find the last character in the <code>lastName</code> variable.",
"<strong>Hint</strong><br>Try looking at the <code>lastLetterOfFirstName</code> variable declaration if you get stuck."
],
"challengeSeed": [
"// Example",
"var firstName = \"Ada\";",
"var lastLetterOfFirstName = firstName[firstName.length - 1];",
"",
"// Setup",
"var lastName = \"Lovelace\";",
"",
"// Only change code below this line.",
"var lastLetterOfLastName = lastName;",
"",
""
],
"tail": [
"(function(v){return v;})(lastLetterOfLastName);"
],
"solutions": [
"var firstName = \"Ada\";\nvar lastLetterOfFirstName = firstName[firstName.length - 1];\n\nvar lastName = \"Lovelace\";\nvar lastLetterOfLastName = lastName[lastName.length - 1];"
],
"tests": [
"assert(lastLetterOfLastName === \"e\", 'message: <code>lastLetterOfLastName</code> should be \"e\".');",
"assert(code.match(/\\.length/g).length === 2, 'message: You have to use <code>.length</code> to get the last letter.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Usa notación de corchetes para encontrar el último caracter de una cadena",
"descriptionEs": [
"Con el fin de conseguir la última letra de una cadena, puedes restar uno a la longitud de la cadena.",
"Por ejemplo, si <code>var firstName = \"Charles\"</code>, se puede obtener la última letra usando <code>firstName[firstName.length - 1]</code>. ",
"Utiliza <code>notación de corchetes</code> para encontrar el último caracter de la variabel <code>lastName</code>.",
"Si te atascas intenta mirando la declaración de la variable <code>lastLetterOfFirstName</code>."
]
},
{
"id": "bd7123c9c452eddfaeb5bdef",
"title": "Use Bracket Notation to Find the Nth-to-Last Character in a String",
"description": [
"You can use the same principle we just used to retrieve the last character in a string to retrieve the Nth-to-last character.",
"For example, you can get the value of the third-to-last letter of the <code>var firstName = \"Charles\"</code> string by using <code>firstName[firstName.length - 3]</code>",
"<h4>Instructions</h4>",
"Use <dfn>bracket notation</dfn> to find the second-to-last character in the <code>lastName</code> string.",
" <strong>Hint</strong><br>Try looking at the <code>thirdToLastLetterOfFirstName</code> variable declaration if you get stuck."
],
"challengeSeed": [
"// Example",
"var firstName = \"Ada\";",
"var thirdToLastLetterOfFirstName = firstName[firstName.length - 3];",
"",
"// Setup",
"var lastName = \"Lovelace\";",
"",
"// Only change code below this line",
"var secondToLastLetterOfLastName = lastName;",
"",
""
],
"tail": [
"(function(v){return v;})(secondToLastLetterOfLastName);"
],
"solutions": [
"var firstName = \"Ada\";\nvar thirdToLastLetterOfFirstName = firstName[firstName.length - 3];\n\nvar lastName = \"Lovelace\";\nvar secondToLastLetterOfLastName = lastName[lastName.length - 2];"
],
"tests": [
"assert(secondToLastLetterOfLastName === 'c', 'message: <code>secondToLastLetterOfLastName</code> should be \"c\".');",
"assert(code.match(/\\.length/g).length === 2, 'message: You have to use <code>.length</code> to get the second last letter.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Usa notación de corchetes para encontrar el n-ésimo último caracter de una cadena",
"descriptionEs": [
"Puede utilizar el mismo principio utilizamos para recuperar el último caracter de una cadena para recuperar el n-ésimo último caracter.",
"Por ejemplo, se puede obtener el valor de la tercera última letra de la cadena <code>var firstName = \"Charles\"</code> utilizando <code>firstName[firstName.length - 3]</code> ",
"Usa <code>notación de corchete</code> para encontrar el segundo último caracter de la cadena en <code>lastName</code>.",
"Si te atascas intenta mirando la declaración de la variable <code>thirdToLastLetterOfFirstName</code>."
]
},
{
"id": "56533eb9ac21ba0edf2244bb",
"title": "Word Blanks",
"description": [
"We will now use our knowledge of strings to build a \"<a href='https://en.wikipedia.org/wiki/Mad_Libs' target='_blank'>Mad Libs</a>\" style word game we're calling \"Word Blanks\". You will create an (optionally humorous) \"Fill in the Blanks\" style sentence.",
"You will need to use string operators to build a new string, <code>result</code>, using the provided variables: <code>myNoun</code>, <code>myAdjective</code>, <code>myVerb</code>, and <code>myAdverb</code>.",
"You will also need to provide additional strings, which will not change, in between the provided words.",
"We have provided a framework for testing your results with different words. The tests will run your function with several different inputs to make sure all of the provided words appear in the output, as well as your extra strings."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) {",
" var result = \"\";",
" // Your code below this line",
" ",
"",
" // Your code above this line",
" return result;",
"}",
"",
"// Change the words here to test your function",
"wordBlanks(\"dog\", \"big\", \"ran\", \"quickly\");"
],
"tail": [
"var test1 = wordBlanks(\"dog\", \"big\", \"ran\", \"quickly\");",
"var test2 = wordBlanks(\"cat\", \"little\", \"hit\", \"slowly\");"
],
"solutions": [
"function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) {\n var result = \"\";\n\n result = \"Once there was a \" + myNoun + \" which was very \" + myAdjective + \". \";\n result += \"It \" + myVerb + \" \" + myAdverb + \" around the yard.\";\n\n return result;\n}"
],
"tests": [
"assert(typeof wordBlanks(\"\",\"\",\"\",\"\") === 'string', 'message: <code>wordBlanks(\"\",\"\",\"\",\"\")</code> should return a string.');",
"assert(/\\bdog\\b/.test(test1) && /\\bbig\\b/.test(test1) && /\\bran\\b/.test(test1) && /\\bquickly\\b/.test(test1),'message: <code>wordBlanks(\"dog\", \"big\", \"ran\", \"quickly\")</code> should contain all of the passed words separated by non-word characters (and any additional words in your madlib).');",
"assert(/\\bcat\\b/.test(test2) && /\\blittle\\b/.test(test2) && /\\bhit\\b/.test(test2) && /\\bslowly\\b/.test(test2),'message: <code>wordBlanks(\"cat\", \"little\", \"hit\", \"slowly\")</code> should contain all of the passed words separated by non-word characters (and any additional words in your madlib).');"
],
"type": "checkpoint",
"challengeType": 1
},
{
"id": "bd7993c9c69feddfaeb8bdef",
"title": "Store Multiple Values in one Variable using JavaScript Arrays",
"description": [
"With JavaScript <code>array</code> variables, we can store several pieces of data in one place.",
"You start an array declaration with an opening square bracket, end it with a closing square bracket, and put a comma between each entry, like this:<br><code>var sandwich = [\"peanut butter\", \"jelly\", \"bread\"]</code>.",
"<h4>Instructions</h4>",
"Create a new array called <code>myArray</code> that contains both a <code>string</code> and a <code>number</code> (in that order).",
"<strong>Hint</strong><br>Refer to the example code in the text editor if you get stuck."
],
"challengeSeed": [
"// Example",
"var array = [\"John\", 23];",
"",
"// Only change code below this line.",
"var myArray = [];",
""
],
"tail": [
"(function(z){return z;})(myArray);"
],
"solutions": [
"var myArray = [\"The Answer\", 42];"
],
"tests": [
"assert(typeof myArray == 'object', 'message: <code>myArray</code> should be an <code>array</code>.');",
"assert(typeof myArray[0] !== 'undefined' && typeof myArray[0] == 'string', 'message: The first item in <code>myArray</code> should be a <code>string</code>.');",
"assert(typeof myArray[1] !== 'undefined' && typeof myArray[1] == 'number', 'message: The second item in <code>myArray</code> should be a <code>number</code>.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Almacena múltiples valores en una variable utilizando vectores en JavaScript",
"descriptionEs": [
"Con las variables tipo <code>vector</code> (o en inglés <code>array</code>) podemos almacenar diversos datos en un solo lugar.",
"Empiezas la declaración de un vector con un corchete de apertura, y terminas con un corchete de cierre, y pones una coma entre cada entrada, así: <code>var sandwich = [\"mantequilla de maní\", \"jalea\" , \"pan\"]</code>. ",
"Ahora vamos a crear un nuevo vector llamado <code>myArray</code> que contenga una <code>cadena</code> y un <code>número</code> (en ese orden).",
"Consulta el código comentado en el editor de texto si te atascas."
]
},
{
"id": "cf1111c1c11feddfaeb7bdef",
"title": "Nest one Array within Another Array",
"description": [
"You can also nest arrays within other arrays, like this: <code>[[\"Bulls\", 23], [\"White Sox\", 45]]</code>. This is also called a <dfn>Multi-dimensional Array<dfn>.",
"<h4>Instructions</h4>",
"Create a nested array called <code>myArray</code>."
],
"challengeSeed": [
"// Example",
"var ourArray = [[\"the universe\", 42], [\"everything\", 101010]];",
"",
"// Only change code below this line.",
"var myArray = [];",
""
],
"tail": [
"if(typeof myArray !== \"undefined\"){(function(){return myArray;})();}"
],
"solutions": [
"var myArray = [[1,2,3]];"
],
"tests": [
"assert(Array.isArray(myArray) && myArray.some(Array.isArray), 'message: <code>myArray</code> should have at least one array nested within another array.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Anida un vector dentro de otro vector",
"descriptionEs": [
"También puedes anidar vectores dentro de otros vectores, como este: <code>[[\"Bulls\", 23], [\"White Sox\", 45]]</code>.",
"Ahora vamos a crear un vector anidado llamado <code>myArray</code>."
]
},
{
"id": "bg9997c9c79feddfaeb9bdef",
"title": "Access Array Data with Indexes",
"description": [
"We can access the data inside arrays using <code>indexes</code>.",
"Array indexes are written in the same bracket notation that strings use, except that instead of specifying a character, they are specifying an entry in the array. Like strings, arrays use <dfn>zero-based</dfn> indexing, so the first element in an array is element <code>0</code>.",
"<strong>Example</strong>",
"<blockquote>var array = [1,2,3];<br>array[0]; // equals 1<br>var data = array[1]; // equals 2</blockquote>",
"<h4>Instructions</h4>",
"Create a variable called <code>myData</code> and set it to equal the first value of <code>myArray</code>."
],
"challengeSeed": [
"// Example",
"var ourArray = [1,2,3];",
"var ourData = ourArray[0]; // equals 1",
"",
"// Setup",
"var myArray = [1,2,3];",
"",
"// Only change code below this line.",
""
],
"tail": [
"if(typeof myArray !== \"undefined\" && typeof myData !== \"undefined\"){(function(y,z){return 'myArray = ' + JSON.stringify(y) + ', myData = ' + JSON.stringify(z);})(myArray, myData);}"
],
"solutions": [
"var myArray = [1,2,3];\nvar myData = myArray[0];"
],
"tests": [
"assert((function(){if(typeof myArray != 'undefined' && typeof myData != 'undefined' && myArray[0] == myData){return true;}else{return false;}})(), 'message: The variable <code>myData</code> should equal the first value of <code>myArray</code>.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Accede a los datos de un vector mediante índices",
"descriptionEs": [
"Podemos acceder a los datos dentro de los vectores usando <code>índices</code>.",
"Los índices del vector se escriben en la misma notación con corchetes usado con cadenas, excepto que en lugar de especificar un caracter, especifican un elemento del vector.",
"Por ejemplo:",
"<code>var array = [1,2,3];</code>",
"<code>array[0]; //es igual a 1</code>",
"<code>var data = array[1];</code>",
"Crea una variable llamada <code>myData</ code> y asignale el primer valor del vector <code>myArray</code>."
]
},
{
"id": "cf1111c1c11feddfaeb8bdef",
"title": "Modify Array Data With Indexes",
"description": [
"Unlike strings, the entries of arrays are <dfn>mutable</dfn> and can be changed freely.",
"<strong>Example</strong>",
"<blockquote>var ourArray = [3,2,1];<br>ourArray[0] = 1; // equals [1,2,1]</blockquote>",
"<h4>Instructions</h4>",
"Modify the data stored at index <code>0</code> of <code>myArray</code> to a value of <code>3</code>."
],
"challengeSeed": [
"// Example",
"var ourArray = [1,2,3];",
"ourArray[1] = 3; // ourArray now equals [1,3,3].",
"",
"// Setup",
"var myArray = [1,2,3];",
"",
"// Only change code below this line.",
"",
""
],
"tail": [
"if(typeof myArray !== \"undefined\"){(function(){return myArray;})();}"
],
"solutions": [
"var myArray = [1,2,3];\nmyArray[0] = 3;"
],
"tests": [
"assert((function(){if(typeof myArray != 'undefined' && myArray[0] == 3 && myArray[1] == 2 && myArray[2] == 3){return true;}else{return false;}})(), 'message: <code>myArray</code> should now be [3,2,3].');",
"assert((function(){if(code.match(/myArray\\[0\\]\\s?=\\s?/g)){return true;}else{return false;}})(), 'message: You should be using correct index to modify the value in <code>myArray</code>.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Modifica datos de un vector usando índices",
"descriptionEs": [
"También podemos modificar los datos almacenados en vectores usando índices.",
"Por ejemplo:",
"<code>var ourArray = [3,2,1];</code>",
"<code>ourArray[0] = 1; // equals [1,2,1]</code>",
"Ahora establece el dato almacenado en el índice 0 de <code>myArray</code> para que sea el valor 3."
]
},
{
"id": "56592a60ddddeae28f7aa8e1",
"title": "Access Multi-Dimensional Arrays With Indexes",
"description": [
"One way to think of a <dfn>multi-dimensional</dfn> array, is as an <em>array of arrays</em>. When you use brackets to access your array, the first set of bracket refers to the entries in the outer-most array, and each subsequent level of brackets refers to the next level of entries inside.",
"<strong>Example</strong>",
"<blockquote>var arr = [<br> [1,2,3],<br> [4,5,6],<br> [7,8,9],<br> [[10,11,12], 13, 14]<br>];<br>arr[0]; // equals [1,2,3]<br>arr[1][2]; // equals 6<br>arr[3][0][1]; // equals 11</blockquote>",
"<h4>Instructions</h4>",
"Read from <code>myArray</code> using bracket notation so that myData is equal to <code>8</code>"
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Setup",
"var myArray = [[1,2,3], [4,5,6], [7,8,9], [[10,11,12], 13, 14]];",
"",
"// Only change code below this line.",
"var myData = myArray[0][0];",
""
],
"tail": [
"if(typeof myArray !== \"undefined\"){(function(){return \"myData: \" + myData + \" myArray: \" + JSON.stringify(myArray);})();}"
],
"solutions": [
"var myArray = [[1,2,3],[4,5,6], [7,8,9], [[10,11,12], 13, 14]];\nvar myData = myArray[2][1];"
],
"tests": [
"assert(myData === 8, 'message: <code>myData</code> should be equal to <code>8</code>.');",
"assert(/myArray\\[2\\]\\[1\\]/g.test(code), 'message: You should be using bracket notation to read the value from <code>myArray</code>.');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "bg9995c9c69feddfaeb9bdef",
"title": "Manipulate Arrays With push()",
"description": [
"An easy way to append data to the end of an array is via the <code>push()</code> function.",
"<code>.push()</code> takes one or more <dfn>parameter</dfn> and \"pushes\" it onto the end of the array.",
"<blockquote>var arr = [1,2,3];<br>arr.push(4);<br>// arr is now [1,2,3,4]</blockquote>",
"<h4>Instructions</h4>",
"Push <code>[\"dog\", 3]</code> onto the end of the <code>myArray</code> variable."
],
"challengeSeed": [
"// Example",
"var ourArray = [\"Stimpson\", \"J\", \"cat\"];",
"ourArray.push([\"happy\", \"joy\"]); ",
"// ourArray now equals [\"Stimpson\", \"J\", \"cat\", [\"happy\", \"joy\"]]",
"",
"// Setup",
"var myArray = [[\"John\", 23], [\"cat\", 2]];",
"",
"// Only change code below this line.",
"",
""
],
"tail": [
"(function(z){return 'myArray = ' + JSON.stringify(z);})(myArray);"
],
"solutions": [
"var myArray = [[\"John\", 23], [\"cat\", 2]];\nmyArray.push([\"dog\",3]);"
],
"tests": [
"assert((function(d){if(d[2] != undefined && d[0][0] == 'John' && d[0][1] == 23 && d[2][0] == 'dog' && d[2][1] == 3 && d[2].length == 2){return true;}else{return false;}})(myArray), 'message: <code>myArray</code> should now equal <code>[[\"John\", 23], [\"cat\", 2], [\"dog\", 3]]</code>.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Manipula vectores con push()",
"descriptionEs": [
"No sólo se pueden sacar datos del final de un vector con <code>pop()</code>, también puedes empujar (<code>push()</code>) datos al final del vector.",
"Empuja <code>[\"dog\", 3]</code> al final de la variable <code>myArray</code>."
]
},
{
"id": "bg9994c9c69feddfaeb9bdef",
"title": "Manipulate Arrays With pop()",
"description": [
"Another way to change the data in an array is with the <code>.pop()</code> function.",
"<code>.pop()</code> is used to \"pop\" a value off of the end of an array. We can store this \"popped off\" value by assigning it to a variable.",
"Any type of entry can be \"popped\" off of an array - numbers, strings, even nested arrays.",
"For example, for the code<br><code>var oneDown = [1, 4, 6].pop();</code><br>the variable <code>oneDown</code> now holds the value <code>6</code> and the array becomes <code>[1, 4]</code>.",
"<h4>Instructions</h4>",
"Use the <code>.pop()</code> function to remove the last item from <code>myArray</code>, assigning the \"popped off\" value to <code>removedFromMyArray</code>."
],
"challengeSeed": [
"// Example",
"var ourArray = [1,2,3];",
"var removedFromOurArray = ourArray.pop(); ",
"// removedFromOurArray now equals 3, and ourArray now equals [1,2]",
"",
"// Setup",
"var myArray = [[\"John\", 23], [\"cat\", 2]];",
"",
"// Only change code below this line.",
"var removedFromMyArray;",
"",
""
],
"tail": [
"(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);"
],
"solutions": [
"var myArray = [[\"John\", 23], [\"cat\", 2]];\nvar removedFromMyArray = myArray.pop();"
],
"tests": [
"assert((function(d){if(d[0][0] == 'John' && d[0][1] == 23 && d[2] == undefined){return true;}else{return false;}})(myArray), 'message: <code>myArray</code> should only contain <code>[[\"John\", 23]]</code>.');",
"assert((function(d){if(d[0] == 'cat' && d[1] == 2 && d[2] == undefined){return true;}else{return false;}})(removedFromMyArray), 'message: <code>removedFromMyArray</code> should only contain <code>[\"cat\", 2]</code>.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Manipula vectores con pop()",
"descriptionEs": [
"Otra forma de cambiar los datos en un vector es con la función <code>.pop()</code>.",
"<code>.pop()</code> se utiliza para \"sacar\" el valor final de un vector. Podemos almacenar el valor \"sacado\" asignando <code>pop</code> a una variable por ejemplo durante su declaración.",
"Todo tipo de datos puede ser \"sacado\" de un vector --números, cadenas, incluso los vectores anidadas.",
"Usa la función <code>.pop()</code> para sacar el último elemento de <code>myArray</code> y asigna ese valor \"sacado\" a <code>removedFromMyArray </code>."
]
},
{
"id": "bg9996c9c69feddfaeb9bdef",
"title": "Manipulate Arrays With shift()",
"description": [
"<code>pop()</code> always removes the last element of an array. What if you want to remove the first?",
"That's where <code>.shift()</code> comes in. It works just like <code>.pop()</code>, except it removes the first element instead of the last.",
"<h4>Instructions</h4>",
"Use the <code>.shift()</code> function to remove the first item from <code>myArray</code>, assigning the \"shifted off\" value to <code>removedFromMyArray</code>."
],
"challengeSeed": [
"// Example",
"var ourArray = [\"Stimpson\", \"J\", [\"cat\"]];",
"removedFromOurArray = ourArray.shift();",
"// removedFromOurArray now equals \"Stimpson\" and ourArray now equals [\"J\", [\"cat\"]].",
"",
"// Setup",
"var myArray = [[\"John\", 23], [\"dog\", 3]];",
"",
"// Only change code below this line.",
"var removedFromMyArray;",
"",
""
],
"tail": [
"(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);"
],
"solutions": [
"var myArray = [[\"John\", 23], [\"dog\", 3]];\n\n// Only change code below this line.\nvar removedFromMyArray = myArray.shift();"
],
"tests": [
"assert((function(d){if(d[0][0] == 'dog' && d[0][1] == 3 && d[1] == undefined){return true;}else{return false;}})(myArray), 'message: <code>myArray</code> should now equal <code>[[\"dog\", 3]]</code>.');",
"assert((function(d){if(d[0] === 'John' && d[1] === 23 && typeof removedFromMyArray === 'object'){return true;}else{return false;}})(removedFromMyArray), 'message: <code>removedFromMyArray</code> should contain <code>[\"John\", 23]</code>.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Manipula vectores con shift()",
"descriptionEs": [
"<code>pop()</code> siempre elimina el último elemento de un vector. ¿Qué pasa si quieres quitar el primero?",
"Ahí es donde entra <code>.shift()</code>. Funciona igual que <code>.pop ()</code>, excepto que elimina el primer elemento en lugar del pasado. ",
"Usa la función <code>.shift()</code> para eliminar el primer elemento de <code>myArray</code>, y el elemento que saques asignalo a <code>removedFromMyArra</code>"
]
},
{
"id": "bg9997c9c69feddfaeb9bdef",
"title": "Manipulate Arrays With unshift()",
"description": [
"Not only can you <code>shift</code> elements off of the beginning of an array, you can also <code>unshift</code> elements to the beginning of an array i.e. add elements in front of the array.",
"<code>.unshift()</code> works exactly like <code>.push()</code>, but instead of adding the element at the end of the array, <code>unshift()</code> adds the element at the beginning of the array.",
"<h4>Instructions</h4>",
"Add <code>[\"Paul\",35]</code> to the beginning of the <code>myArray</code> variable using <code>unshift()</code>."
],
"challengeSeed": [
"// Example",
"var ourArray = [\"Stimpson\", \"J\", \"cat\"];",
"ourArray.shift(); // ourArray now equals [\"J\", \"cat\"]",
"ourArray.unshift(\"Happy\"); ",
"// ourArray now equals [\"Happy\", \"J\", \"cat\"]",
"",
"// Setup",
"var myArray = [[\"John\", 23], [\"dog\", 3]];",
"myArray.shift();",
"",
"// Only change code below this line.",
"",
""
],
"tail": [
"(function(y, z){return 'myArray = ' + JSON.stringify(y);})(myArray);"
],
"solutions": [
"var myArray = [[\"John\", 23], [\"dog\", 3]];\nmyArray.shift();\nmyArray.unshift([\"Paul\", 35]);"
],
"tests": [
"assert((function(d){if(typeof d[0] === \"object\" && d[0][0].toLowerCase() == 'paul' && d[0][1] == 35 && d[1][0] != undefined && d[1][0] == 'dog' && d[1][1] != undefined && d[1][1] == 3){return true;}else{return false;}})(myArray), 'message: <code>myArray</code> should now have [[\"Paul\", 35], [\"dog\", 3]].');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Manipula vectores con unshift()",
"descriptionEs": [
"No sólo se puedes <code>correr</code> (shift) elementos del comienzo de un vector, también puedes <code>descorrerlos</code> (unshift) al comienzo.",
"<code>unshift()</code> funciona exactamente igual que <code>push()</code>, pero en lugar de añadir el elemento al final del vector, <code>unshift()</code> añade el elemento al comienzo del vector. ",
"Añade <code>\"Paul\"</code> al comienzo de la variable <code>myArray</code> usando <code>unshift()</code>."
]
},
{
"id": "56533eb9ac21ba0edf2244bc",
"title": "Shopping List",
"description": [
"Create a shopping list in the variable <code>myList</code>. 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.",
"<code>[\"Chocolate Bar\", 15]</code>",
"There should be at least 5 sub-arrays in the list."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"var myList = [];",
"",
""
],
"tail": [
"var count = 0;",
"var isArray = false;",
"var hasString = false;",
"var hasNumber = false;",
"(function(list){",
" if(Array.isArray(myList)) {",
" isArray = true;",
" if(myList.length > 0) {",
" hasString = true;",
" hasNumber = true;",
" myList.forEach(function(elem) {",
" if(typeof elem[0] !== 'string') {",
" hasString = false;",
" }",
" if(typeof elem[1] !== 'number') {",
" hasNumber = false;",
" }",
" });",
" }",
" count = myList.length;",
" return JSON.stringify(myList);",
" } else {",
" return \"myList is not an array\";",
" }",
"",
"})(myList);"
],
"solutions": [
"var myList = [\n [\"Candy\", 10],\n [\"Potatoes\", 12],\n [\"Eggs\", 12],\n [\"Catfood\", 1],\n [\"Toads\", 9]\n];"
],
"tests": [
"assert(isArray, 'message: <code>myList</code> should be an array');",
"assert(hasString, 'message: The first elements in each of your sub-arrays must all be strings');",
"assert(hasNumber, 'message: The second elements in each of your sub-arrays must all be numbers');",
"assert(count > 4, 'message: You must have at least 5 items in your list');"
],
"type": "checkpoint",
"challengeType": 1
},
{
"id": "bg9997c9c89feddfaeb9bdef",
"title": "Write Reusable JavaScript with Functions",
"description": [
"In JavaScript, we can divide up our code into reusable parts called <dfn>functions</dfn>.",
"Here's an example of a function:",
"<blockquote>function functionName() {<br> console.log(\"Hello World\");<br>}</blockquote>",
"You can call or <dfn>invoke</dfn> this function by using its name followed by parentheses, like this:",
"<code>functionName();</code>",
"Each time the function is called it will print out the message <code>\"Hello World\"</code> on the dev console. All of the code between the curly braces will be executed every time the function is called.",
"<h4>Instructions</h4>",
"<ol><li>Create a function called <code>myFunction</code> which prints <code>\"Hi World\"</code> to the dev console.</li><li>Call the function.</li></ol>"
],
"challengeSeed": [
"// Example",
"function ourFunction() {",
" console.log(\"Heyya, World\");",
"}",
"",
"ourFunction();",
"",
"// Only change code below this line",
"",
""
],
"tail": [
"var logOutput = \"\";",
"var originalConsole = console",
"function capture() {",
" var nativeLog = console.log;",
" console.log = function (message) {",
" if(message && message.trim) logOutput = message.trim();",
" if(nativeLog.apply) {",
" nativeLog.apply(originalConsole, arguments);",
" } else {",
" var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');",
" nativeLog(nativeMsg);",
" }",
" };",
"}",
"",
"function uncapture() {",
" console.log = originalConsole.log;",
"}",
"",
"if (typeof myFunction !== \"function\") { ",
" (function() { return \"myFunction is not defined\"; })();",
"} else {",
" capture();",
" myFunction(); ",
" uncapture();",
" (function() { return logOutput || \"console.log never called\"; })();",
"}"
],
"solutions": [
"function myFunction() {\n console.log(\"Hi World\");\n}\nmyFunction();"
],
"tests": [
"assert(typeof myFunction === 'function', 'message: <code>myFunction</code> should be a function');",
"assert(\"Hi World\" === logOutput, 'message: <code>myFunction</code> should output \"Hi World\" to the dev console');",
"assert(/^\\s*myFunction\\(\\)\\s*;/m.test(code), 'message: Call <code>myFunction</code> after you define it');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Escribe código Javascript reutilizable con funciones",
"descriptionEs": [
"En JavaScript, podemos dividir nuestro código en partes reutilizables llamadas funciones.",
"He aquí un ejemplo de una función:",
"<code>function nombreDeFuncion(a, b) {</code>",
"<code>& nbsp; & nbsp; return a + b;</code>",
"<code>}</code>",
"Después de escribir las líneas anteriores en nuestro código, podemos pasar valores a nuestra función y el resultado que sigue a la instrucción <code>return</code> será retornado.",
"Por ejemplo, podemos pasar los números <code>4</code> y <code>2</code> al \"llamar\" la función más adelante en nuestro código, así: <code>nombreDeFuncion(4, 2)</ code >. ",
"En este ejemplo, la función devolverá el número <code>6</code>, ya que es el resultado de <code>4 + 2</code>.",
"Crea y llama una función de nombre <code>myFunction</code> que devuelva la suma de <code>a</code> y <code>b</code>."
]
},
{
"id": "56533eb9ac21ba0edf2244bd",
"title": "Passing Values to Functions with Arguments",
"description": [
"<dfn>Parameters</dfn> are variables that act as placeholders for the values that are to be input to a function when it is called. When a function is defined, it is typically defined along with one or more parameters. The actual values that are input (or <dfn>\"passed\"</dfn>) into a function when it is called are known as <dfn>arguments</dfn>.",
"Here is a function with two parameters, <code>param1</code> and <code>param2</code>:",
"<blockquote>function testFun(param1, param2) {<br> console.log(param1, param2);<br>}</blockquote>",
"Then we can call <code>testFun</code>:",
"<code>testFun(\"Hello\", \"World\");</code>",
"We have passed two arguments, <code>\"Hello\"</code> and <code>\"World\"</code>. Inside the function, <code>param1</code> will equal \"Hello\" and <code>param2</code> will equal \"World\". Note that you could call <code>testFun</code> again with different arguments and the parameters would take on the value of the new arguments.",
"<h4>Instructions</h4>",
"<ol><li>Create a function called <code>myFunction</code> that accepts two arguments and outputs their sum to the dev console.</li><li>Call the function.</li></ol>"
],
"releasedOn": "January 1, 2016",
"head": [
"var logOutput = \"\";",
"var originalConsole = console",
"function capture() {",
" var nativeLog = console.log;",
" console.log = function (message) {",
" if(message) logOutput = JSON.stringify(message).trim();",
" if(nativeLog.apply) {",
" nativeLog.apply(originalConsole, arguments);",
" } else {",
" var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');",
" nativeLog(nativeMsg);",
" }",
" };",
"}",
"",
"function uncapture() {",
" console.log = originalConsole.log;",
"}",
"",
"capture();"
],
"challengeSeed": [
"// Example",
"function ourFunction(a, b) {",
" console.log(a - b);",
"}",
"ourFunction(10, 5); // Outputs 5",
"",
"// Only change code below this line.",
"",
""
],
"tail": [
"uncapture();",
"",
"if (typeof myFunction !== \"function\") { ",
" (function() { return \"myFunction is not defined\"; })();",
"} else {",
" (function() { return logOutput || \"console.log never called\"; })();",
"}"
],
"solutions": [
"function myFunction(a, b) {\n console.log(a + b);\n}\nmyFunction(10, 5);"
],
"tests": [
"assert(typeof myFunction === 'function', 'message: <code>myFunction</code> should be a function');",
"if(typeof myFunction === \"function\") { capture(); myFunction(1,2); uncapture(); } assert(logOutput == 3, 'message: <code>myFunction(1,2)</code> should output <code>3</code>');",
"if(typeof myFunction === \"function\") { capture(); myFunction(7,9); uncapture(); } assert(logOutput == 16, 'message: <code>myFunction(7,9)</code> should output <code>16</code>');",
"assert(/^\\s*myFunction\\s*\\([\\w\\W]+\\)\\s*;/m.test(code), 'message: Call <code>myFunction</code> after you define it.');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244be",
"title": "Global Scope and Functions",
"description": [
"In JavaScript, <dfn>scope</dfn> refers to the visibility of variables. Variables which are defined outside of a function block have <dfn>Global</dfn> scope. This means, they can be seen everywhere in your JavaScript code.",
"Variables which are used without the <code>var</code> keyword are automatically created in the <code>global</code> scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with <code>var</code>.",
"<h4>Instructions</h4>",
"Declare a <code>global</code> variable <code>myGlobal</code> outside of any function. Initialize it to have a value of <code>10</code> ",
"Inside function <code>fun1</code>, assign <code>5</code> to <code>oopsGlobal</code> <strong><em>without</em></strong> using the <code>var</code> keyword."
],
"releasedOn": "January 1, 2016",
"head": [
"var logOutput = \"\";",
"var originalConsole = console",
"function capture() {",
" var nativeLog = console.log;",
" console.log = function (message) {",
" logOutput = message;",
" if(nativeLog.apply) {",
" nativeLog.apply(originalConsole, arguments);",
" } else {",
" var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');",
" nativeLog(nativeMsg);",
" }",
" };",
"}",
"",
"function uncapture() {",
" console.log = originalConsole.log;",
"}",
"var oopsGlobal;",
"capture();"
],
"challengeSeed": [
"// Declare your variable here",
"",
"",
"function fun1() {",
" // Assign 5 to oopsGlobal Here",
" ",
"}",
"",
"// Only change code above this line",
"function fun2() {",
" var output = \"\";",
" if (typeof myGlobal != \"undefined\") {",
" output += \"myGlobal: \" + myGlobal;",
" }",
" if (typeof oopsGlobal != \"undefined\") {",
" output += \" oopsGlobal: \" + oopsGlobal;",
" }",
" console.log(output);",
"}"
],
"tail": [
"fun1();",
"fun2();",
"uncapture();",
"(function() { return logOutput || \"console.log never called\"; })();"
],
"solutions": [
"// Declare your variable here\nvar myGlobal = 10;\n\nfunction fun1() {\n // Assign 5 to oopsGlobal Here\n oopsGlobal = 5;\n}\n\n// Only change code above this line\nfunction fun2() {\n var output = \"\";\n if(typeof myGlobal != \"undefined\") {\n output += \"myGlobal: \" + myGlobal;\n }\n if(typeof oopsGlobal != \"undefined\") {\n output += \" oopsGlobal: \" + oopsGlobal;\n }\n console.log(output);\n}"
],
"tests": [
"assert(typeof myGlobal != \"undefined\", 'message: <code>myGlobal</code> should be defined');",
"assert(myGlobal === 10, 'message: <code>myGlobal</code> should have a value of <code>10</code>');",
"assert(/var\\s+myGlobal/.test(code), 'message: <code>myGlobal</code> should be declared using the <code>var</code> keyword');",
"assert(typeof oopsGlobal != \"undefined\" && oopsGlobal === 5, 'message: <code>oopsGlobal</code> should have a value of <code>5</code>');",
"assert(!/var\\s+oopsGlobal/.test(code), 'message: Do not declare <code>oopsGlobal</code> using the <code>var</code> keyword');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244bf",
"title": "Local Scope and Functions",
"description": [
"Variables which are declared within a function, as well as the function parameters have <dfn>local</dfn> scope. That means, they are only visible within that function.",
"Here is a function <code>myTest</code> with a local variable called <code>loc</code>.",
"<blockquote>function myTest() {<br> var loc = \"foo\";<br> console.log(loc);<br>}<br>myTest(); // \"foo\"<br>console.log(loc); // \"undefined\"</blockquote>",
"<code>loc</code> is not defined outside of the function.",
"<h4>Instructions</h4>",
"Declare a local variable <code>myVar</code> inside <code>myFunction</code>"
],
"releasedOn": "January 1, 2016",
"head": [
"var logOutput = \"\";",
"var originalConsole = console",
"function capture() {",
" var nativeLog = console.log;",
" console.log = function (message) {",
" logOutput = message;",
" if(nativeLog.apply) {",
" nativeLog.apply(originalConsole, arguments);",
" } else {",
" var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');",
" nativeLog(nativeMsg);",
" }",
" };",
"}",
"",
"function uncapture() {",
" console.log = originalConsole.log;",
"}",
""
],
"challengeSeed": [
"function myFunction() {",
" 'use strict';",
" ",
" ",
" console.log(myVar);",
"}",
"myFunction();",
"",
"// run and check the console ",
"// myVar is not defined outside of myFunction",
"console.log(myVar);",
"",
"// now remove the console log line to pass the test",
""
],
"tail": [
"typeof myFunction === 'function' && (capture(), myFunction(), uncapture());",
"(function() { return logOutput || \"console.log never called\"; })();"
],
"solutions": [
"function myFunction() {\n 'use strict';\n \n var myVar;\n console.log(myVar);\n}\nmyFunction();"
],
"tests": [
"assert(typeof myVar === 'undefined', 'message: No global <code>myVar</code> variable');",
"assert(/var\\s+myVar/.test(code), 'message: Add a local <code>myVar</code> variable');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244c0",
"title": "Global vs. Local Scope in Functions",
"description": [
"It is possible to have both <dfn>local</dfn> and <dfn>global</dfn> variables with the same name. When you do this, the <code>local</code> variable takes precedence over the <code>global</code> variable.",
"In this example:",
"<blockquote>var someVar = \"Hat\";<br>function myFun() {<br> var someVar = \"Head\";<br> return someVar;<br>}</blockquote>",
"The function <code>myFun</code> will return <code>\"Head\"</code> because the <code>local</code> version of the variable is present.",
"<h4>Instructions</h4>",
"Add a local variable to <code>myFunction</code> to override the value of <code>outerWear</code> with <code>\"sweater\"</code>."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Setup",
"var outerWear = \"T-Shirt\";",
"",
"function myFunction() {",
" // Only change code below this line",
" ",
" ",
" ",
" // Only change code above this line",
" return outerWear;",
"}",
"",
"myFunction();"
],
"solutions": [
"var outerWear = \"T-Shirt\";\nfunction myFunction() {\n var outerWear = \"sweater\";\n return outerWear;\n}"
],
"tests": [
"assert(outerWear === \"T-Shirt\", 'message: Do not change the value of the global <code>outerWear</code>');",
"assert(myFunction() === \"sweater\", 'message: <code>myFunction</code> should return <code>\"sweater\"</code>');",
"assert(/return outerWear/.test(code), 'message: Do not change the return statement');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244c2",
"title": "Return a Value from a Function with Return",
"description": [
"We can pass values into a function with <dfn>arguments</dfn>. You can use a <code>return</code> statement to send a value back out of a function.",
"<strong>Example</strong>",
"<blockquote>function plusThree(num) {<br> return num + 3;<br>}<br>var answer = plusThree(5); // 8</blockquote>",
"<code>plusThree</code> takes an <dfn>argument</dfn> for <code>num</code> and returns a value equal to <code>num + 3</code>.",
"<h4>Instructions</h4>",
"Create a function <code>timesFive</code> that accepts one argument, multiplies it by <code>5</code>, and returns the new value."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Example",
"function minusSeven(num) {",
" return num - 7;",
"}",
"",
"// Only change code below this line",
"",
""
],
"tail": [
"(function() { if(typeof timesFive === 'function'){ return \"timesfive(5) === \" + timesFive(5); } else { return \"timesFive is not a function\"} })();"
],
"solutions": [
"function timesFive(num) {\n return num * 5;\n}"
],
"tests": [
"assert(typeof timesFive === 'function', 'message: <code>timesFive</code> should be a function');",
"assert(timesFive(5) === 25, 'message: <code>timesFive(5)</code> should return <code>25</code>');",
"assert(timesFive(2) === 10, 'message: <code>timesFive(2)</code> should return <code>10</code>');",
"assert(timesFive(0) === 0, 'message: <code>timesFive(0)</code> should return <code>0</code>');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244c3",
"title": "Assignment with a Returned Value",
"description": [
"If you'll recall from our discussion of <a href=\"waypoint-storing-values-with-the-equal-operator\" target=\"_blank\">Storing Values with the Equal Operator</a>, everything to the right of the equal sign is resolved before the value is assigned. This means we can take the return value of a function and assign it to a variable.",
"Assume we have pre-defined a function <code>sum</code> which adds two numbers together, then: ",
"<code>ourSum = sum(5, 12);</code>",
"will call <code>sum</code> function, which returns a value of <code>17</code> and assigns it to <code>ourSum</code> variable.",
"<h4>Instructions</h4>",
"Call the <code>process</code> function with an argument of <code>7</code> and assign its return value to the variable <code>processed</code>."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Example",
"var changed = 0;",
"",
"function change(num) {",
" return (num + 5) / 3;",
"}",
"",
"changed = change(10);",
"",
"// Setup",
"var processed = 0;",
"",
"function process(num) {",
" return (num + 3) / 5;",
"}",
"",
"// Only change code below this line",
"",
""
],
"tail": [
"(function(){return \"processed = \" + processed})();"
],
"solutions": [
"var processed = 0;\n\nfunction process(num) {\n return (num + 3) / 5;\n}\n\nprocessed = process(7);"
],
"tests": [
"assert(processed === 2, 'message: <code>processed</code> should have a value of <code>2</code>');",
"assert(/processed\\s*=\\s*process\\(\\s*7\\s*\\)\\s*;/.test(code), 'message: You should assign <code>process</code> to <code>processed</code>');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244c6",
"title": "Stand in Line",
"description": [
"In Computer Science a <dfn>queue</dfn> is an abstract <dfn>Data Structure</dfn> where items are kept in order. New items can be added at the back of the <code>queue</code> and old items are taken off from the front of the <code>queue</code>.",
"Write a function <code>queue</code> which takes an array (<code>arr</code>) and a number (<code>item</code>) as arguments. Add the number to the end of the array, then remove the first element of array. The queue function should then return the element that was removed."
],
"releasedOn": "January 1, 2016",
"head": [
"var logOutput = [];",
"var originalConsole = console",
"function capture() {",
" var nativeLog = console.log;",
" console.log = function (message) {",
" logOutput.push(message);",
" if(nativeLog.apply) {",
" nativeLog.apply(originalConsole, arguments);",
" } else {",
" var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');",
" nativeLog(nativeMsg);",
" }",
" };",
"}",
"",
"function uncapture() {",
" console.log = originalConsole.log;",
"}",
"",
"capture();"
],
"challengeSeed": [
"function queue(arr, item) {",
" // Your code here",
" ",
" return item; // Change this line",
"}",
"",
"// Test Setup",
"var testArr = [1,2,3,4,5];",
"",
"// Display Code",
"console.log(\"Before: \" + JSON.stringify(testArr));",
"console.log(queue(testArr, 6)); // Modify this line to test",
"console.log(\"After: \" + JSON.stringify(testArr));"
],
"tail": [
"uncapture();",
"testArr = [1,2,3,4,5];",
"(function() { return logOutput.join(\"\\n\");})();"
],
"solutions": [
"var testArr = [ 1,2,3,4,5];\n\nfunction queue(arr, item) {\n arr.push(item);\n return arr.shift();\n}"
],
"tests": [
"assert(queue([],1) === 1, 'message: <code>queue([], 1)</code> should return <code>1</code>');",
"assert(queue([2],1) === 2, 'message: <code>queue([2], 1)</code> should return <code>2</code>');",
"assert(queue([5,6,7,8,9],1) === 5, 'message: <code>queue([5,6,7,8,9], 1)</code> should return <code>5</code>');",
"queue(testArr, 10); assert(testArr[4] === 10, 'message: After <code>queue(testArr, 10)</code>, <code>myArr[4]</code> should be <code>10</code>');"
],
"type": "checkpoint",
"challengeType": 1
},
{
"id": "bd7123c9c441eddfaeb5bdef",
"title": "Understanding Boolean Values",
"description": [
"Another data type is the <dfn>Boolean</dfn>. <code>Booleans</code> may only be one of two values: <code>true</code> or <code>false</code>. They are basically little on-off switches, where <code>true</code> is \"on\" and <code>false</code> is \"off.\" These two states are mutually exclusive.",
"<strong>Note</strong><br><code>Boolean</code> values are never written with quotes. The <code>strings</code> <code>\"true\"</code> and <code>\"false\"</code> are not <code>Boolean</code> and have no special meaning in JavaScript.",
"<h4>Instructions</h4>",
"Modify the <code>welcomeToBooleans</code> function so that it returns <code>true</code> instead of <code>false</code> when the run button is clicked."
],
"challengeSeed": [
"function welcomeToBooleans() {",
"",
"// Only change code below this line.",
"",
"return false; // Change this line",
"",
"// Only change code above this line.",
"}"
],
"tail": [
"welcomeToBooleans();"
],
"solutions": [
"function welcomeToBooleans() {\n return true; // Change this line\n}"
],
"tests": [
"assert(typeof welcomeToBooleans() === 'boolean', 'message: The <code>welcomeToBooleans()</code> function should return a boolean &#40;true/false&#41; value.');",
"assert(welcomeToBooleans() === true, 'message: <code>welcomeToBooleans()</code> should return true.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Entiende los valores booleanos",
"descriptionEs": [
"En informática las <code>estructuras de datos</code> son cosas que contienen datos. JavaScript tiene siete de estas. Por ejemplo, la estructura de datos <code>Número</code> contiene números. ",
"Vamos a aprender acerca de la estructura de datos más básica de todas: el <code>Boolean</code>. Los booleanos sólo puede contener el valor verdadero o el valor falso. Son básicamente pequeños interruptores de encendido y apagado. ",
"Vamos a modificar nuestra función <code>welcomeToBooleans</code> para que devuelva <code>true</code> en lugar de <code>false</code> cuando se pulse el botón de ejecución."
]
},
{
"id": "cf1111c1c12feddfaeb3bdef",
"title": "Use Conditional Logic with If Statements",
"description": [
"<code>If</code> statements are used to make decisions in code. The keyword <code>if</code> tells JavaScript to execute the code in the curly braces under certain conditions, defined in the parentheses. These conditions are known as <code>Boolean</code> conditions because they may only be <code>true</code> or <code>false</code>.",
"When the condition evaluates to <code>true</code>, the program executes the statement inside the curly braces. When the Boolean condition evaluates to <code>false</code>, the statement inside the curly braces will not execute.",
"<strong>Pseudocode</strong>",
"<blockquote>if (<i>condition is true</i>) {<br> <i>statement is executed</i><br>}</blockquote>",
"<strong>Example</strong>",
"<blockquote>function test (myCondition) {<br> if (myCondition) {<br> return \"It was true\";<br> }<br> return \"It was false\";<br>}<br>test(true); // returns \"It was true\"<br>test(false); // returns \"It was false\"</blockquote>",
"When <code>test</code> is called with a value of <code>true</code>, the <code>if</code> statement evaluates <code>myCondition</code> to see if it is <code>true</code> or not. Since it is <code>true</code>, the function returns <code>\"It was true\"</code>. When we call <code>test</code> with a value of <code>false</code>, <code>myCondition</code> is <em>not</em> <code>true</code> and the statement in the curly braces is not executed and the function returns <code>\"It was false\"</code>.",
"<h4>Instructions</h4>",
"Create an <code>if</code> statement inside the function to return <code>\"That was true\"</code> if the parameter <code>wasThatTrue</code> is <code>true</code> and return <code>\"That was false\"</code> otherwise."
],
"challengeSeed": [
"// Example",
"function ourFunction(isItTrue) {",
" if (isItTrue) { ",
" return \"Yes, it's true\";",
" }",
" return \"No, it's false\";",
"}",
"",
"// Setup",
"function myFunction(wasThatTrue) {",
"",
" // Only change code below this line.",
" ",
" ",
" ",
" // Only change code above this line.",
"",
"}",
"",
"// Change this value to test",
"myFunction(true);"
],
"solutions": [
"function myFunction(wasThatTrue) {\n if (wasThatTrue) {\n return \"That was true\";\n }\n return \"That was false\";\n}"
],
"tests": [
"assert(typeof myFunction === \"function\", 'message: <code>myFunction</code> should be a function');",
"assert(typeof myFunction(true) === \"string\", 'message: <code>myFunction(true)</code> should return a string');",
"assert(typeof myFunction(false) === \"string\", 'message: <code>myFunction(false)</code> should return a string');",
"assert(myFunction(true) === \"That was true\", 'message: <code>myFunction(true)</code> should return \"That was true\"');",
"assert(myFunction(false) === \"That was false\", 'message: <code>myFunction(false)</code> should return \"That was false\"');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Usa lógica condicional con instrucciones if y else",
"descriptionEs": [
"Podemos usar instrucciones <code>if</code> (\"if\" es \"si\" en español) en JavaScript para ejecutar código sólo cuando cierta condición se cumpla.",
"Las instrucciones <code>if</code> requieren evaluar algún tipo de condición booleana.",
"Por ejemplo:",
"<code>if (1 === 2) {</code>",
"<code>&nbsp;&nbsp;return true;</code>",
"<code>} else {</code>",
"<code>&nbsp;&nbsp;return false;</code>",
"<code>}</code>",
"Vamos a usar la instrucción <code>if</code> con <code>else</code> (\"else\" puede traducirse como \"de lo contrario\") para hacer un juego de cara o sello.",
"Crea una instrucción <code>if</code> con <code>else</code> que retorne la cadena <code>\"heads\"</code> si la variable <code>flip</code> es cero, o bien que retorne <code >\"tails\"</code> si la variable <code>flip</code> no es cero. "
]
},
{
"id": "56533eb9ac21ba0edf2244d0",
"title": "Comparison with the Equality Operator",
"description": [
"There are many <dfn>Comparison Operators</dfn> in JavaScript. All of these operators return a boolean <code>true</code> or <code>false</code> value.",
"The most basic operator is the equality operator <code>==</code>. The equality operator compares two values and returns <code>true</code> if they're equivalent or <code>false</code> if they are not. Note that equality is different from assignment (<code>=</code>), which assigns the value at the right of the operator to a variable in the left.",
"<blockquote>function equalityTest(myVal) {<br> if (myVal == 10) {<br> return \"Equal\";<br> }<br> return \"Not Equal\";<br>}</blockquote>",
"If <code>myVal</code> is equal to <code>10</code>, the equality operator returns <code>true</code>, so the code in the curly braces will execute, and the function will return <code>\"Equal\"</code>. Otherwise, the function will return <code>\"Not Equal\"</code>.",
"In order for JavaScript to compare two different <code>data types</code> (for example, <code>numbers</code> and <code>strings</code>), it must convert one type to another. Once it does, however, it can compare terms as follows:",
"<blockquote> 1 == 1 // true<br> 1 == 2 // false<br> 1 == '1' // true<br> \"3\" == 3 // true</blockquote>",
"<h4>Instructions</h4>",
"Add the <code>equality operator</code> to the indicated line so that the function will return \"Equal\" when <code>val</code> is equivalent to <code>12</code>"
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Setup",
"function myTest(val) {",
" if (val) { // Change this line",
" return \"Equal\";",
" }",
" return \"Not Equal\";",
"}",
"",
"// Change this value to test",
"myTest(10);"
],
"solutions": [
"function myTest(val) {\n if (val == 12) {\n return \"Equal\";\n }\n return \"Not Equal\";\n}"
],
"tests": [
"assert(myTest(10) === \"Not Equal\", 'message: <code>myTest(10)</code> should return \"Not Equal\"');",
"assert(myTest(12) === \"Equal\", 'message: <code>myTest(12)</code> should return \"Equal\"');",
"assert(myTest(\"12\") === \"Equal\", 'message: <code>myTest(\"12\")</code> should return \"Equal\"');",
"assert(code.match(/val\\s*==[\\s'\"\\d]+/g).length > 0, 'message: You should use the <code>==</code> operator');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244d1",
"title": "Comparison with the Strict Equality Operator",
"description": [
"Strict equality (<code>===</code>) is the counterpart to the equality operator (<code>==</code>). Unlike the equality operator, strict equality tests both the <code>data type</code> and value of the compared elements.",
"<strong>Examples</strong>",
"<blockquote>3 === 3 // true<br>3 === '3' // false</blockquote>",
"In the second example, <code>3</code> is a <code>Number</code> type and <code>'3'</code> is a <code>String</code> type.",
"<h4>Instructions</h4>",
"Use strict equality operator in <code>if</code> statement so the function will return \"Equal\" when <code>val</code> is strictly equal to <code>7</code>"
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Setup",
"function myTest(val) {",
" if (val) { // Change this line",
" return \"Equal\";",
" }",
" return \"Not Equal\";",
"}",
"",
"// Change this value to test",
"myTest(10);"
],
"solutions": [
"function myTest(val) {\n if (val === 7) {\n return \"Equal\";\n }\n return \"Not Equal\";\n}"
],
"tests": [
"assert(myTest(10) === \"Not Equal\", 'message: <code>myTest(10)</code> should return \"Not Equal\"');",
"assert(myTest(7) === \"Equal\", 'message: <code>myTest(7)</code> should return \"Equal\"');",
"assert(myTest(\"7\") === \"Not Equal\", 'message: <code>myTest(\"7\")</code> should return \"Not Equal\"');",
"assert(code.match(/val\\s*===\\s*\\d+/g).length > 0, 'message: You should use the <code>===</code> operator');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244d2",
"title": "Comparison with the Inequality Operator",
"description": [
"The inequality operator (<code>!=</code>) is the opposite of the equality operator. It means \"Not Equal\" and returns <code>false</code> where equality would return <code>true</code> and <em>vice versa</em>. Like the equality operator, the inequality operator will convert data types of values while comparing.",
"<strong>Examples</strong>",
"<blockquote>1 != 2 // true<br>1 != \"1\" // false<br>1 != '1' // false<br>1 != true // false<br>0 != false // false</blockquote>",
"<h4>Instructions</h4>",
"Add the inequality operator <code>!=</code> in the <code>if</code> statement so that the function will return \"Not Equal\" when <code>val</code> is not equivalent to <code>99</code>"
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Setup",
"function myTest(val) {",
" if (val) { // Change this line",
" return \"Not Equal\";",
" }",
" return \"Equal\";",
"}",
"",
"// Change this value to test",
"myTest(10);"
],
"solutions": [
"function myTest(val) {\n if (val != 99) {\n return \"Not Equal\";\n }\n return \"Equal\";\n}"
],
"tests": [
"assert(myTest(99) === \"Equal\", 'message: <code>myTest(99)</code> should return \"Equal\"');",
"assert(myTest(\"99\") === \"Equal\", 'message: <code>myTest(\"99\")</code> should return \"Equal\"');",
"assert(myTest(12) === \"Not Equal\", 'message: <code>myTest(12)</code> should return \"Not Equal\"');",
"assert(myTest(\"12\") === \"Not Equal\", 'message: <code>myTest(\"12\")</code> should return \"Not Equal\"');",
"assert(myTest(\"bob\") === \"Not Equal\", 'message: <code>myTest(\"bob\")</code> should return \"Not Equal\"');",
"assert(code.match(/val\\s*!=\\s*\\d+/g).length > 0, 'message: You should use the <code>!=</code> operator');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244d3",
"title": "Comparison with the Strict Inequality Operator",
"description": [
"The strict inequality operator (<code>!==</code>) is the opposite of the strict equality operator. It means \"Strictly Not Equal\" and returns <code>false</code> where strict equality would return <code>true</code> and <em>vice versa</em>. Strict inequality will not convert data types.",
"<strong>Examples</strong>",
"<blockquote>3 !== 3 // false<br>3 !== '3' // true<br>4 !== 3 // true</blockquote>",
"<h4>Instructions</h4>",
"Add the <code>strict inequality operator</code> to the <code>if</code> statement so the function will return \"Not Equal\" when <code>val</code> is not strictly equal to <code>17</code>"
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Setup",
"function myTest(val) {",
" // Only Change Code Below this Line",
" ",
" if (val) {",
"",
" // Only Change Code Above this Line",
"",
" return \"Not Equal\";",
" }",
" return \"Equal\";",
"}",
"",
"// Change this value to test",
"myTest(10);"
],
"solutions": [
"function myTest(val) {\n if (val !== 17) {\n return \"Not Equal\";\n }\n return \"Equal\";\n}"
],
"tests": [
"assert(myTest(17) === \"Equal\", 'message: <code>myTest(17)</code> should return \"Equal\"');",
"assert(myTest(\"17\") === \"Not Equal\", 'message: <code>myTest(\"17\")</code> should return \"Not Equal\"');",
"assert(myTest(12) === \"Not Equal\", 'message: <code>myTest(12)</code> should return \"Not Equal\"');",
"assert(myTest(\"bob\") === \"Not Equal\", 'message: <code>myTest(\"bob\")</code> should return \"Not Equal\"');",
"assert(code.match(/val\\s*!==\\s*\\d+/g).length > 0, 'message: You should use the <code>!==</code> operator');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244d4",
"title": "Comparison with the Greater Than Operator",
"description": [
"The greater than operator (<code>&gt;</code>) compares the values of two numbers. If the number to the left is greater than the number to the right, it returns <code>true</code>. Otherwise, it returns <code>false</code>.",
"Like the equality operator, greater than operator will convert data types of values while comparing.",
"<strong>Examples</strong>",
"<blockquote> 5 > 3 // true<br> 7 > '3' // true<br> 2 > 3 // false<br>'1' > 9 // false</blockquote>",
"<h4>Instructions</h4>",
"Add the <code>greater than</code> operator to the indicated lines so that the return statements make sense."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"function myTest(val) {",
" if (val) { // Change this line",
" return \"Over 100\";",
" }",
" ",
" if (val) { // Change this line",
" return \"Over 10\";",
" }",
"",
" return \"10 or Under\";",
"}",
"",
"// Change this value to test",
"myTest(10);"
],
"solutions": [
"function myTest(val) {\n if (val > 100) { // Change this line\n return \"Over 100\";\n }\n if (val > 10) { // Change this line\n return \"Over 10\";\n }\n return \"10 or Under\";\n}"
],
"tests": [
"assert(myTest(0) === \"10 or Under\", 'message: <code>myTest(0)</code> should return \"10 or Under\"');",
"assert(myTest(10) === \"10 or Under\", 'message: <code>myTest(10)</code> should return \"10 or Under\"');",
"assert(myTest(11) === \"Over 10\", 'message: <code>myTest(11)</code> should return \"Over 10\"');",
"assert(myTest(99) === \"Over 10\", 'message: <code>myTest(99)</code> should return \"Over 10\"');",
"assert(myTest(100) === \"Over 10\", 'message: <code>myTest(100)</code> should return \"Over 10\"');",
"assert(myTest(101) === \"Over 100\", 'message: <code>myTest(101)</code> should return \"Over 100\"');",
"assert(myTest(150) === \"Over 100\", 'message: <code>myTest(150)</code> should return \"Over 100\"');",
"assert(code.match(/val\\s*>\\s*('|\")*\\d+('|\")*/g).length > 1, 'message: You should use the <code>&gt;</code> operator at least twice');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244d5",
"title": "Comparison with the Greater Than Or Equal To Operator",
"description": [
"The <code>greater than or equal to</code> operator (<code>&gt;=</code>) compares the values of two numbers. If the number to the left is greater than or equal to the number to the right, it returns <code>true</code>. Otherwise, it returns <code>false</code>.",
"Like the equality operator, <code>greater than or equal to</code> operator will convert data types while comparing.",
"<strong>Examples</strong>",
"<blockquote> 6 >= 6 // true<br> 7 >= '3' // true<br> 2 >= 3 // false<br>'7' >= 9 // false</blockquote>",
"<h4>Instructions</h4>",
"Add the <code>greater than or equal to</code> operator to the indicated lines so that the return statements make sense."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"function myTest(val) {",
" if (val) { // Change this line",
" return \"20 or Over\";",
" }",
" ",
" if (val) { // Change this line",
" return \"10 or Over\";",
" }",
"",
" return \"9 or Under\";",
"}",
"",
"// Change this value to test",
"myTest(10);"
],
"solutions": [
"function myTest(val) {\n if (val >= 20) { // Change this line\n return \"20 or Over\";\n }\n \n if (val >= 10) { // Change this line\n return \"10 or Over\";\n }\n\n return \"9 or Under\";\n}"
],
"tests": [
"assert(myTest(0) === \"9 or Under\", 'message: <code>myTest(0)</code> should return \"9 or Under\"');",
"assert(myTest(9) === \"9 or Under\", 'message: <code>myTest(9)</code> should return \"9 or Under\"');",
"assert(myTest(10) === \"10 or Over\", 'message: <code>myTest(10)</code> should return \"10 or Over\"');",
"assert(myTest(11) === \"10 or Over\", 'message: <code>myTest(11)</code> should return \"10 or Over\"');",
"assert(myTest(19) === \"10 or Over\", 'message: <code>myTest(19)</code> should return \"10 or Over\"');",
"assert(myTest(100) === \"20 or Over\", 'message: <code>myTest(100)</code> should return \"20 or Over\"');",
"assert(myTest(21) === \"20 or Over\", 'message: <code>myTest(21)</code> should return \"20 or Over\"');",
"assert(code.match(/val\\s*>=\\s*('|\")*\\d+('|\")*/g).length > 1, 'message: You should use the <code>&gt;=</code> operator at least twice');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244d6",
"title": "Comparison with the Less Than Operator",
"description": [
"The <dfn>less than</dfn> operator (<code>&lt;</code>) compares the values of two numbers. If the number to the left is less than the number to the right, it returns <code>true</code>. Otherwise, it returns <code>false</code>. Like the equality operator, <dfn>less than</dfn> operator converts data types while comparing.",
"<strong>Examples</strong>",
"<blockquote> 2 &lt; 5 // true<br>'3' &lt; 7 // true<br> 5 &lt; 5 // false<br> 3 &lt; 2 // false<br>'8' &lt; 4 // false</blockquote>",
"<h4>Instructions</h4>",
"Add the <code>less than</code> operator to the indicated lines so that the return statements make sense."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"function myTest(val) {",
" if (val) { // Change this line",
" return \"Under 25\";",
" }",
" ",
" if (val) { // Change this line",
" return \"Under 55\";",
" }",
"",
" return \"55 or Over\";",
"}",
"",
"// Change this value to test",
"myTest(10);"
],
"solutions": [
"function myTest(val) {\n if (val < 25) { // Change this line\n return \"Under 25\";\n }\n \n if (val < 55) { // Change this line\n return \"Under 55\";\n }\n\n return \"55 or Over\";\n}"
],
"tests": [
"assert(myTest(0) === \"Under 25\", 'message: <code>myTest(0)</code> should return \"Under 25\"');",
"assert(myTest(24) === \"Under 25\", 'message: <code>myTest(24)</code> should return \"Under 25\"');",
"assert(myTest(25) === \"Under 55\", 'message: <code>myTest(25)</code> should return \"Under 55\"');",
"assert(myTest(54) === \"Under 55\", 'message: <code>myTest(54)</code> should return \"Under 55\"');",
"assert(myTest(55) === \"55 or Over\", 'message: <code>myTest(55)</code> should return \"55 or Over\"');",
"assert(myTest(99) === \"55 or Over\", 'message: <code>myTest(99)</code> should return \"55 or Over\"');",
"assert(code.match(/val\\s*<\\s*('|\")*\\d+('|\")*/g).length > 1, 'message: You should use the <code>&lt;</code> operator at least twice');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244d7",
"title": "Comparison with the Less Than Or Equal To Operator",
"description": [
"The <code>less than or equal to</code> operator (<code>&lt;=</code>) compares the values of two numbers. If the number to the left is less than or equal the number to the right, it returns <code>true</code>. If the number on the left is greater than the number on the right, it returns <code>false</code>. Like the equality operator, <code>less than or equal to</code> converts data types.",
"<strong>Examples</strong>",
"<blockquote> 4 &lt;= 5 // true<br>'7' &lt;= 7 // true<br> 5 &lt;= 5 // true<br> 3 &lt;= 2 // false<br>'8' &lt;= 4 // false</blockquote>",
"<h4>Instructions</h4>",
"Add the <code>less than or equal to</code> operator to the indicated lines so that the return statements make sense."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"function myTest(val) {",
" if (val) { // Change this line",
" return \"Smaller Than or Equal to 12\";",
" }",
" ",
" if (val) { // Change this line",
" return \"Smaller Than or Equal to 24\";",
" }",
"",
" return \"25 or More\";",
"}",
"",
"// Change this value to test",
"myTest(10);",
""
],
"solutions": [
"function myTest(val) {\n if (val <= 12) { // Change this line\n return \"Smaller Than or Equal to 12\";\n }\n \n if (val <= 24) { // Change this line\n return \"Smaller Than or Equal to 24\";\n }\n\n return \"25 or More\";\n}"
],
"tests": [
"assert(myTest(0) === \"Smaller Than or Equal to 12\", 'message: <code>myTest(0)</code> should return \"Smaller Than or Equal to 12\"');",
"assert(myTest(11) === \"Smaller Than or Equal to 12\", 'message: <code>myTest(11)</code> should return \"Smaller Than or Equal to 12\"');",
"assert(myTest(12) === \"Smaller Than or Equal to 12\", 'message: <code>myTest(12)</code> should return \"Smaller Than or Equal to 12\"');",
"assert(myTest(23) === \"Smaller Than or Equal to 24\", 'message: <code>myTest(23)</code> should return \"Smaller Than or Equal to 24\"');",
"assert(myTest(24) === \"Smaller Than or Equal to 24\", 'message: <code>myTest(24)</code> should return \"Smaller Than or Equal to 24\"');",
"assert(myTest(25) === \"25 or More\", 'message: <code>myTest(25)</code> should return \"25 or More\"');",
"assert(myTest(55) === \"25 or More\", 'message: <code>myTest(55)</code> should return \"25 or More\"');",
"assert(code.match(/val\\s*<=\\s*('|\")*\\d+('|\")*/g).length > 1, 'message: You should use the <code>&lt;=</code> operator at least twice');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244d8",
"title": "Comparisons with the Logical And Operator",
"description": [
"Sometimes you will need to test more than one thing at a time. The <dfn>logical and</dfn> operator (<code>&&</code>) returns <code>true</code> if and only if the <dfn>operands</dfn> to the left and right of it are true.",
"The same effect could be achieved by nesting an if statement inside another if:",
"<blockquote>if (num > 5) {<br> if (num < 10) {<br> return \"Yes\";<br> }<br>}<br>return \"No\";</blockquote>",
"will only return \"Yes\" if <code>num</code> is between <code>6</code> and <code>9</code> (6 and 9 included). The same logic can be written as:",
"<blockquote>if (num > 5 && num < 10) {<br> return \"Yes\";<br>}<br>return \"No\";</blockquote>",
"<h4>Instructions</h4>",
"Combine the two if statements into one statement which will return <code>\"Yes\"</code> if <code>val</code> is less than or equal to <code>50</code> and greater than or equal to <code>25</code>. Otherwise, will return <code>\"No\"</code>."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"function myTest(val) {",
" // Only change code below this line",
"",
" if (val) {",
" if (val) {",
" return \"Yes\";",
" }",
" }",
"",
" // Only change code above this line",
" return \"No\";",
"}",
"",
"// Change this value to test",
"myTest(10);"
],
"solutions": [
"function myTest(val) {\n if (val >= 25 && val <= 50) {\n return \"Yes\";\n }\n return \"No\";\n}"
],
"tests": [
"assert(code.match(/&&/g).length === 1, 'message: You should use the <code>&&</code> operator once');",
"assert(code.match(/if/g).length === 1, 'message: You should only have one <code>if</code> statement');",
"assert(myTest(0) === \"No\", 'message: <code>myTest(0)</code> should return \"No\"');",
"assert(myTest(24) === \"No\", 'message: <code>myTest(24)</code> should return \"No\"');",
"assert(myTest(25) === \"Yes\", 'message: <code>myTest(25)</code> should return \"Yes\"');",
"assert(myTest(30) === \"Yes\", 'message: <code>myTest(30)</code> should return \"Yes\"');",
"assert(myTest(50) === \"Yes\", 'message: <code>myTest(50)</code> should return \"Yes\"');",
"assert(myTest(51) === \"No\", 'message: <code>myTest(51)</code> should return \"No\"');",
"assert(myTest(75) === \"No\", 'message: <code>myTest(75)</code> should return \"No\"');",
"assert(myTest(51) === \"No\", 'message: <code>myTest(51)</code> should return \"No\"');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244d9",
"title": "Comparisons with the Logical Or Operator",
"description": [
"The <dfn>logical or</dfn> operator (<code>||</code>) returns <code>true</code> if either of the <dfn>operands</dfn> is <code>true</code>. Otherwise, it returns <code>false</code>.",
"The pattern below should look familiar from prior waypoints:",
"<blockquote>if (num > 10) {<br> return \"No\";<br>}<br>if (num < 5) {<br> return \"No\";<br>}<br>return \"Yes\";</blockquote>",
"will return \"Yes\" only if <code>num</code> is between <code>5</code> and <code>10</code> (5 and 10 included). The same logic can be written as:",
"<blockquote>if (num > 10 || num < 5) {<br> return \"No\";<br>}<br>return \"Yes\";</blockquote>",
"<h4>Instructions</h4>",
"Combine the two <code>if</code> statements into one statement which returns <code>\"Outside\"</code> if <code>val</code> is not between <code>10</code> and <code>20</code>, inclusive. Otherwise, return <code>\"Inside\"</code>."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"function myTest(val) {",
" // Only change code below this line",
"",
" if (val) {",
" return \"Outside\";",
" }",
"",
" if (val) {",
" return \"Outside\";",
" }",
"",
" // Only change code above this line",
" return \"Inside\";",
"}",
"",
"// Change this value to test",
"myTest(15);"
],
"solutions": [
"function myTest(val) {\n if (val < 10 || val > 20) {\n return \"Outside\";\n }\n return \"Inside\";\n}"
],
"tests": [
"assert(code.match(/\\|\\|/g).length === 1, 'message: You should use the <code>||</code> operator once');",
"assert(code.match(/if/g).length === 1, 'message: You should only have one <code>if</code> statement');",
"assert(myTest(0) === \"Outside\", 'message: <code>myTest(0)</code> should return \"Outside\"');",
"assert(myTest(9) === \"Outside\", 'message: <code>myTest(9)</code> should return \"Outside\"');",
"assert(myTest(10) === \"Inside\", 'message: <code>myTest(10)</code> should return \"Inside\"');",
"assert(myTest(15) === \"Inside\", 'message: <code>myTest(15)</code> should return \"Inside\"');",
"assert(myTest(19) === \"Inside\", 'message: <code>myTest(19)</code> should return \"Inside\"');",
"assert(myTest(20) === \"Inside\", 'message: <code>myTest(20)</code> should return \"Inside\"');",
"assert(myTest(21) === \"Outside\", 'message: <code>myTest(21)</code> should return \"Outside\"');",
"assert(myTest(25) === \"Outside\", 'message: <code>myTest(25)</code> should return \"Outside\"');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244da",
"title": "Introducing Else Statements",
"description": [
"When a condition for an <code>if</code> statement is true, the block of code following it is executed. What about when that condition is false? Normally nothing would happen. With an <code>else</code> statement, an alternate block of code can be executed.",
"<blockquote>if (num > 10) {<br> return \"Bigger than 10\";<br>} else {<br> return \"10 or Less\";<br>}</blockquote>",
"<h4>Instructions</h4>",
"Combine the <code>if</code> statements into a single <code>if/else</code> statement."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"function myTest(val) {",
" var result = \"\";",
" // Only change code below this line",
" ",
" if (val > 5) {",
" result = \"Bigger than 5\";",
" }",
" ",
" if (val <= 5) {",
" result = \"5 or Smaller\";",
" }",
" ",
" // Only change code above this line",
" return result;",
"}",
"",
"// Change this value to test",
"myTest(4);",
""
],
"solutions": [
"function myTest(val) {\n var result = \"\";\n if(val > 5) {\n result = \"Bigger than 5\";\n } else {\n result = \"5 or Smaller\";\n }\n return result;\n}"
],
"tests": [
"assert(code.match(/if/g).length === 1, 'message: You should only have one <code>if</code> statement');",
"assert(/else/g.test(code), 'message: You should use an <code>else</code> statement');",
"assert(myTest(4) === \"5 or Smaller\", 'message: <code>myTest(4)</code> should return \"5 or Smaller\"');",
"assert(myTest(5) === \"5 or Smaller\", 'message: <code>myTest(5)</code> should return \"5 or Smaller\"');",
"assert(myTest(6) === \"Bigger than 5\", 'message: <code>myTest(6)</code> should return \"Bigger than 5\"');",
"assert(myTest(10) === \"Bigger than 5\", 'message: <code>myTest(10)</code> should return \"Bigger than 5\"');",
"assert(/var result = \"\";/.test(code) && /return result;/.test(code), 'message: Do not change the code above or below the lines.');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244db",
"title": "Introducing Else If Statements",
"description": [
"If you have multiple conditions that need to be addressed, you can chain <code>if</code> statements together with <code>else if</code> statements.",
"<blockquote>if (num > 15) {<br> return \"Bigger than 15\";<br>} else if (num < 5) {<br> return \"Smaller than 5\";<br>} else {<br> return \"Between 5 and 15\";<br>}</blockquote>",
"<h4>Instructions</h4>",
"Convert the logic to use <code>else if</code> statements."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"function myTest(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",
"myTest(7);",
""
],
"solutions": [
"function myTest(val) {\n if(val > 10) {\n return \"Greater than 10\";\n } else if(val < 5) {\n return \"Smaller than 5\";\n } else {\n return \"Between 5 and 10\";\n }\n}"
],
"tests": [
"assert(code.match(/else/g).length > 1, 'message: You should have at least two <code>else</code> statements');",
"assert(code.match(/if/g).length > 1, 'message: You should have at least two <code>if</code> statements');",
"assert(myTest(0) === \"Smaller than 5\", 'message: <code>myTest(0)</code> should return \"Smaller than 5\"');",
"assert(myTest(5) === \"Between 5 and 10\", 'message: <code>myTest(5)</code> should return \"Between 5 and 10\"');",
"assert(myTest(7) === \"Between 5 and 10\", 'message: <code>myTest(7)</code> should return \"Between 5 and 10\"');",
"assert(myTest(10) === \"Between 5 and 10\", 'message: <code>myTest(10)</code> should return \"Between 5 and 10\"');",
"assert(myTest(12) === \"Greater than 10\", 'message: <code>myTest(12)</code> should return \"Greater than 10\"');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "5690307fddb111c6084545d7",
"title": "Logical Order in If Else Statements",
"description": [
"Order is important in <code>if</code>, <code>else if</code> statements.",
"The loop is executed from top to bottom so you will want to be careful of what statement comes first.",
"Take these two functions as an example.",
"Heres the first:",
"<blockquote>function foo(x) {<br> if (x < 1) {<br> return \"Less than one\";<br> } else if (x < 2) {<br> return \"Less than two\";<br> } else {<br> return \"Greater than or equal to two\";<br> }<br>}</blockquote>",
"And the second just switches the order of the statements:",
"<blockquote>function bar(x) {<br> if (x < 2) {<br> return \"Less than two\";<br> } else if (x < 1) {<br> return \"Less than one\";<br> } else {<br> return \"Greater than or equal to two\";<br> }<br>}</blockquote>",
"While these two functions look nearly identical if we pass a number to both we get different outputs.",
"<blockquote>foo(0) // \"Less than one\"<br>bar(0) // \"Less than two\"</blockquote>",
"<h4>Instructions</h4>",
"Change the order of logic in the function so that it will return the correct statements in all cases."
],
"challengeSeed": [
"function myTest(val) {",
" if (val < 10) {",
" return \"Less than 10\";",
" } else if (val < 5) {",
" return \"Less than 5\";",
" } else {",
" return \"Greater than or equal to 10\";",
" }",
"}",
"",
"// Change this value to test",
"myTest(7);"
],
"solutions": [
"function myTest(val) {\n if(val < 5) {\n return \"Less than 5\"; \n } else if (val < 10) {\n return \"Less than 10\";\n } else {\n return \"Greater than or equal to 10\";\n }\n}"
],
"tests": [
"assert(myTest(4) === \"Less than 5\", 'message: <code>myTest(4)</code> should return \"Less than 5\"');",
"assert(myTest(6) === \"Less than 10\", 'message: <code>myTest(6)</code> should return \"Less than 10\"');",
"assert(myTest(11) === \"Greater than or equal to 10\", 'message: <code>myTest(11)</code> should return \"Greater than or equal to 10\"');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244dc",
"title": "Chaining If Else Statements",
"description": [
"<code>if/else</code> statements can be chained together for complex logic. Here is <dfn>pseudocode</dfn> of multiple chained <code>if</code> / <code>else if</code> statements:",
"<blockquote>if (<em>condition1</em>) {<br> <em>statement1</em><br>} else if (<em>condition2</em>) {<br> <em>statement2</em><br>} else if (<em>condition3</em>) {<br> <em>statement3</em><br>. . .<br>} else {<br> <em>statementN</em><br>}</blockquote>",
"<h4>Instructions</h4>",
"Write chained <code>if</code>/<code>else if</code> statements to fulfill the following conditions:",
"<code>num &lt; 5</code> - return \"Tiny\"<br><code>num &lt; 10</code> - return \"Small\"<br><code>num &lt; 15</code> - return \"Medium\"<br><code>num &lt; 20</code> - return \"Large\"<br><code>num >= 20</code> - return \"Huge\""
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"function myTest(num) {",
" // Only change code below this line",
" ",
" ",
" return \"Change Me\";",
" // Only change code above this line",
"}",
"",
"// Change this value to test",
"myTest(7);"
],
"solutions": [
"function myTest(num) {\n if (num < 5) {\n return \"Tiny\";\n } else if (num < 10) {\n return \"Small\";\n } else if (num < 15) {\n return \"Medium\";\n } else if (num < 20) {\n return \"Large\";\n } else {\n return \"Huge\";\n }\n}"
],
"tests": [
"assert(code.match(/else/g).length > 3, 'message: You should have at least four <code>else</code> statements');",
"assert(code.match(/if/g).length > 3, 'message: You should have at least four <code>if</code> statements');",
"assert(code.match(/return/g).length >= 5, 'message: You should have at least five <code>return</code> statements');",
"assert(myTest(0) === \"Tiny\", 'message: <code>myTest(0)</code> should return \"Tiny\"');",
"assert(myTest(4) === \"Tiny\", 'message: <code>myTest(4)</code> should return \"Tiny\"');",
"assert(myTest(5) === \"Small\", 'message: <code>myTest(5)</code> should return \"Small\"');",
"assert(myTest(8) === \"Small\", 'message: <code>myTest(8)</code> should return \"Small\"');",
"assert(myTest(10) === \"Medium\", 'message: <code>myTest(10)</code> should return \"Medium\"');",
"assert(myTest(14) === \"Medium\", 'message: <code>myTest(14)</code> should return \"Medium\"');",
"assert(myTest(15) === \"Large\", 'message: <code>myTest(15)</code> should return \"Large\"');",
"assert(myTest(17) === \"Large\", 'message: <code>myTest(17)</code> should return \"Large\"');",
"assert(myTest(20) === \"Huge\", 'message: <code>myTest(20)</code> should return \"Huge\"');",
"assert(myTest(25) === \"Huge\", 'message: <code>myTest(25)</code> should return \"Huge\"');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "5664820f61c48e80c9fa476c",
"title": "Golf Code",
"description": [
"In the game of <a href='https://en.wikipedia.org/wiki/Golf' target='_blank'>golf</a> each hole has a <dfn>par</dfn> for the average number of <dfn>strokes</dfn> needed to sink the ball. Depending on how far above or below <code>par</code> your <code>strokes</code> are, there is a different nickname.",
"Your function will be passed a <code>par</code> and <code>strokes</code>. Return strings according to this table (based on order of priority - top (highest) to bottom (lowest)):",
"<table class=\"table table-striped\"><thead><tr><th>Strokes</th><th>Return</th></tr></thead><tbody><tr><td>1</td><td>\"Hole-in-one!\"</td></tr><tr><td>&lt;= par - 2</td><td>\"Eagle\"</td></tr><tr><td>par - 1</td><td>\"Birdie\"</td></tr><tr><td>par</td><td>\"Par\"</td></tr><tr><td>par + 1</td><td>\"Bogey\"</td></tr><tr><td>par + 2</td><td>\"Double Bogey\"</td></tr><tr><td>&gt;= par + 3</td><td>\"Go Home!\"</td></tr></tbody></table>",
"<code>par</code> and <code>strokes</code> will always be numeric and positive."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"function golfScore(par, strokes) {",
" // Only change code below this line",
" ",
" ",
" return \"Change Me\";",
" // Only change code above this line",
"}",
"",
"// Change these values to test",
"golfScore(5, 4);"
],
"solutions": [
"function golfScore(par, strokes) {\n if (strokes === 1) {\n return \"Hole-in-one!\";\n }\n \n if (strokes <= par - 2) {\n return \"Eagle\";\n }\n \n if (strokes === par - 1) {\n return \"Birdie\";\n }\n \n if (strokes === par) {\n return \"Par\";\n }\n \n if (strokes === par + 1) {\n return \"Bogey\";\n }\n \n if(strokes === par + 2) {\n return \"Double Bogey\";\n }\n \n return \"Go Home!\";\n}"
],
"tests": [
"assert(golfScore(4, 1) === \"Hole-in-one!\", 'message: <code>golfScore(4, 1)</code> should return \"Hole-in-one!\"');",
"assert(golfScore(4, 2) === \"Eagle\", 'message: <code>golfScore(4, 2)</code> should return \"Eagle\"');",
"assert(golfScore(5, 2) === \"Eagle\", 'message: <code>golfScore(5, 2)</code> should return \"Eagle\"');",
"assert(golfScore(4, 3) === \"Birdie\", 'message: <code>golfScore(4, 3)</code> should return \"Birdie\"');",
"assert(golfScore(4, 4) === \"Par\", 'message: <code>golfScore(4, 4)</code> should return \"Par\"');",
"assert(golfScore(1, 1) === \"Hole-in-one!\", 'message: <code>golfScore(1, 1)</code> should return \"Hole-in-one!\"');",
"assert(golfScore(5, 5) === \"Par\", 'message: <code>golfScore(5, 5)</code> should return \"Par\"');",
"assert(golfScore(4, 5) === \"Bogey\", 'message: <code>golfScore(4, 5)</code> should return \"Bogey\"');",
"assert(golfScore(4, 6) === \"Double Bogey\", 'message: <code>golfScore(4, 6)</code> should return \"Double Bogey\"');",
"assert(golfScore(4, 7) === \"Go Home!\", 'message: <code>golfScore(4, 7)</code> should return \"Go Home!\"');",
"assert(golfScore(5, 9) === \"Go Home!\", 'message: <code>golfScore(5, 9)</code> should return \"Go Home!\"');"
],
"type": "checkpoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244dd",
"title": "Selecting from many options with Switch Statements",
"description": [
"If you have many options to choose from, use a <code>switch</code> statement. A <code>switch</code> statement tests a value and can have many <code>case</code> statements which defines various possible values. Statements are executed from the first matched <code>case</code> value until a <code>break</code> is encountered.",
"Here is a <dfn>pseudocode</dfn> example:",
"<blockquote>switch (num) {<br> case value1:<br> statement1;<br> break;<br> case value2:<br> statement2;<br> break;<br>...<br> case valueN:<br> statementN;<br> break;<br>}</blockquote>",
"<code>case</code> values are tested with strict equality (<code>===</code>). The <code>break</code> tells JavaScript to stop executing statements. If the <code>break</code> is omitted, the next statement will be executed.",
"<h4>Instructions</h4>",
"Write a switch statement which tests <code>val</code> and sets <code>answer</code> for the following conditions:<br><code>1</code> - \"alpha\"<br><code>2</code> - \"beta\"<br><code>3</code> - \"gamma\"<br><code>4</code> - \"delta\""
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"function myTest(val) {",
" var answer = \"\";",
" // Only change code below this line",
" ",
" ",
" ",
" // Only change code above this line ",
" return answer; ",
"}",
"",
"// Change this value to test",
"myTest(1);",
""
],
"solutions": [
"function myTest(val) {\n var answer = \"\";\n\n switch (val) {\n case 1:\n answer = \"alpha\";\n break;\n case 2:\n answer = \"beta\";\n break;\n case 3:\n answer = \"gamma\";\n break;\n case 4:\n answer = \"delta\";\n }\n return answer; \n}"
],
"tests": [
"assert(myTest(1) === \"alpha\", 'message: <code>myTest(1) should have a value of \"alpha\"');",
"assert(myTest(2) === \"beta\", 'message: <code>myTest(2) should have a value of \"beta\"');",
"assert(myTest(3) === \"gamma\", 'message: <code>myTest(3) should have a value of \"gamma\"');",
"assert(myTest(4) === \"delta\", 'message: <code>myTest(4) should have a value of \"delta\"');",
"assert(!/else/g.test(code) || !/if/g.test(code), 'message: You should not use any <code>if</code> or <code>else</code> statements');",
"assert(code.match(/break/g).length > 2, 'message: You should have at least 3 <code>break</code> statements');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244de",
"title": "Adding a default option in Switch statements",
"description": [
"In a <code>switch</code> statement you may not be able to specify all possible values as <code>case</code> statements. Instead, you can add the <code>default</code> statement which will be executed if no matching <code>case</code> statements are found. Think of it like the final <code>else</code> statement in an <code>if/else</code> chain.",
"A <code>default</code> statement should be the last case.",
"<blockquote>switch (num) {<br> case value1:<br> statement1;<br> break;<br> case value2:<br> statement2;<br> break;<br>...<br> default:<br> defaultStatement;<br>}</blockquote>",
"<h4>Instructions</h4>",
"Write a switch statement to set <code>answer</code> for the following conditions:<br><code>\"a\"</code> - \"apple\"<br><code>\"b\"</code> - \"bird\"<br><code>\"c\"</code> - \"cat\"<br><code>default</code> - \"stuff\""
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"function myTest(val) {",
" var answer = \"\";",
" // Only change code below this line",
" ",
" ",
" ",
" // Only change code above this line ",
" return answer; ",
"}",
"",
"// Change this value to test",
"myTest(1);",
""
],
"solutions": [
"function myTest(val) {\n var answer = \"\";\n\n switch(val) {\n case \"a\":\n answer = \"apple\";\n break;\n case \"b\":\n answer = \"bird\";\n break;\n case \"c\":\n answer = \"cat\";\n break;\n default:\n answer = \"stuff\";\n }\n return answer; \n}"
],
"tests": [
"assert(myTest(\"a\") === \"apple\", 'message: <code>myTest(\"a\") should have a value of \"apple\"');",
"assert(myTest(\"b\") === \"bird\", 'message: <code>myTest(\"b\") should have a value of \"bird\"');",
"assert(myTest(\"c\") === \"cat\", 'message: <code>myTest(\"c\") should have a value of \"cat\"');",
"assert(myTest(\"d\") === \"stuff\", 'message: <code>myTest(\"d\") should have a value of \"stuff\"');",
"assert(myTest(4) === \"stuff\", 'message: <code>myTest(4) should have a value of \"stuff\"');",
"assert(!/else/g.test(code) || !/if/g.test(code), 'message: You should not use any <code>if</code> or <code>else</code> statements');",
"assert(code.match(/break/g).length > 2, 'message: You should have at least 3 <code>break</code> statements');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244df",
"title": "Multiple Identical Options in Switch Statements",
"description": [
"If the <code>break</code> statement is omitted from a <code>switch</code> statement's <code>case</code>, the following <code>case</code> statement(s) are executed until a <code>break</code> is encountered. If you have multiple inputs with the same output, you can represent them in a <code>switch</code> statement like this:",
"<blockquote>switch(val) {<br> case 1:<br> case 2:<br> case 3:<br> result = \"1, 2, or 3\";<br> break;<br> case 4:<br> result = \"4 alone\";<br>}</blockquote>",
"Cases for 1, 2, and 3 will all produce the same result.",
"<h4>Instructions</h4>",
"Write a switch statement to set <code>answer</code> for the following ranges:<br><code>1-3</code> - \"Low\"<br><code>4-6</code> - \"Mid\"<br><code>7-9</code> - \"High\"",
"<strong>Note</strong><br>You will need to have a <code>case</code> statement for each number in the range."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"function myTest(val) {",
" var answer = \"\";",
" // Only change code below this line",
" ",
" ",
" ",
" // Only change code above this line ",
" return answer; ",
"}",
"",
"// Change this value to test",
"myTest(1);",
""
],
"solutions": [
"function myTest(val) {\n var answer = \"\";\n \n switch (val) {\n case 1:\n case 2:\n case 3:\n answer = \"Low\";\n break;\n case 4:\n case 5:\n case 6:\n answer = \"Mid\";\n break;\n case 7:\n case 8:\n case 9:\n answer = \"High\";\n }\n \n return answer; \n}"
],
"tests": [
"assert(myTest(1) === \"Low\", 'message: <code>myTest(1)</code> should return \"Low\"');",
"assert(myTest(2) === \"Low\", 'message: <code>myTest(2)</code> should return \"Low\"');",
"assert(myTest(3) === \"Low\", 'message: <code>myTest(3)</code> should return \"Low\"');",
"assert(myTest(4) === \"Mid\", 'message: <code>myTest(4)</code> should return \"Mid\"');",
"assert(myTest(5) === \"Mid\", 'message: <code>myTest(5)</code> should return \"Mid\"');",
"assert(myTest(6) === \"Mid\", 'message: <code>myTest(6)</code> should return \"Mid\"');",
"assert(myTest(7) === \"High\", 'message: <code>myTest(7)</code> should return \"High\"');",
"assert(myTest(8) === \"High\", 'message: <code>myTest(8)</code> should return \"High\"');",
"assert(myTest(9) === \"High\", 'message: <code>myTest(9)</code> should return \"High\"');",
"assert(!/else/g.test(code) || !/if/g.test(code), 'message: You should not use any <code>if</code> or <code>else</code> statements');",
"assert(code.match(/case/g).length === 9, 'message: You should have nine <code>case</code> statements');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244e0",
"title": "Replacing If Else Chains with Switch",
"description": [
"If you have many options to choose from, a <code>switch</code> statement can be easier to write than many chained <code>if</code>/<code>if else</code> statements. The following:",
"<blockquote>if (val === 1) {<br> answer = \"a\";<br>} else if (val === 2) {<br> answer = \"b\";<br>} else {<br> answer = \"c\";<br>}</blockquote>",
"can be replaced with:",
"<blockquote>switch (val) {<br> case 1:<br> answer = \"a\";<br> break;<br> case 2:<br> answer = \"b\";<br> break;<br> default:<br> answer = \"c\";<br>}</blockquote>",
"<h4>Instructions</h4>",
"Change the chained <code>if</code>/<code>if else</code> statements into a <code>switch</code> statement."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"function myTest(val) {",
" var answer = \"\";",
" // Only change code below this line",
" ",
" if (val === \"bob\") {",
" answer = \"Marley\";",
" } else if (val === 42) {",
" answer = \"The Answer\";",
" } else if (val === 1) {",
" answer = \"There is no #1\";",
" } else if (val === 99) {",
" answer = \"Missed me by this much!\";",
" } else if (val === 7) {",
" answer = \"Ate Nine\";",
" }",
" ",
" // Only change code above this line ",
" return answer; ",
"}",
"",
"// Change this value to test",
"myTest(7);",
""
],
"solutions": [
"function myTest(val) {\n var answer = \"\";\n\n switch (val) {\n case \"bob\":\n answer = \"Marley\";\n break;\n case 42:\n answer = \"The Answer\";\n break;\n case 1:\n answer = \"There is no #1\";\n break;\n case 99:\n answer = \"Missed me by this much!\";\n break;\n case 7:\n answer = \"Ate Nine\";\n }\n return answer; \n}"
],
"tests": [
"assert(!/else/g.test(code), 'message: You should not use any <code>else</code> statements');",
"assert(!/if/g.test(code), 'message: You should not use any <code>if</code> statements');",
"assert(code.match(/break/g).length >= 4, 'message: You should have at least four <code>break</code> statements');",
"assert(myTest(\"bob\") === \"Marley\", 'message: <code>myTest(\"bob\")</code> should be \"Marley\"');",
"assert(myTest(42) === \"The Answer\", 'message: <code>myTest(42)</code> should be \"The Answer\"');",
"assert(myTest(1) === \"There is no #1\", 'message: <code>myTest(1)</code> should be \"There is no #1\"');",
"assert(myTest(99) === \"Missed me by this much!\", 'message: <code>myTest(99)</code> should be \"Missed me by this much!\"');",
"assert(myTest(7) === \"Ate Nine\", 'message: <code>myTest(7)</code> should be \"Ate Nine\"');",
"assert(myTest(\"John\") === \"\", 'message: <code>myTest(\"John\")</code> should be \"\" (empty string)');",
"assert(myTest(156) === \"\", 'message: <code>myTest(156)</code> should be \"\" (empty string)');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "5679ceb97cbaa8c51670a16b",
"title": "Returning Boolean Values from Functions",
"description": [
"You may recall from <a href=\"waypoint-comparison-with-the-equality-operator\" target=\"_blank\">Comparison with the Equality Operator</a> that all comparison operators return a boolean <code>true</code> or <code>false</code> value.",
"A common <dfn>anti-pattern</dfn> is to use an <code>if/else</code> statement to do a comparison and then <code>return</code> <code>true</code>/<code>false</code>:",
"<blockquote>function isEqual(a,b) {<br> if (a === b) {<br> return true;<br> } else {<br> return false;<br> }<br>}</blockquote>",
"Since <code>===</code> returns <code>true</code> or <code>false</code>, we can simply return the result of the comparison:",
"<blockquote>function isEqual(a,b) {<br> return a === b;<br>}</blockquote>",
"<h4>Instructions</h4>",
"Fix the function <code>isLess</code> to remove the <code>if/else</code> statements."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"function isLess(a, b) {",
" // Fix this code",
" if (a < b) {",
" return true;",
" } else {",
" return false;",
" }",
"}",
"",
"// Change these values to test",
"isLess(10, 15);"
],
"tail": [
""
],
"solutions": [
"function isLess(a, b) {\n return a < b;\n}"
],
"tests": [
"assert(isLess(10,15) === true, 'message: <code>isLess(10,15)</code> should return <code>true</code>');",
"assert(isLess(15, 10) === false, 'message: <code>isLess(15,10)</code> should return <code>false</code>');",
"assert(!/if|else/g.test(code), 'message: You should not use any <code>if</code> or <code>else</code> statements');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244c4",
"title": "Return Early Pattern for Functions",
"description": [
"When a <code>return</code> statement is reached, the execution of the current function stops and control returns to the calling location.",
"<strong>Example</strong>",
"<blockquote>function myFun() {<br> console.log(\"Hello\");<br> return \"World\";<br> console.log(\"byebye\")<br>}<br>myFun();</blockquote>",
"The above outputs \"Hello\" to the console, returns \"World\", but <code>\"byebye\"</code> is never output, because the function exits at the <code>return</code> statement.",
"<h4>Instructions</h4>",
"Modify the function <code>abTest</code> so that if <code>a</code> or <code>b</code> are less than <code>0</code> the function will immediately exit with a value of <code>undefined</code>.",
"<strong>Hint</strong><br>Remember that <a href='http://www.freecodecamp.com/challenges/understanding-uninitialized-variables' target='_blank'><code>undefined</code> is a keyword</a>, not a string."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// 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);"
],
"tail": [
""
],
"solutions": [
"function abTest(a, b) {\n if(a < 0 || b < 0) {\n return undefined;\n } \n return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));\n}"
],
"tests": [
"assert(typeof abTest(2,2) === 'number' , 'message: <code>abTest(2,2)</code> should return a number');",
"assert(abTest(2,2) === 8 , 'message: <code>abTest(2,2)</code> should return <code>8</code>');",
"assert(abTest(-2,2) === undefined , 'message: <code>abTest(-2,2)</code> should return <code>undefined</code>');",
"assert(abTest(2,-2) === undefined , 'message: <code>abTest(2,-2)</code> should return <code>undefined</code>');",
"assert(abTest(2,8) === 18 , 'message: <code>abTest(2,8)</code> should return <code>18</code>');",
"assert(abTest(3,3) === 12 , 'message: <code>abTest(3,3)</code> should return <code>12</code>');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "565bbe00e9cc8ac0725390f4",
"title": "Counting Cards",
"description": [
"In the casino game Blackjack, a player can gain an advantage over the house by keeping track of the relative number of high and low cards remaining in the deck. This is called <a href='https://en.wikipedia.org/wiki/Card_counting' target='_blank'>Card Counting</a>.",
"Having more high cards remaining in the deck favors the player. Each card is assigned a value according to the table below. When the count is positive, the player should bet high. When the count is zero or negative, the player should bet low.",
"<table class=\"table table-striped\"><thead><tr><th>Value</th><th>Cards</th></tr></thead><tbody><tr><td>+1</td><td>2, 3, 4, 5, 6</td></tr><tr><td>0</td><td>7, 8, 9</td></tr><tr><td>-1</td><td>10, 'J', 'Q', 'K','A'</td></tr></tbody></table>",
"You will write a card counting function. It will receive a <code>card</code> parameter and increment or decrement the global <code>count</code> variable according to the card's value (see table). The function will then return a string with the current count and the string <code>\"Bet\"</code> if the count is positive, or <code>\"Hold\"</code> if the count is zero or negative. The current count and the player's decision (<code>\"Bet\"</code> or <code>\"Hold\"</code>) should be separated by a single space.<br><br>",
"<strong>Example Output</strong><br><code>\"-3 Hold\"<br>\"5 Bet\"</code>"
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"var count = 0;",
"",
"function cc(card) {",
" // Only change code below this line",
" ",
" ",
" return \"Change Me\";",
" // Only change code above this line",
"}",
"",
"// Add/remove calls to test your function.",
"// Note: Only the last will display",
"cc(2); cc(3); cc(7); cc('K'); cc('A');"
],
"solutions": [
"var count = 0;\nfunction cc(card) {\n switch(card) {\n case 2:\n case 3:\n case 4:\n case 5:\n case 6:\n count++;\n break;\n case 10:\n case 'J':\n case 'Q':\n case 'K':\n case 'A':\n count--;\n }\n if(count > 0) {\n return count + \" Bet\";\n } else {\n return count + \" Hold\";\n }\n}"
],
"tests": [
"assert((function(){ count = 0; cc(2);cc(3);cc(4);cc(5);var out = cc(6); if(out === \"5 Bet\") {return true;} return false; })(), 'message: Cards Sequence 2, 3, 4, 5, 6 should return <code>\"5 Bet\"</code>');",
"assert((function(){ count = 0; cc(7);cc(8);var out = cc(9); if(out === \"0 Hold\") {return true;} return false; })(), 'message: Cards Sequence 7, 8, 9 should return <code>\"0 Hold\"</code>');",
"assert((function(){ count = 0; cc(10);cc('J');cc('Q');cc('K');var out = cc('A'); if(out === \"-5 Hold\") {return true;} return false; })(), 'message: Cards Sequence 10, J, Q, K, A should return <code>\"-5 Hold\"</code>');",
"assert((function(){ count = 0; cc(3);cc(2);cc('A');cc(10);var out = cc('K'); if(out === \"-1 Hold\") {return true;} return false; })(), 'message: Cards Sequence 3, 2, A, 10, K should return <code>\"-1 Hold\"</code>');"
],
"type": "checkpoint",
"challengeType": 1
},
{
"id": "bg9998c9c99feddfaeb9bdef",
"title": "Build JavaScript Objects",
"description": [
"You may have heard the term <code>object</code> before.",
"Objects are similar to <code>arrays</code>, except that instead of using indexes to access and modify their data, you access the data in objects through what are called <code>properties</code>.",
"Here's a sample object:",
"<blockquote>var cat = {<br> \"name\": \"Whiskers\",<br> \"legs\": 4,<br> \"tails\": 1,<br> \"enemies\": [\"Water\", \"Dogs\"]<br>};</blockquote>",
"Objects are useful for storing data in a structured way, and can represent real world objects, like a cat.",
"<h4>Instructions</h4>",
"Make an object that represents a dog called <code>myDog</code> which contains the properties <code>\"name\"</code> (a string), <code>\"legs\"</code>, <code>\"tails\"</code> and <code>\"friends\"</code>.",
"You can set these object properties to whatever values you want, as long <code>\"name\"</code> is a string, <code>\"legs\"</code> and <code>\"tails\"</code> are numbers, and <code>\"friends\"</code> is an array."
],
"challengeSeed": [
"// Example",
"var ourDog = {",
" \"name\": \"Camper\",",
" \"legs\": 4,",
" \"tails\": 1,",
" \"friends\": [\"everything!\"]",
"};",
"",
"// Only change code below this line.",
"",
"var myDog = {",
" ",
" ",
" ",
" ",
"};"
],
"tail": [
"(function(z){return z;})(myDog);"
],
"solutions": [
"var myDog = {\n \"name\": \"Camper\",\n \"legs\": 4,\n \"tails\": 1,\n \"friends\": [\"everything!\"] \n};"
],
"tests": [
"assert((function(z){if(z.hasOwnProperty(\"name\") && z.name !== undefined && typeof z.name === \"string\"){return true;}else{return false;}})(myDog), 'message: <code>myDog</code> should contain the property <code>name</code> and it should be a <code>string</code>.');",
"assert((function(z){if(z.hasOwnProperty(\"legs\") && z.legs !== undefined && typeof z.legs === \"number\"){return true;}else{return false;}})(myDog), 'message: <code>myDog</code> should contain the property <code>legs</code> and it should be a <code>number</code>.');",
"assert((function(z){if(z.hasOwnProperty(\"tails\") && z.tails !== undefined && typeof z.tails === \"number\"){return true;}else{return false;}})(myDog), 'message: <code>myDog</code> should contain the property <code>tails</code> and it should be a <code>number</code>.');",
"assert((function(z){if(z.hasOwnProperty(\"friends\") && z.friends !== undefined && Array.isArray(z.friends)){return true;}else{return false;}})(myDog), 'message: <code>myDog</code> should contain the property <code>friends</code> and it should be an <code>array</code>.');",
"assert((function(z){return Object.keys(z).length === 4;})(myDog), 'message: <code>myDog</code> should only contain all the given properties.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Construye objetos en JavaScript",
"descriptionEs": [
"Es posible que haya oído el término <code>objeto</code> antes.",
"Los objetos son similares a los <code>vectores</code>, excepto que en lugar de utilizar los índices para acceder y modificar sus datos, pueden accederse mediante lo que se llama <code>propiedades</code>.",
"Esto es un objeto de ejemplo:",
"<code>var cat = {</code>",
"<code>&nbsp;&nbsp;\"name\": \"Whiskers\",</code>",
"<code>&nbsp;&nbsp;\"legs\": 4,</code>",
"<code>&nbsp;&nbsp;\"tails\": 1,</code>",
"<code>&nbsp;&nbsp;\"enemies\": [\"Water\", \"Dogs\"]</code>",
"<code>};</code>",
"Los objetos son útiles para almacenar datos de manera estructurada, y pueden representar objetos del mundo real, como un gato.",
"Vamos a tratar de hacer un objeto que representa un perro, lo llamaremos <code>mydog</code> y contendrá las propiedades <code>\"name\"</code> (una cadena con el nombre), <code>\"legs\"</code> (piernas), <code>\"tails\"</code> (colas) y <code>\"friends\" (amigos)</code>. ",
"Podrás establecer estas propiedades del objeto en los valores que desees, siempre y cuando <code>\"name\"</code> sea una cadena, <code>\"legs\"</code> y <code>\"tails\"</code> sean números, y <code>\"friends\"</code> sea un vector."
]
},
{
"id": "56533eb9ac21ba0edf2244c7",
"title": "Accessing Objects Properties with the Dot Operator",
"description": [
"There are two ways to access the properties of an object: the dot operator (<code>.</code>) and bracket notation (<code>[]</code>), similar to an array.",
"The dot operator is what you use when you know the name of the property you're trying to access ahead of time.",
"Here is a sample of using the dot operator (<code>.</code>) to read an object property:",
"<blockquote>var myObj = {<br> prop1: \"val1\",<br> prop2: \"val2\"<br>};<br>var prop1val = myObj.prop1; // val1<br>var prop2val = myObj.prop2; // val2</blockquote>",
"<h4>Instructions</h4>",
"Read in the property values of <code>testObj</code> using dot notation. Set the property <code>hat</code> to the variable <code>hatValue</code> and the property <code>shirt</code> to <code>shirtValue</code>."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Setup",
"var testObj = {",
" \"hat\": \"ballcap\",",
" \"shirt\": \"jersey\",",
" \"shoes\": \"cleats\"",
"};",
"",
"// Only change code below this line",
"",
"var hatValue = testObj; // Change this line",
"var shirtValue = testObj; // Change this line"
],
"tail": [
"(function(a,b) { return \"hatValue = '\" + a + \"', shirtValue = '\" + b + \"'\"; })(hatValue,shirtValue);"
],
"solutions": [
"var testObj = {\n \"hat\": \"ballcap\",\n \"shirt\": \"jersey\",\n \"shoes\": \"cleats\"\n};\n\nvar hatValue = testObj.hat; \nvar shirtValue = testObj.shirt;"
],
"tests": [
"assert(typeof hatValue === 'string' , 'message: <code>hatValue</code> should be a string');",
"assert(hatValue === 'ballcap' , 'message: The value of <code>hatValue</code> should be <code>\"ballcap\"</code>');",
"assert(typeof shirtValue === 'string' , 'message: <code>shirtValue</code> should be a string');",
"assert(shirtValue === 'jersey' , 'message: The value of <code>shirtValue</code> should be <code>\"jersey\"</code>');",
"assert(code.match(/testObj\\.\\w+/g).length > 1, 'message: You should use dot notation twice');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244c8",
"title": "Accessing Objects Properties with Bracket Notation",
"description": [
"The second way to access the properties of an object is bracket notation (<code>[]</code>). If the property of the object you are trying to access has a space in it, you will need to use bracket notation.",
"Here is a sample of using bracket notation to read an object property:",
"<blockquote>var myObj = {<br> \"Space Name\": \"Kirk\",<br> \"More Space\": \"Spock\"<br>};<br>myObj[\"Space Name\"]; // Kirk<br>myObj['More Space']; // Spock</blockquote>",
"Note that property names with spaces in them must be in quotes (single or double).",
"<h4>Instructions</h4>",
"Read the values of the properties <code>\"an entree\"</code> and <code>\"the drink\"</code> of <code>testObj</code> using bracket notation."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Setup",
"var testObj = {",
" \"an entree\": \"hamburger\",",
" \"my side\": \"veggies\",",
" \"the drink\": \"water\"",
"};",
"",
"// Only change code below this line",
"",
"var entreeValue = testObj; // Change this line",
"var drinkValue = testObj; // Change this line"
],
"tail": [
"(function(a,b) { return \"entreeValue = '\" + a + \"', drinkValue = '\" + b + \"'\"; })(entreeValue,drinkValue);"
],
"solutions": [
"var testObj = {\n \"an entree\": \"hamburger\",\n \"my side\": \"veggies\",\n \"the drink\": \"water\"\n};\nvar entreeValue = testObj[\"an entree\"];\nvar drinkValue = testObj['the drink'];"
],
"tests": [
"assert(typeof entreeValue === 'string' , 'message: <code>entreeValue</code> should be a string');",
"assert(entreeValue === 'hamburger' , 'message: The value of <code>entreeValue</code> should be <code>\"hamburger\"</code>');",
"assert(typeof drinkValue === 'string' , 'message: <code>drinkValue</code> should be a string');",
"assert(drinkValue === 'water' , 'message: The value of <code>drinkValue</code> should be <code>\"water\"</code>');",
"assert(code.match(/testObj\\s*?\\[('|\")[^'\"]+\\1\\]/g).length > 1, 'message: You should use bracket notation twice');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244c9",
"title": "Accessing Objects Properties with Variables",
"description": [
"Another use of bracket notation on objects is to use a variable to access a property. This can be very useful for iterating through lists of the object properties or for doing the lookup.",
"Here is an example of using a variable to access a property:",
"<blockquote>var someProp = \"propName\";<br>var myObj = {<br> propName: \"Some Value\"<br >}<br>myObj[someProp]; // \"Some Value\"</blockquote>",
"Here is one more:",
"<blockquote>var myDog = \"Hunter\";<br>var dogs = {<br> Fido: \"Mutt\",\n Hunter: \"Doberman\",\n Snoopie: \"Beagle\"<br >}<br>var breed = dogs[myDog]; // \"Hunter\"<br>console.log(breed)// \"Doberman\"</blockquote>",
"Note that we do <em>not</em> use quotes around the variable name when using it to access the property because we are using the <em>value</em> of the variable, not the <em>name</em>",
"<h4>Instructions</h4>",
"Use the <code>playerNumber</code> variable to lookup player <code>16</code> in <code>testObj</code> using bracket notation."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Setup",
"var testObj = {",
" 12: \"Namath\",",
" 16: \"Montana\",",
" 19: \"Unitas\"",
"};",
"",
"// Only change code below this line;",
"",
"var playerNumber; // Change this Line",
"var player = testObj; // Change this Line"
],
"tail": [
"if(typeof player !== \"undefined\"){(function(v){return v;})(player);}"
],
"solutions": [
"var testObj = {\n 12: \"Namath\",\n 16: \"Montana\",\n 19: \"Unitas\"\n};\nvar playerNumber = 16;\nvar player = testObj[playerNumber];"
],
"tests": [
"assert(typeof playerNumber === 'number', 'message: <code>playerNumber</code> should be a number');",
"assert(typeof player === 'string', 'message: The variable <code>player</code> should be a string');",
"assert(player === 'Montana', 'message: The value of <code>player</code> should be \"Montana\"');",
"assert(/testObj\\s*?\\[\\s*playerNumber\\s*\\]/.test(code),'message: You should use bracket notation to access <code>testObj</code>');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "bg9999c9c99feddfaeb9bdef",
"title": "Updating Object Properties",
"description": [
"After you've created a JavaScript object, you can update its properties at any time just like you would update any other variable. You can use either dot or bracket notation to update.",
"For example, let's look at <code>ourDog</code>:",
"<blockquote>var ourDog = {<br> \"name\": \"Camper\",<br> \"legs\": 4,<br> \"tails\": 1,<br> \"friends\": [\"everything!\"]<br>};</blockquote>",
"Since he's a particularly happy dog, let's change his name to \"Happy Camper\". Here's how we update his object's name property:",
"<code>ourDog.name = \"Happy Camper\";</code> or",
"<code>ourDog[\"name\"] = \"Happy Camper\";</code>",
"Now when we evaluate <code>ourDog.name</code>, instead of getting \"Camper\", we'll get his new name, \"Happy Camper\".",
"<h4>Instructions</h4>",
"Update the <code>myDog</code> object's name property. Let's change her name from \"Coder\" to \"Happy Coder\". You can use either dot or bracket notation."
],
"challengeSeed": [
"// Example",
"var ourDog = {",
" \"name\": \"Camper\",",
" \"legs\": 4,",
" \"tails\": 1,",
" \"friends\": [\"everything!\"]",
"};",
"",
"ourDog.name = \"Happy Camper\";",
"",
"// Setup",
"var myDog = {",
" \"name\": \"Coder\",",
" \"legs\": 4,",
" \"tails\": 1,",
" \"friends\": [\"Free Code Camp Campers\"]",
"};",
"",
"// Only change code below this line.",
"",
""
],
"tail": [
"(function(z){return z;})(myDog);"
],
"solutions": [
"var myDog = {\n \"name\": \"Coder\",\n \"legs\": 4,\n \"tails\": 1,\n \"friends\": [\"Free Code Camp Campers\"]\n};\nmyDog.name = \"Happy Coder\";"
],
"tests": [
"assert(/happy coder/gi.test(myDog.name), 'message: Update <code>myDog</code>&apos;s <code>\"name\"</code> property to equal \"Happy Coder\".');",
"assert(/\"name\": \"Coder\"/.test(code), 'message: Do not edit the <code>myDog</code> definition');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Actualiza las propiedades de un objeto en JavaScript",
"descriptionEs": [
"Después de que hayas creado un objeto de JavaScript, puedes actualizar sus propiedades en cualquier momento, tal y como harías con cualquier otra variable.",
"Por ejemplo, echemos un vistazo a <code>ourDog</code>:",
"<code>var ourDog = {</code>",
"<code>&nbsp;&nbsp;\"name\": \"Camper\",</code>",
"<code>&nbsp;&nbsp;\"legs\": 4,</code>",
"<code>&nbsp;&nbsp;\"tails\": 1,</code>",
"<code>&nbsp;&nbsp;\"friends\": [\"everything!\"]</code>",
"<code>};</code>",
"Dado que es un perro particularmente feliz, vamos a cambiar su nombre a \"Happy Camper\". Así es como actualizamos la propiedad nombre del objeto: ",
"<code>ourDog.name = \"Happy Camper\";</code>",
"Ahora, cuando ejecutemos <code>return ourDog.name</code>, en lugar de obtener \"Camper\", vamos a recibir su nuevo nombre, \"Happy Camper\".",
"Vamos a actualizar la propiedad del objeto <code>mydog</code>. Cambiemos su nombre de \"Coder\" a \"Happy Coder\"."
]
},
{
"id": "bg9999c9c99feedfaeb9bdef",
"title": "Add New Properties to a JavaScript Object",
"description": [
"You can add new properties to existing JavaScript objects the same way you would modify them.",
"Here's how we would add a <code>\"bark\"</code> property to <code>ourDog</code>:",
"<code>ourDog.bark = \"bow-wow\";</code> ",
"or",
"<code>ourDog[\"bark\"] = \"bow-wow\";</code>",
"Now when we evaluate <code>ourDog.bark</code>, we'll get his bark, \"bow-wow\".",
"<h4>Instructions</h4>",
"Add a <code>\"bark\"</code> property to <code>myDog</code> and set it to a dog sound, such as \"woof\". You may use either dot or bracket notation."
],
"challengeSeed": [
"// Example",
"var ourDog = {",
" \"name\": \"Camper\",",
" \"legs\": 4,",
" \"tails\": 1,",
" \"friends\": [\"everything!\"]",
"};",
"",
"ourDog.bark = \"bow-wow\";",
"",
"// Setup",
"var myDog = {",
" \"name\": \"Happy Coder\",",
" \"legs\": 4,",
" \"tails\": 1,",
" \"friends\": [\"Free Code Camp Campers\"]",
"};",
"",
"// Only change code below this line.",
""
],
"tail": [
"(function(z){return z;})(myDog);"
],
"solutions": [
"var myDog = {\n \"name\": \"Happy Coder\",\n \"legs\": 4,\n \"tails\": 1,\n \"friends\": [\"Free Code Camp Campers\"]\n};\nmyDog.bark = \"Woof Woof\";"
],
"tests": [
"assert(myDog.bark !== undefined, 'message: Add the property <code>\"bark\"</code> to <code>myDog</code>.');",
"assert(!/bark[^\\n]:/.test(code), 'message: Do not add <code>\"bark\"</code> to the setup section');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Añade nuevas propiedades a un objeto JavaScript",
"descriptionEs": [
"Puedes añadir nuevas propiedades a objetos existente de la misma forma que usarías para modificarlos.",
"Así es como añadimos una propiedad <code>\"bark\"</code> (ladra) a nuestro objeto <code>ourDog</code>:",
"<code>ourDog.bark = \"bow-wow\";</code>",
"Ahora, cuando ejecutemos <code>return ourDog.bark</code>, vamos a recbir su ladrido, \" bow-wow \".",
"Vamos a añadir una propiedad <code>ladra</code> a <code>myDog</code> y a ponerle un sonido de perro, tal como \"woof\"."
]
},
{
"id": "bg9999c9c99fdddfaeb9bdef",
"title": "Delete Properties from a JavaScript Object",
"description": [
"We can also delete properties from objects like this:",
"<code>delete ourDog.bark;</code>",
"<h4>Instructions</h4>",
"Delete the <code>\"tails\"</code> property from <code>myDog</code>. You may use either dot or bracket notation."
],
"challengeSeed": [
"// Example",
"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\": [\"Free Code Camp Campers\"],",
" \"bark\": \"woof\"",
"};",
"",
"// Only change code below this line.",
"",
""
],
"tail": [
"(function(z){return z;})(myDog);"
],
"solutions": [
"var ourDog = {\n \"name\": \"Camper\",\n \"legs\": 4,\n \"tails\": 1,\n \"friends\": [\"everything!\"],\n \"bark\": \"bow-wow\"\n};\n\nvar myDog = {\n \"name\": \"Happy Coder\",\n \"legs\": 4,\n \"tails\": 1,\n \"friends\": [\"Free Code Camp Campers\"],\n \"bark\": \"woof\"\n};\n\ndelete myDog.tails;"
],
"tests": [
"assert(myDog.tails === undefined, 'message: Delete the property <code>\"tails\"</code> from <code>myDog</code>.');",
"assert(code.match(/\"tails\": 1/g).length > 1, 'message: Do not modify the <code>myDog</code> setup');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Elimina propiedades de un objeto JavaScript",
"descriptionEs": [
"También podemos eliminar propiedades de los objetos de esta manera:",
"<code>delete ourDog.bark;</code>",
"Borremos la propiedad <code>\"tails\"</code> de <code>myDog</code>."
]
},
{
"id": "56533eb9ac21ba0edf2244ca",
"title": "Using Objects for Lookups",
"description": [
"Objects can be thought of as a key/value storage, like a dictionary. If you have tabular data, you can use an object to \"lookup\" values rather than a <code>switch</code> statement or an <code>if/else</code> chain. This is most useful when you know that your input data is limited to a certain range.",
"Here is an example of a simple reverse alphabet lookup:",
"<blockquote>var alpha = {<br> 1:\"Z\",<br> 2:\"Y\",<br> 3:\"X\",<br> 4:\"W\",<br> ...<br> 24:\"C\",<br> 25:\"B\",<br> 26:\"A\"<br>};<br>alpha[2]; // \"Y\"<br>alpha[24]; // \"C\"<br><br>var value = 2;<br>alpha[value]; // \"Y\"</blockquote>",
"<h4>Instructions</h4>",
"Convert the switch statement into a lookup table called <code>lookup</code>. Use it to lookup <code>val</code> and assign the associated string to the <code>result</code> variable."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Setup",
"function phoneticLookup(val) {",
" var result = \"\";",
"",
" // Only change code below this line",
" switch(val) {",
" case \"alpha\": ",
" result = \"Adams\";",
" break;",
" case \"bravo\": ",
" result = \"Boston\";",
" break;",
" case \"charlie\": ",
" result = \"Chicago\";",
" break;",
" case \"delta\": ",
" result = \"Denver\";",
" break;",
" case \"echo\": ",
" result = \"Easy\";",
" break;",
" case \"foxtrot\": ",
" result = \"Frank\";",
" }",
"",
" // Only change code above this line",
" return result;",
"}",
"",
"// Change this value to test",
"phoneticLookup(\"charlie\");"
],
"solutions": [
"function phoneticLookup(val) {\n var result = \"\";\n\n var lookup = {\n alpha: \"Adams\",\n bravo: \"Boston\",\n charlie: \"Chicago\",\n delta: \"Denver\",\n echo: \"Easy\",\n foxtrot: \"Frank\"\n };\n\n result = lookup[val];\n\n return result;\n}"
],
"tests": [
"assert(phoneticLookup(\"alpha\") === 'Adams', 'message: <code>phoneticLookup(\"alpha\")</code> should equal <code>\"Adams\"</code>');",
"assert(phoneticLookup(\"bravo\") === 'Boston', 'message: <code>phoneticLookup(\"bravo\")</code> should equal <code>\"Boston\"</code>');",
"assert(phoneticLookup(\"charlie\") === 'Chicago', 'message: <code>phoneticLookup(\"charlie\")</code> should equal <code>\"Chicago\"</code>');",
"assert(phoneticLookup(\"delta\") === 'Denver', 'message: <code>phoneticLookup(\"delta\")</code> should equal <code>\"Denver\"</code>');",
"assert(phoneticLookup(\"echo\") === 'Easy', 'message: <code>phoneticLookup(\"echo\")</code> should equal <code>\"Easy\"</code>');",
"assert(phoneticLookup(\"foxtrot\") === 'Frank', 'message: <code>phoneticLookup(\"foxtrot\")</code> should equal <code>\"Frank\"</code>');",
"assert(typeof phoneticLookup(\"\") === 'undefined', 'message: <code>phoneticLookup(\"\")</code> should equal <code>undefined</code>');",
"assert(!/case|switch|if/g.test(code), 'message: You should not use <code>case</code>, <code>switch</code>, or <code>if</code> statements'); "
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "567af2437cbaa8c51670a16c",
"title": "Testing Objects for Properties",
"description": [
"Sometimes it is useful to check if the property of a given object exists or not. We can use the <code>.hasOwnProperty(propname)</code> method of objects to determine if that object has the given property name. <code>.hasOwnProperty()</code> returns <code>true</code> or <code>false</code> if the property is found or not.",
"<strong>Example</strong>",
"<blockquote>var myObj = {<br> top: \"hat\",<br> bottom: \"pants\"<br>};<br>myObj.hasOwnProperty(\"top\"); // true<br>myObj.hasOwnProperty(\"middle\"); // false</blockquote>",
"<h4>Instructions</h4>",
"Modify the function <code>checkObj</code> to test <code>myObj</code> for <code>checkProp</code>. If the property is found, return that property's value. If not, return <code>\"Not Found\"</code>."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// 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\");"
],
"tail": [
""
],
"solutions": [
"var myObj = {\n gift: \"pony\",\n pet: \"kitten\",\n bed: \"sleigh\"\n};\nfunction checkObj(checkProp) {\n if(myObj.hasOwnProperty(checkProp)) {\n return myObj[checkProp];\n } else {\n return \"Not Found\";\n }\n}"
],
"tests": [
"assert(checkObj(\"gift\") === \"pony\", 'message: <code>checkObj(\"gift\")</code> should return <code>\"pony\"</code>.');",
"assert(checkObj(\"pet\") === \"kitten\", 'message: <code>checkObj(\"pet\")</code> should return <code>\"kitten\"</code>.');",
"assert(checkObj(\"house\") === \"Not Found\", 'message: <code>checkObj(\"house\")</code> should return <code>\"Not Found\"</code>.');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244cb",
"title": "Introducing JavaScript Object Notation (JSON)",
"description": [
"JavaScript Object Notation or <code>JSON</code> uses the format of JavaScript Objects to store data. JSON is flexible because it allows for <dfn>Data Structures</dfn> with arbitrary combinations of <dfn>strings</dfn>, <dfn>numbers</dfn>, <dfn>booleans</dfn>, <dfn>arrays</dfn>, and <dfn>objects</dfn>.",
"Here is an example of a JSON object:",
"<blockquote>var ourMusic = [<br> {<br> \"artist\": \"Daft Punk\",<br> \"title\": \"Homework\",<br> \"release_year\": 1997,<br> \"formats\": [ <br> \"CD\", <br> \"Cassette\", <br> \"LP\" ],<br> \"gold\": true<br> }<br>];</blockquote>",
"This is an array of objects and the object has various pieces of <dfn>metadata</dfn> about an album. It also has a nested <code>formats</code> array. Additional album records could be added to the top level array.",
"<strong>Note</strong><br>You will need a comma in between objects in JSON objects with more than one object in the array.",
"<h4>Instructions</h4>",
"Add a new album to the <code>myMusic</code> JSON object. Add <code>artist</code> and <code>title</code> strings, <code>release_year</code> number, and a <code>formats</code> array of strings."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"var myMusic = [",
" {",
" \"artist\": \"Billy Joel\",",
" \"title\": \"Piano Man\",",
" \"release_year\": 1973,",
" \"formats\": [ ",
" \"CS\", ",
" \"8T\", ",
" \"LP\" ],",
" \"gold\": true",
" }",
" // Add record here",
"];",
""
],
"tail": [
"(function(x){ if (Array.isArray(x)) { return JSON.stringify(x); } return \"myMusic is not an array\"})(myMusic);"
],
"solutions": [
"var myMusic = [\n {\n \"artist\": \"Billy Joel\",\n \"title\": \"Piano Man\",\n \"release_year\": 1973,\n \"formats\": [ \n \"CS\", \n \"8T\", \n \"LP\" ],\n \"gold\": true\n }, \n {\n \"artist\": \"ABBA\",\n \"title\": \"Ring Ring\",\n \"release_year\": 1973,\n \"formats\": [ \n \"CS\", \n \"8T\", \n \"LP\",\n \"CD\",\n ]\n }\n];"
],
"tests": [
"assert(Array.isArray(myMusic), 'message: <code>myMusic</code> should be an array');",
"assert(myMusic.length > 1, 'message: <code>myMusic</code> should have at least two elements');",
"assert(typeof myMusic[1] === 'object', 'message: <code>myMusic[1]</code> should be an object');",
"assert(Object.keys(myMusic[1]).length > 3, 'message: <code>myMusic[1]</code> should have at least 4 properties');",
"assert(myMusic[1].hasOwnProperty('artist') && typeof myMusic[1].artist === 'string', 'message: <code>myMusic[1]</code> should contain an <code>artist</code> property which is a string');",
"assert(myMusic[1].hasOwnProperty('title') && typeof myMusic[1].title === 'string', 'message: <code>myMusic[1]</code> should contain a <code>title</code> property which is a string');",
"assert(myMusic[1].hasOwnProperty('release_year') && typeof myMusic[1].release_year === 'number', 'message: <code>myMusic[1]</code> should contain a <code>release_year</code> property which is a number');",
"assert(myMusic[1].hasOwnProperty('formats') && Array.isArray(myMusic[1].formats), 'message: <code>myMusic[1]</code> should contain a <code>formats</code> property which is an array');",
"assert(myMusic[1].formats.every(function(item) { return (typeof item === \"string\")}) && myMusic[1].formats.length > 1, 'message: <code>formats</code> should be an array of strings with at least two elements');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244cc",
"title": "Accessing Nested Objects in JSON",
"description": [
"The properties and sub-properties of JSON objects can be accessed by chaining together the dot or bracket notation.",
"Here is a nested JSON Object:",
"<blockquote>var ourStorage = {<br> \"desk\": {<br> \"drawer\": \"stapler\"<br> },<br> \"cabinet\": {<br> \"top drawer\": { <br> \"folder1\": \"a file\",<br> \"folder2\": \"secrets\"<br> },<br> \"bottom drawer\": \"soda\"<br> }<br>}<br>ourStorage.cabinet[\"top drawer\"].folder2; // \"secrets\"<br>ourStorage.desk.drawer; // \"stapler\"</blockquote>",
"<h4>Instructions</h4>",
"Access the <code>myStorage</code> JSON object to retrieve the contents of the <code>glove box</code>. Use bracket notation for properties with a space in their name."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Setup",
"var myStorage = {",
" \"car\": {",
" \"inside\": {",
" \"glove box\": \"maps\",",
" \"passenger seat\": \"crumbs\"",
" },",
" \"outside\": {",
" \"trunk\": \"jack\"",
" }",
" }",
"};",
"",
"// Only change code below this line",
"",
"var gloveBoxContents = \"\"; // Change this line",
""
],
"tail": [
"(function(x) { ",
" if(typeof x != 'undefined') { ",
" return \"gloveBoxContents = \" + x;",
" }",
" return \"gloveBoxContents is undefined\";",
"})(gloveBoxContents);"
],
"solutions": [
"var myStorage = { \n \"car\":{ \n \"inside\":{ \n \"glove box\":\"maps\",\n \"passenger seat\":\"crumbs\"\n },\n \"outside\":{ \n \"trunk\":\"jack\"\n }\n }\n};\nvar gloveBoxContents = myStorage.car.inside[\"glove box\"];"
],
"tests": [
"assert(gloveBoxContents === \"maps\", 'message: <code>gloveBoxContents</code> should equal \"maps\"');",
"assert(/=\\s*myStorage\\.car\\.inside\\[(\"|')glove box\\1\\]/g.test(code), 'message: Use dot and bracket notation to access <code>myStorage</code>');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244cd",
"title": "Accessing Nested Arrays in JSON",
"description": [
"As we have seen in earlier examples, JSON objects can contain both nested objects and nested arrays. Similar to accessing nested objects, Array bracket notation can be chained to access nested arrays.",
"Here is an example of how to access a nested array:",
"<blockquote>var ourPets = { <br> \"cats\": [<br> \"Meowzer\",<br> \"Fluffy\",<br> \"Kit-Cat\"<br> ],<br> \"dogs\": [<br> \"Spot\",<br> \"Bowser\",<br> \"Frankie\"<br> ]<br>};<br>ourPets.cats[1]; // \"Fluffy\"<br>ourPets.dogs[0]; // \"Spot\"</blockquote>",
"<h4>Instructions</h4>",
"Retrieve the second tree from the variable <code>myPlants</code> using object dot and array bracket notation."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Setup",
"var myPlants = [",
" { ",
" type: \"flowers\",",
" list: [",
" \"rose\",",
" \"tulip\",",
" \"dandelion\"",
" ]",
" },",
" {",
" type: \"trees\",",
" list: [",
" \"fir\",",
" \"pine\",",
" \"birch\"",
" ]",
" } ",
"];",
"",
"// Only change code below this line",
"",
"var secondTree = \"\"; // Change this line",
""
],
"tail": [
"(function(x) { ",
" if(typeof x != 'undefined') { ",
" return \"secondTree = \" + x;",
" }",
" return \"secondTree is undefined\";",
"})(secondTree);"
],
"solutions": [
"var myPlants = [\n { \n type: \"flowers\",\n list: [\n \"rose\",\n \"tulip\",\n \"dandelion\"\n ]\n },\n {\n type: \"trees\",\n list: [\n \"fir\",\n \"pine\",\n \"birch\"\n ]\n } \n];\n\n// Only change code below this line\n\nvar secondTree = myPlants[1].list[1];"
],
"tests": [
"assert(secondTree === \"pine\", 'message: <code>secondTree</code> should equal \"pine\"');",
"assert(/=\\s*myPlants\\[1\\].list\\[1\\]/.test(code), 'message: Use dot and bracket notation to access <code>myPlants</code>');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244cf",
"title": "Record Collection",
"description": [
"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 <code>id</code>, a property (<code>prop</code>), and a <code>value</code>.",
"For the given <code>id</code> in <code>collection</code>:",
"If <code>value</code> is non-blank (<code>value !== \"\"</code>) and <code>prop</code> is not <code>\"tracks\"</code> then update or set the <code>value</code> for the <code>prop</code>.",
"If the <code>prop</code> is <code>\"tracks\"</code> and <code>value</code> is non-blank, push the <code>value</code> onto the end of the <code>tracks</code> array.",
"If <code>value</code> is blank, delete that <code>prop</code>.",
"Always return the entire collection object.",
"<strong>Note</strong><br>Don't forget to use <code>bracket notation</code> when <a href=\"accessing-objects-properties-with-variables\" target=\"_blank\">accessing object properties with variables</a>."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Setup",
"var collection = {",
" 2548: {",
" album: \"Slippery When Wet\",",
" artist: \"Bon Jovi\",",
" tracks: [ ",
" \"Let It Rock\", ",
" \"You Give Love a Bad Name\" ",
" ]",
" },",
" 2468: {",
" album: \"1999\",",
" artist: \"Prince\",",
" tracks: [ ",
" \"1999\", ",
" \"Little Red Corvette\" ",
" ]",
" },",
" 1245: {",
" artist: \"Robert Palmer\",",
" tracks: [ ]",
" },",
" 5439: {",
" album: \"ABBA Gold\"",
" }",
"};",
"// Keep a copy of the collection for tests",
"var collectionCopy = JSON.parse(JSON.stringify(collection));",
"",
"// Only change code below this line",
"function update(id, prop, value) {",
"",
"",
" return collection;",
"}",
"",
"// Alter values below to test your code",
"update(5439, \"artist\", \"ABBA\");",
""
],
"tail": [
"(function(x) { return \"collection = \\n\" + JSON.stringify(x, '\\n', 2); })(collection);"
],
"solutions": [
"var collection = {\n 2548: {\n album: \"Slippery When Wet\",\n artist: \"Bon Jovi\",\n tracks: [ \n \"Let It Rock\", \n \"You Give Love a Bad Name\" \n ]\n },\n 2468: {\n album: \"1999\",\n artist: \"Prince\",\n tracks: [ \n \"1999\", \n \"Little Red Corvette\" \n ]\n },\n 1245: {\n artist: \"Robert Palmer\",\n tracks: [ ]\n },\n 5439: {\n album: \"ABBA Gold\"\n }\n};\n// Keep a copy of the collection for tests\nvar collectionCopy = JSON.parse(JSON.stringify(collection));\n\n// Only change code below this line\nfunction update(id, prop, value) {\n if(value !== \"\") {\n if(prop === \"tracks\") {\n collection[id][prop].push(value);\n } else {\n collection[id][prop] = value;\n }\n } else {\n delete collection[id][prop];\n }\n\n return collection;\n}"
],
"tests": [
"collection = collectionCopy; assert(update(5439, \"artist\", \"ABBA\")[5439][\"artist\"] === \"ABBA\", 'message: After <code>update(5439, \"artist\", \"ABBA\")</code>, <code>artist</code> should be <code>\"ABBA\"</code>');",
"update(2548, \"artist\", \"\"); assert(!collection[2548].hasOwnProperty(\"artist\"), 'message: After <code>update(2548, \"artist\", \"\")</code>, <code>artist</code> should not be set');",
"assert(update(1245, \"tracks\", \"Addicted to Love\")[1245][\"tracks\"].length === 1, 'message: After <code>update(1245, \"tracks\", \"Addicted to Love\")</code>, <code>tracks</code> should have a length of <code>1</code>');",
"update(2548, \"tracks\", \"\"); assert(!collection[2548].hasOwnProperty(\"tracks\"), 'message: After <code>update(2548, \"tracks\", \"\")</code>, <code>tracks</code> should not be set');"
],
"type": "checkpoint",
"challengeType": 1
},
{
"id": "cf1111c1c11feddfaeb5bdef",
"title": "Iterate with JavaScript For Loops",
"description": [
"You can run the same code multiple times by using a loop.",
"The most common type of JavaScript loop is called a \"<code>for loop</code>\" because it runs \"for\" a specific number of times.",
"For loops are declared with three optional expressions separated by semicolons:",
"<code>for ([initialization]; [condition]; [final-expression])</code>",
"The <code>initialization</code> statement is executed one time only before the loop starts. It is typically used to define and setup your loop variable.",
"The <code>condition</code> statement is evaluated at the beginning of every loop iteration and will continue as long as it evalutes to <code>true</code>. When <code>condition</code> is <code>false</code> at the start of the iteration, the loop will stop executing. This means if <code>condition</code> starts as <code>false</code>, your loop will never execute.",
"The <code>final-expression</code> is executed at the end of each loop iteration, prior to the next <code>condition</code> check and is usually used to increment or decrement your loop counter.",
"In the following example we initialize with <code>i = 0</code> and iterate while our condition <code>i < 5</code> is true. We'll increment <code>i</code> by <code>1</code> in each loop iteration with <code>i++</code> as our <code>final-expression</code>.",
"<blockquote>var ourArray = [];<br>for (var i = 0; i < 5; i++) {<br> ourArray.push(i);<br>}</blockquote>",
"<code>ourArray</code> will now contain <code>[0,1,2,3,4]</code>.",
"<h4>Instructions</h4>",
"Use a <code>for</code> loop to work to push the values 1 through 5 onto <code>myArray</code>."
],
"challengeSeed": [
"// Example",
"var ourArray = [];",
"",
"for (var i = 0; i < 5; i++) {",
" ourArray.push(i);",
"}",
"",
"// Setup",
"var myArray = [];",
"",
"// Only change code below this line.",
"",
""
],
"tail": [
"if (typeof myArray !== \"undefined\"){(function(){return myArray;})();}"
],
"solutions": [
"var ourArray = [];\nfor (var i = 0; i < 5; i++) {\n ourArray.push(i);\n}\nvar myArray = [];\nfor (var i = 1; i < 6; i++) {\n myArray.push(i);\n}"
],
"tests": [
"assert(code.match(/for\\s*\\(/g).length > 1, 'message: You should be using a <code>for</code> loop for this.');",
"assert.deepEqual(myArray, [1,2,3,4,5], 'message: <code>myArray</code> should equal <code>[1,2,3,4,5]</code>.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Iterar con JavaScript en ciclos",
"descriptionEs": [
"Puede ejecutar el mismo código varias veces mediante el uso de un ciclo.",
"El tipo más común de bucle de JavaScript se llama \"ciclo for\"porque se ejecuta \"por\" (for) un número específico de veces.",
"Los ciclos for se declaran con tres expresiones opcionales separadas por punto y coma:",
"<code>for ([inicialización]; [condición]; [expresión-final])</code>",
"La <code>inicialización</code> se ejecuta sólo una vez antes de que empiece el ciclo. Normalmente se utiliza para definir e inicializar su variable de ciclo. ",
"La expresión <code>condición</code> se evalúa al principio de cada iteración del ciclo y continuará en el ciclo siempre y cuando sea verdadera (<code>true</code>). Cuando la <code>condición</code> sea falsa (<code>false</code>) al comienzo de la iteración, se detendrá la ejecución del ciclo. Esto significa que si la <code>condición</code> inicia en el valor falso <code>false</code>, el ciclo no se ejecutará. ",
"La <code>expresión final</code> se ejecuta al final de cada repetición del ciclo, antes del siguiente chequeo de la <code>condición</code> y se utiliza generalmente para aumentar o disminuir el contador del ciclo.",
"En el siguiente ejemplo inicializamos con <code>i = 0</code> e iteramos mientras nuestra condición <code>i <5</code> sea verdadera. Vamos a incrementar <code>i</code> en <code>1</code> en cada iteración del ciclo con <code>i++</code> como nuestra <code>expresión final</code>. ",
"<code>var ourArray = [];</code>",
"<code>for (var i = 0; i < 5; i++) {</code>",
"<code>&nbsp;&nbsp;ourArray.push(i);</code>",
"<code>}</code>",
"<code>ourArray</code> ahora contendrá <code>[0,1,2,3,4]</code>.",
"Vamos a utilizar un ciclo <code>for</code> para empujar los valores del 1 al 5 en <code>myArray</code>."
]
},
{
"id": "56104e9e514f539506016a5c",
"title": "Iterate Odd Numbers With a For Loop",
"description": [
"For loops don't have to iterate one at a time. By changing our <code>final-expression</code>, we can count by even numbers.",
"We'll start at <code>i = 0</code> and loop while <code>i < 10</code>. We'll increment <code>i</code> by 2 each loop with <code>i += 2</code>.",
"<blockquote>var ourArray = [];<br>for (var i = 0; i < 10; i += 2) {<br> ourArray.push(i);<br>}</blockquote>",
"<code>ourArray</code> will now contain <code>[0,2,4,6,8]</code>.",
"Let's change our <code>initialization</code> so we can count by odd numbers.",
"<h4>Instructions</h4>",
"Push the odd numbers from 1 through 9 to <code>myArray</code> using a <code>for</code> loop."
],
"challengeSeed": [
"// Example",
"var ourArray = [];",
"",
"for (var i = 0; i < 10; i += 2) {",
" ourArray.push(i);",
"}",
"",
"// Setup",
"var myArray = [];",
"",
"// Only change code below this line.",
"",
""
],
"tail": [
"if(typeof myArray !== \"undefined\"){(function(){return myArray;})();}"
],
"solutions": [
"var ourArray = [];\nfor (var i = 0; i < 10; i += 2) {\n ourArray.push(i);\n}\nvar myArray = [];\nfor (var i = 1; i < 10; i += 2) {\n myArray.push(i);\n}"
],
"tests": [
"assert(code.match(/for\\s*\\(/g).length > 1, 'message: You should be using a <code>for</code> loop for this.');",
"assert.deepEqual(myArray, [1,3,5,7,9], 'message: <code>myArray</code> should equal <code>[1,3,5,7,9]</code>.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Itera por los números pares con un ciclo for",
"descriptionEs": [
"Los ciclos <code>for</code> no siempre iteran incrementado de a uno. Cambiando nuestra <code>expresión final</code>, podemos contar los números pares.",
"Vamos a empezar con <code>i = 0</code> e iterar mientras <code>i <10</code>. Vamos a incrementar <code>i</code> de a 2 en cada iteración <code>i + = 2</code>. ",
"<code>var ourArray = [];</code>",
"<code>for (var i = 0; i < 10; i += 2) {</code>",
"<code>&nbsp;&nbsp;ourArray.push(i);</code>",
"<code>}</code>",
"<code>ourArray</code> ahora contendrá <code>[0,2,4,6,8]</code>.",
"Vamos a cambiar nuestra <code>inicialización</code> y <code>expresión final</code> para que podamos contar los números impares.",
"Empuja los números impares del 1 al 9 en <code>myArray</code> utilizando un ciclo <code>for</code>."
]
},
{
"id": "56105e7b514f539506016a5e",
"title": "Count Backwards With a For Loop",
"description": [
"A for loop can also count backwards, so long as we can define the right conditions.",
"In order to count backwards by twos, we'll need to change our <code>initialization</code>, <code>condition</code>, and <code>final-expression</code>.",
"We'll start at <code>i = 10</code> and loop while <code>i > 0</code>. We'll decrement <code>i</code> by 2 each loop with <code>i -= 2</code>.",
"<blockquote>var ourArray = [];<br>for (var i=10; i > 0; i-=2) {<br> ourArray.push(i);<br>}</blockquote>",
"<code>ourArray</code> will now contain <code>[10,8,6,4,2]</code>.",
"Let's change our <code>initialization</code> and <code>final-expression</code> so we can count backward by twos by odd numbers.",
"<h4>Instructions</h4>",
"Push the odd numbers from 9 through 1 to <code>myArray</code> using a <code>for</code> loop."
],
"challengeSeed": [
"// Example",
"var ourArray = [];",
"",
"for (var i = 10; i > 0; i -= 2) {",
" ourArray.push(i);",
"}",
"",
"// Setup",
"var myArray = [];",
"",
"// Only change code below this line.",
""
],
"tail": [
"if(typeof myArray !== \"undefined\"){(function(){return myArray;})();}"
],
"solutions": [
"var ourArray = [];\nfor (var i = 10; i > 0; i -= 2) {\n ourArray.push(i);\n}\nvar myArray = [];\nfor (var i = 9; i > 0; i -= 2) {\n myArray.push(i);\n}"
],
"tests": [
"assert(code.match(/for\\s*\\(/g).length > 1, 'message: You should be using a <code>for</code> loop for this.');",
"assert.deepEqual(myArray, [9,7,5,3,1], 'message: <code>myArray</code> should equal <code>[9,7,5,3,1]</code>.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Cuenta hacia atrás con un ciclo for",
"descriptionEs": [
"Un ciclo también puede contar hacia atrás, siempre y cuando definamos las condiciones adecuadas.",
"Para contar hacia atrás de dos en dos, tendremos que cambiar nuestra <code>inicialización</code>, la <code>condición</code> y la <code>última-expresión</code>.",
"Vamos a empezar con <code>i = 10</code> e iteraremos mientras <code>i > 0</code>. Vamos a decrementar <code>i</code> de a 2 por cada iteración con <code>i -= 2</code>. ",
"<code>var ourArray = [];</code>",
"<code>for (var i = 10; i > 0; i -= 2) {</code>",
"<code>&nbsp;&nbsp;ourArray.push(i);</code>",
"<code>}</code>",
"<code>ourArray</code> ahora contendrá <code>[10,8,6,4,2]</code>.",
"Vamos a cambiar nuestra <code>inicialización</code> y la <code>expresión final</code> para que podamos contar hacia atrás de dos en dos pero números impares.",
"Empuja los números impares del 9 a 1 en <code>myArray</code> utilizando un ciclo <code>for</code>."
]
},
{
"id": "5675e877dbd60be8ad28edc6",
"title": "Iterate Through an Array with a For Loop",
"description": [
"A common task in Javascript is to iterate through the contents of an array. One way to do that is with a <code>for</code> loop. This code will output each element of the array <code>arr</code> to the console:",
"<blockquote>var arr = [10,9,8,7,6];<br>for (var i=0; i < arr.length; i++) {<br> console.log(arr[i]);<br>}</blockquote>",
"Remember that Arrays have zero-based numbering, which means the last index of the array is length - 1. Our <dfn>condition</dfn> for this loop is <code>i < arr.length</code>, which stops when <code>i</code> is at length - 1.",
"<h4>Instructions</h4>",
"Declare and initialize a variable <code>total</code> to <code>0</code>. Use a <code>for</code> loop to add the value of each element of the <code>myArr</code> array to <code>total</code>."
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"// Example",
"var ourArr = [ 9, 10, 11, 12];",
"var ourTotal = 0;",
"",
"for (var i = 0; i < ourArr.length; i++) {",
" ourTotal += ourArr[i];",
"}",
"",
"// Setup",
"var myArr = [ 2, 3, 4, 5, 6];",
"",
"// Only change code below this line",
"",
""
],
"tail": [
"(function(){if(typeof total !== 'undefined') { return \"total = \" + total; } else { return \"total is undefined\";}})()"
],
"solutions": [
"var ourArr = [ 9, 10, 11, 12];\nvar ourTotal = 0;\n\nfor (var i = 0; i < ourArr.length; i++) {\n ourTotal += ourArr[i];\n}\n\nvar myArr = [ 2, 3, 4, 5, 6];\nvar total = 0;\n\nfor (var i = 0; i < myArr.length; i++) {\n total += myArr[i];\n}"
],
"tests": [
"assert(code.match(/var\\s*total\\s*=\\s*0\\s*;/), 'message: <code>total</code> should be declared and initialized to 0');",
"assert(total === 20, 'message: <code>total</code> should equal 20');",
"assert(code.match(/for\\s*\\(/g).length > 1 && code.match(/myArr\\s*\\[/), 'message: You should use a <code>for</code> loop to iterate through <code>myArr</code>');",
"assert(!code.match(/total[\\s\\+\\-]*=\\s*(\\d(?!\\s*;)|[1-9])/g), 'message: Do not set <code>total</code> to 20 directly');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "56533eb9ac21ba0edf2244e1",
"title": "Nesting For Loops",
"description": [
"If you have a multi-dimensional array, you can use the same logic as the prior waypoint to loop through both the array and any sub-arrays. Here is an example:",
"<blockquote>var arr = [<br> [1,2], [3,4], [5,6]<br>];<br>for (var i=0; i &lt; arr.length; i++) {<br> for (var j=0; j &lt; arr[i].length; j++) {<br> console.log(arr[i][j]);<br> }<br>}</blockquote>",
"This outputs each sub-element in <code>arr</code> one at a time. Note that for the inner loop, we are checking the <code>.length</code> of <code>arr[i]</code>, since <code>arr[i]</code> is itself an array.",
"<h4>Instructions</h4>",
"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>"
],
"releasedOn": "January 1, 2016",
"challengeSeed": [
"function multiplyAll(arr) {",
" var product = 1;",
" // Only change code below this line",
" ",
" // Only change code above this line",
" return product;",
"}",
"",
"// Modify values below to test your code",
"multiplyAll([[1,2],[3,4],[5,6,7]]);",
""
],
"tail": [
""
],
"solutions": [
"function multiplyAll(arr) {\n var product = 1;\n for (var i = 0; i < arr.length; i++) {\n for (var j = 0; j < arr[i].length; j++) {\n product *= arr[i][j];\n }\n }\n return product;\n}\n\nmultiplyAll([[1,2],[3,4],[5,6,7]]);"
],
"tests": [
"assert(multiplyAll([[1],[2],[3]]) === 6, 'message: <code>multiplyAll([[1],[2],[3]]);</code> should return <code>6</code>');",
"assert(multiplyAll([[1,2],[3,4],[5,6,7]]) === 5040, 'message: <code>multiplyAll([[1,2],[3,4],[5,6,7]])</code> should return <code>5040</code>');",
"assert(multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]]) === 54, 'message: <code>multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]]);)</code> should return <code>54</code>');"
],
"type": "waypoint",
"challengeType": 1
},
{
"id": "cf1111c1c11feddfaeb1bdef",
"title": "Iterate with JavaScript While Loops",
"description": [
"You can run the same code multiple times by using a loop.",
"Another type of JavaScript loop is called a \"<code>while loop</code>\", because it runs \"while\" a specified condition is true and stops once that condition is no longer true.",
"<blockquote>var ourArray = [];<br>var i = 0;<br>while(i < 5) {<br> ourArray.push(i);<br> i++;<br>}</blockquote>",
"Let's try getting a while loop to work by pushing values to an array.",
"<h4>Instructions</h4>",
"Push the numbers 0 through 4 to <code>myArray</code> using a <code>while</code> loop."
],
"challengeSeed": [
"// Setup",
"var myArray = [];",
"",
"// Only change code below this line.",
"",
""
],
"tail": [
"if(typeof myArray !== \"undefined\"){(function(){return myArray;})();}"
],
"solutions": [
"var myArray = [];\nvar i = 0;\nwhile(i < 5) {\n myArray.push(i);\n i++;\n}"
],
"tests": [
"assert(code.match(/while/g), 'message: You should be using a <code>while</code> loop for this.');",
"assert.deepEqual(myArray, [0,1,2,3,4], 'message: <code>myArray</code> should equal <code>[0,1,2,3,4]</code>.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Iterar con JavaScript con ciclos while",
"descriptionEs": [
"Puede ejecutar el mismo código varias veces mediante el uso de un ciclo.",
"Otro tipo de ciclo de JavaScript se llama un ciclo \"while\", ya que se ejecuta, \"mientras que\" algo sea cierto y se detiene una vez que ya no sea así.",
"<code>var ourArray = [];</code>",
"<code>var i = 0;</code>",
"<code>while(i < 5) {</code>",
"<code>&nbsp;&nbsp;ourArray.push(i);</code>",
"<code>&nbsp;&nbsp;i++;</code>",
"<code>}</code>",
"Intentemos que un ciclo <code>while</code> empuje valores en un vector.",
"Empuja los números de 0 a 4 para <code>myArray</code> utilizando un ciclo <code>while</code>."
]
},
{
"id": "5688e62ea601b2482ff8422b",
"title": "Profile Lookup",
"description": [
"We have an array of objects representing different people in our contacts lists.",
"A <code>lookUp</code> function that takes <code>firstName</code> and a property (<code>prop</code>) as arguments has been pre-written for you.",
"The function should check if <code>firstName</code> is an actual contact's <code>firstName</code> and the given property (<code>prop</code>) is a property of that contact.",
"If both are true, then return the \"value\" of that property.",
"If <code>firstName</code> does not correspond to any contacts then return <code>\"No such contact\"</code>",
"If <code>prop</code> does not correspond to any valid properties then return <code>\"No such property\"</code>",
""
],
"releasedOn": "January 8, 2016",
"challengeSeed": [
"//Setup",
"var contacts = [",
" {",
" \"firstName\": \"Akira\",",
" \"lastName\": \"Laine\",",
" \"number\": \"0543236543\",",
" \"likes\": [\"Pizza\", \"Coding\", \"Brownie Points\"]",
" },",
" {",
" \"firstName\": \"Harry\",",
" \"lastName\": \"Potter\",",
" \"number\": \"0994372684\",",
" \"likes\": [\"Hogwarts\", \"Magic\", \"Hagrid\"]",
" },",
" {",
" \"firstName\": \"Sherlock\",",
" \"lastName\": \"Holmes\",",
" \"number\": \"0487345643\",",
" \"likes\": [\"Intriguing Cases\", \"Violin\"]",
" },",
" {",
" \"firstName\": \"Kristian\",",
" \"lastName\": \"Vos\",",
" \"number\": \"unknown\",",
" \"likes\": [\"Javascript\", \"Gaming\", \"Foxes\"]",
" }",
"];",
"",
"",
"function lookUp(firstName, prop){",
"// Only change code below this line",
"",
"// Only change code above this line",
"}",
"",
"// Change these values to test your function",
"lookUp(\"Akira\", \"likes\");"
],
"solutions": [
"var contacts = [\n {\n \"firstName\": \"Akira\",\n \"lastName\": \"Laine\",\n \"number\": \"0543236543\",\n \"likes\": [\"Pizza\", \"Coding\", \"Brownie Points\"]\n },\n {\n \"firstName\": \"Harry\",\n \"lastName\": \"Potter\",\n \"number\": \"0994372684\",\n \"likes\": [\"Hogwarts\", \"Magic\", \"Hagrid\"]\n },\n {\n \"firstName\": \"Sherlock\",\n \"lastName\": \"Holmes\",\n \"number\": \"0487345643\",\n \"likes\": [\"Intriguing Cases\", \"Violin\"]\n },\n {\n \"firstName\": \"Kristian\",\n \"lastName\": \"Vos\",\n \"number\": \"unknown\",\n \"likes\": [\"Javascript\", \"Gaming\", \"Foxes\"]\n },\n];\n\n\n//Write your function in between these comments\nfunction lookUp(name, prop){\n for(var i in contacts){\n if(contacts[i].firstName === name) {\n return contacts[i][prop] || \"No such property\";\n }\n }\n return \"No such contact\";\n}\n//Write your function in between these comments\n\nlookUp(\"Akira\", \"likes\");"
],
"tests": [
"assert(lookUp('Kristian','lastName') === \"Vos\", 'message: <code>\"Kristian\", \"lastName\"</code> should return <code>\"Vos\"</code>');",
"assert.deepEqual(lookUp(\"Sherlock\", \"likes\"), [\"Intriguing Cases\", \"Violin\"], 'message: <code>\"Sherlock\", \"likes\"</code> should return <code>[\"Intriguing Cases\", \"Violin\"]</code>');",
"assert(typeof lookUp(\"Harry\", \"likes\") === \"object\", 'message: <code>\"Harry\",\"likes\"</code> should return an array');",
"assert(lookUp(\"Bob\", \"number\") === \"No such contact\", 'message: <code>\"Bob\", \"number\"</code> should return \"No such contact\"');",
"assert(lookUp(\"Akira\", \"address\") === \"No such property\", 'message: <code>\"Akira\", \"address\"</code> should return \"No such property\"');"
],
"type": "checkpoint",
"challengeType": 1
},
{
"id": "cf1111c1c11feddfaeb9bdef",
"title": "Generate Random Fractions with JavaScript",
"description": [
"Random numbers are useful for creating random behavior.",
"JavaScript has a <code>Math.random()</code> function that generates a random decimal number between <code>0</code> (inclusive) and not quite up to <code>1</code> (exclusive). Thus <code>Math.random()</code> can return a <code>0</code> but never quite return a <code>1</code>",
"<strong>Note</strong><br>Like <a href='waypoint-storing-values-with-the-equal-operator' target='_blank'>Storing Values with the Equal Operator</a>, all function calls will be resolved before the <code>return</code> executes, so we can simply <code>return</code> the value of the <code>Math.random()</code> function.",
"<h4>Instructions</h4>",
"Change <code>myFunction</code> to return a random number instead of returning <code>0</code>."
],
"challengeSeed": [
"function myFunction() {",
"",
" // Only change code below this line.",
"",
" return 0;",
"",
" // Only change code above this line.",
"}"
],
"tail": [
"(function(){return myFunction();})();"
],
"solutions": [
"function myFunction() {\n return Math.random();\n}"
],
"tests": [
"assert(typeof myFunction() === \"number\", 'message: <code>myFunction</code> should return a random number.');",
"assert((myFunction()+''). match(/\\./g), 'message: The number returned by <code>myFunction</code> should be a decimal.');",
"assert(code.match(/Math\\.random/g).length >= 0, 'message: You should be using <code>Math.random</code> to generate the random decimal number.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Generar fracciones al azar con JavaScript",
"descriptionEs": [
"Los números aleatorios son útiles para crear un comportamiento aleatorio.",
"JavaScript tiene una función <code>Math.random()</code> que genera un número decimal aleatorio.",
"Cambia <code>myFunction</code> para que devuelva un número al azar en lugar de devolver <code>0</code>.",
"Ten en cuenta que puedes retornar lo retornado por una función, igual que harías para devolver una variable o valor."
]
},
{
"id": "cf1111c1c12feddfaeb1bdef",
"title": "Generate Random Whole Numbers with JavaScript",
"description": [
"It's great that we can generate random decimal numbers, but it's even more useful if we use it to generate random whole numbers.",
"<ol><li>Use <code>Math.random()</code> to generate a random decimal.</li><li>Multiply that random decimal by <code>20</code>.</li><li>Use another function, <code>Math.floor()</code> to round the number down to its nearest whole number.</li></ol>",
"Remember that <code>Math.random()</code> can never quite return a <code>1</code> and, because we're rounding down, it's impossible to actually get <code>20</code>. This technique will give us a whole number between <code>0</code> and <code>19</code>.",
"Putting everything together, this is what our code looks like:",
"<code>Math.floor(Math.random() * 20);</code>",
"We are calling <code>Math.random()</code>, multiplying the result by 20, then passing the value to <code>Math.floor()</code> function to round the value down to the nearest whole number.",
"<h4>Instructions</h4>",
"Use this technique to generate and return a random whole number between <code>0</code> and <code>9</code>."
],
"challengeSeed": [
"var randomNumberBetween0and19 = Math.floor(Math.random() * 20);",
"",
"function myFunction() {",
"",
" // Only change code below this line.",
"",
" return Math.random();",
"}"
],
"tail": [
"(function(){return myFunction();})();"
],
"solutions": [
"var randomNumberBetween0and19 = Math.floor(Math.random() * 20);\n\nfunction myFunction() {\n return Math.floor(Math.random() * 10);\n}"
],
"tests": [
"assert(typeof myFunction() === \"number\" && (function(){var r = myFunction();return Math.floor(r) === r;})(), 'message: The result of <code>myFunction</code> should be a whole number.');",
"assert(code.match(/Math.random/g).length > 1, 'message: You should be using <code>Math.random</code> to generate a random number.');",
"assert(code.match(/\\(\\s*?Math.random\\s*?\\(\\s*?\\)\\s*?\\*\\s*?10\\s*?\\)/g) || code.match(/\\(\\s*?10\\s*?\\*\\s*?Math.random\\s*?\\(\\s*?\\)\\s*?\\)/g), 'message: You should have multiplied the result of <code>Math.random</code> by 10 to make it a number that is between zero and nine.');",
"assert(code.match(/Math.floor/g).length > 1, 'message: You should use <code>Math.floor</code> to remove the decimal part of the number.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Genera números aleatorios enteros con JavaScript",
"descriptionEs": [
"Es muy bueno que podamos generar números decimales al azar, pero es aún más útil si lo utilizamos para generar números enteros aleatorios.",
"En primer lugar, vamos a usar <code>Math.random()</code> para generar un decimal aleatorio.",
"Entonces vamos a multiplicar este decimal azar por 20.",
"Por último, vamos a usar otra función, <code>Math.floor()</code> para redondear el número hasta su número entero más próximo.",
"Esta técnica nos da un número entero entre 0 y 19.",
"Tenga en cuenta que debido a que estamos redondeando, es imposible obtener 20.",
"Poniendo todo junto, así es como se ve nuestro código:",
"<code>Math.floor(Math.random() * 20);</code>",
"¿Ves como <code>Math.floor</code> toma <code>(Math.random() * 20)</code> como su argumento? Así es - puedes pasar el resultado de un función como argumento de otra función.",
"usemos esta técnica para generar y devolver un número entero aleatorio entre 0 y 9."
]
},
{
"id": "cf1111c1c12feddfaeb2bdef",
"title": "Generate Random Whole Numbers within a Range",
"description": [
"Instead of generating a random number between zero and a given number like we did before, we can generate a random number that falls within a range of two specific numbers.",
"To do this, we'll define a minimum number <code>min</code> and a maximum number <code>max</code>.",
"Here's the formula we'll use. Take a moment to read it and try to understand what this code is doing:",
"<code>Math.floor(Math.random() * (max - min + 1)) + min</code>",
"<h4>Instructions</h4>",
"Create a function called <code>randomRange</code> that takes a range <code>myMin</code> and <code>myMax</code> and returns a random number that's greater than or equal to <code>myMin</code>, and is less than or equal to <code>myMax</code>, inclusive."
],
"challengeSeed": [
"// Example",
"function ourFunction(ourMin, ourMax) {",
"",
" return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin;",
"}",
"",
"ourFunction(1, 9);",
"",
"// Only change code below this line.",
"",
"function randomRange(myMin, myMax) {",
"",
" return 0; // Change this line",
"",
"}",
"",
"// Change these values to test your function",
"var myRandom = randomRange(5, 15);"
],
"tail": [
"var calcMin = 100;",
"var calcMax = -100;",
"for(var i = 0; i < 100; i++) {",
" var result = randomRange(5,15);",
" calcMin = Math.min(calcMin, result);",
" calcMax = Math.max(calcMax, result);",
"}",
"(function(){",
" if(typeof myRandom === 'number') {",
" return \"myRandom = \" + myRandom;",
" } else {",
" return \"myRandom undefined\";",
" }",
"})();"
],
"solutions": [
"function randomRange(myMin, myMax) {\n return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;\n}"
],
"tests": [
"assert(calcMin === 5, 'message: The random number generated by <code>randomRange</code> should be greater than or equal to your minimum number, <code>myMin</code>.');",
"assert(calcMax === 15, 'message: The random number generated by <code>randomRange</code> should be less than or equal to your maximum number, <code>myMax</code>.');",
"assert(randomRange(0,1) % 1 === 0 , 'message: The random number generated by <code>randomRange</code> should be an integer, not a decimal.');",
"assert((function(){if(code.match(/myMax/g).length > 1 && code.match(/myMin/g).length > 2 && code.match(/Math.floor/g) && code.match(/Math.random/g)){return true;}else{return false;}})(), 'message: <code>randomRange</code> should use both <code>myMax</code> and <code>myMin</code>, and return a random number in your range.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Genera números aleatorios enteros dentro de un rango",
"descriptionEs": [
"En lugar de generar un número aleatorio entre cero y un número dado como lo hicimos antes, podemos generar un número aleatorio que caiga dentro de un rango de dos números específicos.",
"Para ello, vamos a definir un número mínimo <code>min</code> y un número máximo <code>max</code>.",
"He aquí la fórmula que utilizaremos. Tómate un momento para leer y tratar de entender lo que el código está haciendo: ",
"<code>Math.floor(Math.random() * (max - min + 1)) + min</code>",
"Definir dos variables: <code>myMin</code> y <code>myMax</code>, y asignales valores enteros.",
"A continuación, crea una función llamada <code>myFunction</code> que devuelva un número aleatorio mayor o igual a <code>myMin</code>, y menor o igual a <code>myMax</code>. "
]
},
{
"id": "cf1111c1c12feddfaeb6bdef",
"title": "Sift through Text with Regular Expressions",
"description": [
"<code>Regular expressions</code> are used to find certain words or patterns inside of <code>strings</code>.",
"For example, if we wanted to find the word <code>the</code> in the string <code>The dog chased the cat</code>, we could use the following <code>regular expression</code>: <code>/the/gi</code>",
"Let's break this down a bit:",
"<code>/</code> is the start of the regular expression.",
"<code>the</code> is the pattern we want to match.",
"<code>/</code> is the end of the regular expression.",
"<code>g</code> means <code>global</code>, which causes the pattern to return all matches in the string, not just the first one.",
"<code>i</code> means that we want to ignore the case (uppercase or lowercase) when searching for the pattern.",
"<h4>Instructions</h4>",
"Select all the occurrences of the word <code>and</code> in <code>testString</code>.",
"You can do this by replacing the <code>.</code> part of the regular expression with the word <code>and</code>."
],
"head": [
""
],
"challengeSeed": [
"// Setup",
"var testString = \"Ada Lovelace and Charles Babbage designed the first computer and the software that would have run on it.\";",
"",
"// Example",
"var expressionToGetSoftware = /software/gi;",
"var softwareCount = testString.match(expressionToGetSoftware).length;",
" ",
"",
"// Only change code below this line.",
"",
"var expression = /./gi; // Change this Line",
"",
"// Only change code above this line",
"",
"// This code counts the matches of expression in testString",
"var andCount = testString.match(expression).length;",
""
],
"tail": [
"(function(){return andCount;})();"
],
"solutions": [
"var testString = \"Ada Lovelace and Charles Babbage designed the first computer and the software that would have run on it.\";\nvar expression = /and/gi; // Change this Line\nvar andCount = testString.match(expression).length;"
],
"tests": [
"assert(andCount==2, 'message: Your <code>regular expression</code> should find two occurrences of the word <code>and</code>.');",
"assert(code.match(/\\/and\\/gi/), 'message: Use <code>regular expressions</code> to find the word <code>and</code> in <code>testString</code>.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Examina un texto con expresiones regulares",
"descriptionEs": [
"Las <code>expresiones regulares</code> se utilizan para encontrar ciertas palabras o patrones dentro de <code>cadenas</code>.",
"Por ejemplo, si quisiéramos encontrar la palabra <code>el</code> en la cadena <code>El perro persiguió al gato el lunes</code>, podríamos utilizar la siguiente <code>expresión regular</code>: <code>/el/gi</code> ",
"Vamos a dividirla un poco:",
"<code>el</code> es el patrón con el que queremos coincidir.",
"<code>g</code> significa que queremos buscar el patrón en toda la cadena y no sólo la primera ocurrencia.",
"<code>i</code> significa que queremos ignorar la capitalización (en mayúsculas o minúsculas) cuando se busque el patrón.",
"Las <code>expresiones regulares</code> se escriben rodeando el patrón con símbolos de barra <code>/</code>.",
"Vamos a tratar de seleccionar todas las apariciones de la palabra <code>and</code> en la cadena <code>Ada Lovelace and Charles Babbage designed the first computer and the software that would have run on it</code>.",
"Podemos hacer esto sustituyendo la parte <code>.</code> de nuestra expresión regular por la palabra <code>and</code>."
]
},
{
"id": "cf1111c1c12feddfaeb7bdef",
"title": "Find Numbers with Regular Expressions",
"description": [
"We can use special selectors in <dfn>Regular Expressions</dfn> to select a particular type of value.",
"One such selector is the digit selector <code>\\d</code> which is used to retrieve one digit (e.g. numbers 0 to 9) in a string.",
"In JavaScript, it is used like this: <code>/\\d/g</code>.",
"Appending a plus sign (<code>+</code>) after the selector, e.g. <code>/\\d+/g</code>, allows this regular expression to match one or more digits.",
"The trailing <code>g</code> is short for 'global', which allows this regular expression to find all matches rather than stop at the first match.",
"<h4>Instructions</h4>",
"Use the <code>\\d</code> selector to select the number of numbers in the string, allowing for the possibility of one or more digit."
],
"head": [
""
],
"challengeSeed": [
"// Setup",
"var testString = \"There are 3 cats but 4 dogs.\";",
"",
"// Only change code below this line.",
"",
"var expression = /.+/g; // Change this line",
"",
"// Only change code above this line",
"",
"// This code counts the matches of expression in testString",
"var digitCount = testString.match(expression).length;"
],
"tail": [
"(function(){return digitCount;})();"
],
"solutions": [
"var testString = \"There are 3 cats but 4 dogs.\";\nvar expression = /\\d+/g; // Change this line\nvar digitCount = testString.match(expression).length;"
],
"tests": [
"assert(digitCount === 2, 'message: Your regular expression should find two numbers in <code>testString</code>.');",
"assert(code.match(/\\/\\\\d\\+\\//g), 'message: Use the <code>/\\d+/g</code> regular expression to find the numbers in <code>testString</code>.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Encuentra números con expresiones regulares",
"descriptionEs": [
"Podemos usar selectores especiales en las <code>expresiones regulares</code> para seleccionar un determinado tipo de valor.",
"Uno de estos selectores es el de dígitos <code>\\d</code> que se utiliza para hacer coincidir números en una cadena.",
"Se usa así para hacer coincidir un dígito: <code>/\\d/g</code>.",
"Para hacer coincidir números de varios dígtios a menudo se escribe <code>/\\d+/ g </code>, donde el <code>+</code> que sigue al selector de dígito le permite a la expresión regular coincidir con uno o más dígito es decir coincide con números de varios dígitos.",
"Usa el selector <code>\\d</code> para hacer coincidir todos los números de la cadena, permitiendo la posibilidad de hacer coincidir números de varios dígitos."
]
},
{
"id": "cf1111c1c12feddfaeb8bdef",
"title": "Find Whitespace with Regular Expressions",
"description": [
"We can also use regular expression selectors like <code>\\s</code> to find whitespace in a string.",
"The whitespace characters are <code>\" \"</code> (space), <code>\\r</code> (the carriage return), <code>\\n</code> (newline), <code>\\t</code> (tab), and <code>\\f</code> (the form feed).",
"The whitespace regular expression looks like this:",
"<code>/\\s+/g</code>",
"<h4>Instructions</h4>",
"Use <code>\\s</code> to select all the whitespace characters in the sentence string."
],
"head": [
""
],
"challengeSeed": [
"// Setup",
"var testString = \"How many spaces are there in this sentence?\";",
"",
"// Only change code below this line.",
"",
"var expression = /.+/g; // Change this line",
"",
"// Only change code above this line",
"",
"// This code counts the matches of expression in testString",
"var spaceCount = testString.match(expression).length;"
],
"tail": [
"(function(){return spaceCount;})();"
],
"solutions": [
"var testString = \"How many spaces are there in this sentence?\";\nvar expression = /\\s+/g; // Change this line\nvar spaceCount = testString.match(expression).length;"
],
"tests": [
"assert(spaceCount === 7, 'message: Your regular expression should find seven spaces in <code>testString</code>.');",
"assert(code.match(/\\/\\\\s\\+\\//g), 'message: Use the <code>/\\s+/g</code> regular expression to find the spaces in <code>testString</code>.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Encuentra espacios en blanco con las expresiones regulares",
"descriptionEs": [
"También podemos utilizar selectores de expresiones regulares como <code>\\s</code> para encontrar un espacio en blanco en una cadena.",
"Los espacios en blanco son <code>\" \"</code> (espacio), <code>\\r</code> (el retorno de carro), <code>\\n</code> (nueva línea), <code>\\t</code> (tabulador), y <code>\\f</code> (el avance de página). ",
"Una expresión regular con el selector de espacios en blanco puede ser:",
"<code>/\\s+/g</code>",
"Se usa para hacer coincidir todos los espacios en blanco en una cadena."
]
},
{
"id": "cf1111c1c13feddfaeb3bdef",
"title": "Invert Regular Expression Matches with JavaScript",
"description": [
"You can invert any match by using the uppercase version of the regular expression selector.",
"For example, <code>\\s</code> will match any whitespace, and <code>\\S</code> will match anything that isn't whitespace.",
"<h4>Instructions</h4>",
"Use <code>/\\S/g</code> to count the number of non-whitespace characters in <code>testString</code>."
],
"head": [
""
],
"challengeSeed": [
"// Setup",
"var testString = \"How many non-space characters are there in this sentence?\";",
"",
"// Only change code below this line.",
"",
"var expression = /.+/g; // Change this line",
"",
"// Only change code above this line",
"",
"// This code counts the matches of expression in testString",
"var nonSpaceCount = testString.match(expression).length;"
],
"tail": [
"(function(){return nonSpaceCount;})();"
],
"solutions": [
"var testString = \"How many non-space characters are there in this sentence?\";\nvar expression = /\\S/g; \nvar nonSpaceCount = testString.match(expression).length;"
],
"tests": [
"assert(nonSpaceCount === 49, 'message: Your regular expression should find forty nine non-space characters in the <code>testString</code>.');",
"assert(code.match(/\\/\\\\S\\/g/g), 'message: Use the <code>/\\S/g</code> regular expression to find non-space characters in <code>testString</code>.');"
],
"type": "waypoint",
"challengeType": 1,
"nameEs": "Hacer coincidir con una expresión regular invertida",
"descriptionEs": [
"Puedes invertir las coincidencias de un selector usando su versión en mayúsculas.",
"Por ejemplo, <code>\\s</code> coincidirá con cualquier espacio en blanco, mientras que <code>\\S</code> coincidirá con todo lo que no sea espacio en blanco.",
"Usa <code>/\\S/g</code> para contar el número de caracteres que no están en blanco en <code>testString</code>."
]
},
{
"id": "cf1111c1c12feddfaeb9bdef",
"title": "Create a JavaScript Slot Machine",
"description": [
"We are now going to try and combine some of the stuff we've just learned and create the logic for a slot machine game.",
"For this we will need to generate three random numbers between <code>1</code> and <code>3</code> to represent the possible values of each individual slot.",
"Store the three random numbers in <code>slotOne</code>, <code>slotTwo</code> and <code>slotThree</code>.",
"Generate the random numbers by using the system we used earlier (an explanation of the formula can be found <a href='https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/Waypoint-Generate-Random-Whole-Numbers-within-a-Range#explanation' target='_blank'>here</a>):",
"<code>Math.floor(Math.random() * (3 - 1 + 1)) + 1;</code>"
],
"challengeSeed": [
"fccss",
" function runSlots() {",
" var slotOne;",
" var slotTwo;",
" var slotThree;",
" ",
" var images = [\"http://i.imgur.com/9H17QFk.png\", \"http://i.imgur.com/9RmpXTy.png\", \"http://i.imgur.com/VJnmtt5.png\"];",
" ",
" // Only change code below this line.",
" ",
" ",
" ",
" // Only change code above this line.",
" ",
" ",
" if (slotOne !== undefined && slotTwo !== undefined && slotThree !== undefined) {",
" $(\".logger\").html(slotOne + \" \" + slotTwo + \" \" + slotThree);",
" }",
" ",
" ",
" $(\".logger\").append(\" Not A Win\")",
" return [slotOne, slotTwo, slotThree];",
" }",
"",
" $(document).ready(function() {",
" $(\".go\").click(function() {",
" runSlots();",
" });",
" });",
"fcces",
" ",
"<div>",
" <div class = \"container inset\">",
" <div class = \"header inset\">",
" <img src=\"https://s3.amazonaws.com/freecodecamp/freecodecamp_logo.svg.gz\" alt=\"learn to code javascript at Free Code Camp logo\" class=\"img-responsive nav-logo\">",
" <h2>FCC Slot Machine</h2>",
" </div>",
" <div class = \"slots inset\">",
" <div class = \"slot inset\">",
" ",
" </div>",
" <div class = \"slot inset\">",
" ",
" </div>",
" <div class = \"slot inset\">",
" ",
" </div>",
" </div>",
" <br/>",
" <div class = \"outset\">",
" <button class = \"go inset\">",
" Go",
" </button>",
" </div>",
" <br/>",
" <div class = \"foot inset\">",
" <span class = \"logger\"></span>",
" </div>",
" </div>",
"</div>",
"",
"<style>",
" .container {",
" background-color: #4a2b0f;",
" height: 400px;",
" width: 260px;",
" margin: 50px auto;",
" border-radius: 4px;",
" }",
" .header {",
" border: 2px solid #fff;",
" border-radius: 4px;",
" height: 55px;",
" margin: 14px auto;",
" background-color: #457f86",
" }",
" .header h2 {",
" height: 30px;",
" margin: auto;",
" }",
" .header h2 {",
" font-size: 14px;",
" margin: 0 0;",
" padding: 0;",
" color: #fff;",
" text-align: center;",
" }",
" .slots{",
" display: flex;",
" background-color: #457f86;",
" border-radius: 6px;",
" border: 2px solid #fff;",
" }",
" .slot{",
" flex: 1 0 auto;",
" background: white;",
" height: 75px;",
" margin: 8px;",
" border: 2px solid #215f1e;",
" border-radius: 4px;",
" }",
" .go {",
" width: 100%;",
" color: #fff;",
" background-color: #457f86;",
" border: 2px solid #fff;",
" border-radius: 2px;",
" box-sizing: none;",
" outline: none!important;",
" }",
" .foot {",
" height: 150px;",
" background-color: 457f86;",
" border: 2px solid #fff;",
" }",
" ",
" .logger {",
" color: white;",
" margin: 10px;",
" }",
" ",
" .outset {",
" -webkit-box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" -moz-box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" }",
" ",
" .inset {",
" -webkit-box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" -moz-box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" }",
"</style>"
],
"solutions": [
""
],
"tests": [
"assert(typeof(runSlots($(\".slot\"))[0]) === \"number\" && runSlots($(\".slot\"))[0] > 0 && runSlots($(\".slot\"))[0] < 4, '<code>slotOne</code> should be a random number.')",
"assert(typeof(runSlots($(\".slot\"))[1]) === \"number\" && runSlots($(\".slot\"))[1] > 0 && runSlots($(\".slot\"))[1] < 4, '<code>slotTwo</code> should be a random number.')",
"assert(typeof(runSlots($(\".slot\"))[2]) === \"number\" && runSlots($(\".slot\"))[2] > 0 && runSlots($(\".slot\"))[2] < 4, '<code>slotThree</code> should be a random number.')",
"assert((function(){if(editor.match(/Math\\.floor\\(\\s?Math\\.random\\(\\)\\s?\\*\\s?\\(\\s?3\\s?\\-\\s?1\\s?\\+\\s?1\\s?\\)\\s?\\)\\s?\\+\\s?1/gi) !== null){return editor.match(/slot.*?=.*?\\(.*?\\).*?/gi).length >= 3;}else{return false;}})(), 'You should have used <code>Math.floor(Math.random() * (3 - 1 + 1)) + 1;</code> three times to generate your random numbers.')"
],
"type": "waypoint",
"challengeType": 0,
"isBeta": true,
"nameEs": "Crea una máquina tragamonedas en JavaScript",
"descriptionEs": [
"Ahora vamos a tratar de combinar algunas de las cosas que hemos aprendido para crear la lógica de una máquina tragamonedas.",
"Para esto tendremos que generar tres números aleatorios entre <code>1</code> y <code>3</code> que representen los valores posibles de cada casilla.",
"Guarda los tres números aleatorios en <code>slotOne</code>, <code>slotTwo</code> y <code>slotThree</code>.",
"Genera los números aleatorios utilizando el sistema que usamos anteriormente (puedes encontrar una explicación de la fórmula <a href=\"https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/Waypoint-Generate-Random-Whole-Numbers-within-a-Range#explanation\">aquí</a>):",
"<code>Math.floor(Math.random() * (3 - 1 + 1)) + 1;</code>"
]
},
{
"id": "cf1111c1c13feddfaeb1bdef",
"title": "Add your JavaScript Slot Machine Slots",
"description": [
"Now that our slots will each generate random numbers, we need to check whether they've all returned the same number.",
"If they have, we should notify our user that they've won and we should return <code>null</code>.",
"<code>null</code> is a JavaScript data structure that means nothing.",
"The user wins when all the three numbers match. Let's create an <code>if statement</code> with multiple conditions in order to check whether all numbers are equal.",
"<code>if (slotOne === slotTwo && slotTwo === slotThree){</code>",
"<code>&nbsp;&nbsp;return null;</code>",
"<code>}</code>",
"Also, we need to show the user that he has won the game when he gets the same number in all the slots.",
"If all three numbers match, we should also set the text <code>\"It's A Win\"</code> to the element with class <code>logger</code>."
],
"challengeSeed": [
"fccss",
" function runSlots() {",
" var slotOne;",
" var slotTwo;",
" var slotThree;",
" ",
" var images = [\"http://i.imgur.com/9H17QFk.png\", \"http://i.imgur.com/9RmpXTy.png\", \"http://i.imgur.com/VJnmtt5.png\"];",
" ",
" slotOne = Math.floor(Math.random() * (3 - 1 + 1)) + 1;",
" slotTwo = Math.floor(Math.random() * (3 - 1 + 1)) + 1;",
" slotThree = Math.floor(Math.random() * (3 - 1 + 1)) + 1;",
" ",
" ",
" // Only change code below this line.",
" ",
" ",
" ",
" // Only change code above this line.",
" ",
" if (slotOne !== undefined && slotTwo !== undefined && slotThree !== undefined){",
" $(\".logger\").html(slotOne + \" \" + slotTwo + \" \" + slotThree);",
" }",
" ",
" $(\".logger\").append(\" Not A Win\");",
" ",
" return [slotOne, slotTwo, slotThree];",
" }",
"",
" $(document).ready(function() {",
" $(\".go\").click(function() {",
" runSlots();",
" });",
" });",
"fcces",
" ",
"<div>",
" <div class = \"container inset\">",
" <div class = \"header inset\">",
" <img src=\"https://s3.amazonaws.com/freecodecamp/freecodecamp_logo.svg.gz\" alt=\"learn to code javascript at Free Code Camp logo\" class=\"img-responsive nav-logo\">",
" <h2>FCC Slot Machine</h2>",
" </div>",
" <div class = \"slots inset\">",
" <div class = \"slot inset\">",
" ",
" </div>",
" <div class = \"slot inset\">",
" ",
" </div>",
" <div class = \"slot inset\">",
" ",
" </div>",
" </div>",
" <br/>",
" <div class = \"outset\">",
" <button class = \"go inset\">",
" Go",
" </button>",
" </div>",
" <br/>",
" <div class = \"foot inset\">",
" <span class = \"logger\"></span>",
" </div>",
" </div>",
"</div>",
"",
"<style>",
" .container {",
" background-color: #4a2b0f;",
" height: 400px;",
" width: 260px;",
" margin: 50px auto;",
" border-radius: 4px;",
" }",
" .header {",
" border: 2px solid #fff;",
" border-radius: 4px;",
" height: 55px;",
" margin: 14px auto;",
" background-color: #457f86",
" }",
" .header h2 {",
" height: 30px;",
" margin: auto;",
" }",
" .header h2 {",
" font-size: 14px;",
" margin: 0 0;",
" padding: 0;",
" color: #fff;",
" text-align: center;",
" }",
" .slots{",
" display: flex;",
" background-color: #457f86;",
" border-radius: 6px;",
" border: 2px solid #fff;",
" }",
" .slot{",
" flex: 1 0 auto;",
" background: white;",
" height: 75px;",
" margin: 8px;",
" border: 2px solid #215f1e;",
" border-radius: 4px;",
" }",
" .go {",
" width: 100%;",
" color: #fff;",
" background-color: #457f86;",
" border: 2px solid #fff;",
" border-radius: 2px;",
" box-sizing: none;",
" outline: none!important;",
" }",
" .foot {",
" height: 150px;",
" background-color: 457f86;",
" border: 2px solid #fff;",
" }",
" ",
" .logger {",
" color: white;",
" margin: 10px;",
" }",
" ",
" .outset {",
" -webkit-box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" -moz-box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" }",
" ",
" .inset {",
" -webkit-box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" -moz-box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" }",
"</style>"
],
"solutions": [
""
],
"tests": [
"assert((function(){var data = runSlots();return data === null || data.toString().length === 1;})(), 'If all three of our random numbers are the same we should return that number. Otherwise we should return <code>null</code>.')"
],
"type": "waypoint",
"challengeType": 0,
"isBeta": true,
"nameEs": "Añade casillas a tu tragamonedas JavaScript",
"descriptionEs": [
"Ahora que cada una de nuestras casillas genera números aleatorios, tenemos que comprobar si todos quedan con el mismo número.",
"Si es así, debemos notificar a nuestros usuarios que han ganado y debemos retornar <code>null</code>.",
"<code>null</code> es una estructura de datos de JavaScript que significa \"nada\".",
"El usuario gana cuando los tres números coinciden. Cremos una instrucción <code>if</code> con varias condiciones, a fin de comprobar si todos los números son iguales. ",
"<code>if(slotOne === slotTwo && slotTwo === slotThree){</code>",
"<code>&nbsp;&nbsp;return null;</code>",
"<code>}</code>",
"Además, tenemos que mostrar al usuario que ha ganado la partida e caso de que esté el mismo número en todas las casillas.",
"Si los tres números coinciden, también hay que poner el texto <code>\"It's A Win\"</code> en el elemento HTML con clase <code>logger</code>."
]
},
{
"id": "cf1111c1c13feddfaeb2bdef",
"title": "Bring your JavaScript Slot Machine to Life",
"description": [
"Now we can detect a win. Let's get this slot machine working.",
"Let's use the jQuery <code>selector</code> <code>$(\".slot\")</code> to select all of the slots.",
"Once they are all selected, we can use <code>bracket notation</code> to access each individual slot:",
"<code>$($(\".slot\")[0]).html(slotOne);</code>",
"This jQuery will select the first slot and update it's HTML to display the correct number.",
"Use the above selector to display each number in its corresponding slot."
],
"challengeSeed": [
"fccss",
" function runSlots() {",
" var slotOne;",
" var slotTwo;",
" var slotThree;",
" ",
" var images = [\"http://i.imgur.com/9H17QFk.png\", \"http://i.imgur.com/9RmpXTy.png\", \"http://i.imgur.com/VJnmtt5.png\"];",
" ",
" slotOne = Math.floor(Math.random() * (3 - 1 + 1)) + 1;",
" slotTwo = Math.floor(Math.random() * (3 - 1 + 1)) + 1;",
" slotThree = Math.floor(Math.random() * (3 - 1 + 1)) + 1;",
" ",
" ",
" // Only change code below this line.",
" ",
" ",
" ",
" // Only change code above this line.",
" ",
" if (slotOne === slotTwo && slotTwo === slotThree) {",
" $(\".logger\").html(\" It's A Win\")",
" return null;",
" }",
" ",
" if (slotOne !== undefined && slotTwo !== undefined && slotThree !== undefined){",
" $(\".logger\").html(slotOne + \" \" + slotTwo + \" \" + slotThree);",
" }",
" ",
" $(\".logger\").append(\" Not A Win\");",
" ",
" ",
" return [slotOne, slotTwo, slotThree];",
" }",
"",
" $(document).ready(function() {",
" $(\".go\").click(function() {",
" runSlots();",
" });",
" });",
"fcces",
" ",
"<div>",
" <div class = \"container inset\">",
" <div class = \"header inset\">",
" <img src=\"https://s3.amazonaws.com/freecodecamp/freecodecamp_logo.svg.gz\" alt=\"learn to code javascript at Free Code Camp logo\" class=\"img-responsive nav-logo\">",
" <h2>FCC Slot Machine</h2>",
" </div>",
" <div class = \"slots inset\">",
" <div class = \"slot inset\">",
" ",
" </div>",
" <div class = \"slot inset\">",
" ",
" </div>",
" <div class = \"slot inset\">",
" ",
" </div>",
" </div>",
" <br/>",
" <div class = \"outset\">",
" <button class = \"go inset\">",
" Go",
" </button>",
" </div>",
" <br/>",
" <div class = \"foot inset\">",
" <span class = \"logger\"></span>",
" </div>",
" </div>",
"</div>",
"",
"<style>",
" .container {",
" background-color: #4a2b0f;",
" height: 400px;",
" width: 260px;",
" margin: 50px auto;",
" border-radius: 4px;",
" }",
" .header {",
" border: 2px solid #fff;",
" border-radius: 4px;",
" height: 55px;",
" margin: 14px auto;",
" background-color: #457f86",
" }",
" .header h2 {",
" height: 30px;",
" margin: auto;",
" }",
" .header h2 {",
" font-size: 14px;",
" margin: 0 0;",
" padding: 0;",
" color: #fff;",
" text-align: center;",
" }",
" .slots{",
" display: flex;",
" background-color: #457f86;",
" border-radius: 6px;",
" border: 2px solid #fff;",
" }",
" .slot{",
" flex: 1 0 auto;",
" background: white;",
" height: 75px;",
" margin: 8px;",
" border: 2px solid #215f1e;",
" border-radius: 4px;",
" text-align: center;",
" padding-top: 25px;",
" }",
" .go {",
" width: 100%;",
" color: #fff;",
" background-color: #457f86;",
" border: 2px solid #fff;",
" border-radius: 2px;",
" box-sizing: none;",
" outline: none!important;",
" }",
" .foot {",
" height: 150px;",
" background-color: 457f86;",
" border: 2px solid #fff;",
" }",
" ",
" .logger {",
" color: white;",
" margin: 10px;",
" }",
" ",
" .outset {",
" -webkit-box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" -moz-box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" }",
" ",
" .inset {",
" -webkit-box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" -moz-box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" }",
"</style>"
],
"solutions": [
""
],
"tests": [
"assert((function(){runSlots();if($($(\".slot\")[0]).html().replace(/\\s/gi, \"\") !== \"\" && $($(\".slot\")[1]).html().replace(/\\s/gi, \"\") !== \"\" && $($(\".slot\")[2]).html().replace(/\\s/gi, \"\") !== \"\"){return true;}else{return false;}})(), 'You should be displaying the result of the slot numbers in the corresponding slots.')",
"assert((editor.match( /\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[\\d\\]\\s*?\\)/gi) && editor.match( /\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[\\d\\]\\s*?\\)/gi ).length >= 3 && editor.match( /\\.html\\(slotOne\\)/gi ) && editor.match( /\\.html\\(slotTwo\\)/gi ) && editor.match( /\\.html\\(slotThree\\)/gi )), 'You should have used the the selector given in the description to select each slot and assign it the value of <code>slotOne</code>&#44; <code>slotTwo</code> and <code>slotThree</code> respectively.')"
],
"type": "waypoint",
"challengeType": 0,
"isBeta": true,
"nameEs": "Da vida a tu máquina tragamonedas en JavaScript",
"descriptionEs": [
"Ahora podemos detectar una victoria. Logremos que la máquina tragamonedas funcione. ",
"Usemos un <code>selector</code> de jQuery <code>$(\".slot\")</code> para seleccionar todas las casillas.",
"Una vez que todas estén seleccionados, podemos usar <code>notación de corchetes</code> para acceder a cada casilla individual:",
"<code>$($(\".slot\")[0]).html(slotOne);</code>",
"Este jQuery seleccionará la primera ranura y actualizará su HTML para mostrar el número correcto.",
"Usa el selector anterior para mostrar cada número en su casilla correspondiente."
]
},
{
"id": "cf1111c1c11feddfaeb1bdff",
"title": "Give your JavaScript Slot Machine some Stylish Images",
"description": [
"Now let's add some images to our slots.",
"We've already set up the images for you in an array called <code>images</code>. We can use different indexes to grab each of these.",
"Here's how we would set the first slot to show a different image depending on which number its random number generates:",
"<code>$($('.slot')[0]).html('&lt;img src = \"' + images[slotOne-1] + '\"&gt;');</code>",
"Set up all three slots like this, then click the \"Go\" button to play the slot machine."
],
"challengeSeed": [
"fccss",
" function runSlots() {",
" var slotOne;",
" var slotTwo;",
" var slotThree;",
" ",
" var images = [\"http://i.imgur.com/9H17QFk.png\", \"http://i.imgur.com/9RmpXTy.png\", \"http://i.imgur.com/VJnmtt5.png\"];",
" ",
" slotOne = Math.floor(Math.random() * (3 - 1 + 1)) + 1;",
" slotTwo = Math.floor(Math.random() * (3 - 1 + 1)) + 1;",
" slotThree = Math.floor(Math.random() * (3 - 1 + 1)) + 1;",
" ",
" ",
" // Only change code below this line.",
" ",
" ",
" ",
" // Only change code above this line.",
" ",
" if (slotOne === slotTwo && slotTwo === slotThree) {",
" $('.logger').html(\"It's A Win\");",
" return null;",
" }",
" ",
" if (slotOne !== undefined && slotTwo !== undefined && slotThree !== undefined){",
" $(\".logger\").html(slotOne + \" \" + slotTwo + \" \" + slotThree);",
" }",
" ",
" $('.logger').append(\" Not A Win\");",
" ",
" return [slotOne, slotTwo, slotThree];",
" }",
"",
" $(document).ready(function() {",
" $('.go').click(function() {",
" runSlots();",
" });",
" });",
"fcces",
" ",
"<div>",
" <div class = 'container inset'>",
" <div class = 'header inset'>",
" <img src='https://s3.amazonaws.com/freecodecamp/freecodecamp_logo.svg.gz' alt='learn to code javascript at Free Code Camp logo' class='img-responsive nav-logo'>",
" <h2>FCC Slot Machine</h2>",
" </div>",
" <div class = 'slots inset'>",
" <div class = 'slot inset'>",
" ",
" </div>",
" <div class = 'slot inset'>",
" ",
" </div>",
" <div class = 'slot inset'>",
" ",
" </div>",
" </div>",
" <br/>",
" <div class = 'outset'>",
" <button class = 'go inset'>",
" Go",
" </button>",
" </div>",
" <br/>",
" <div class = 'foot inset'>",
" <span class = 'logger'></span>",
" </div>",
" </div>",
"</div>",
"",
"<style>",
" .slot > img {",
" margin: 0!important;",
" height: 71px;",
" width: 50px;",
" }",
" .container {",
" background-color: #4a2b0f;",
" height: 400px;",
" width: 260px;",
" margin: 50px auto;",
" border-radius: 4px;",
" }",
" .header {",
" border: 2px solid #fff;",
" border-radius: 4px;",
" height: 55px;",
" margin: 14px auto;",
" background-color: #457f86",
" }",
" .header h2 {",
" height: 30px;",
" margin: auto;",
" }",
" .header h2 {",
" font-size: 14px;",
" margin: 0 0;",
" padding: 0;",
" color: #fff;",
" text-align: center;",
" }",
" .slots{",
" display: flex;",
" background-color: #457f86;",
" border-radius: 6px;",
" border: 2px solid #fff;",
" }",
" .slot{",
" flex: 1 0 auto;",
" background: white;",
" height: 75px;",
" width: 50px;",
" margin: 8px;",
" border: 2px solid #215f1e;",
" border-radius: 4px;",
" text-align: center;",
" }",
" .go {",
" width: 100%;",
" color: #fff;",
" background-color: #457f86;",
" border: 2px solid #fff;",
" border-radius: 2px;",
" box-sizing: none;",
" outline: none!important;",
" }",
" .foot {",
" height: 150px;",
" background-color: 457f86;",
" border: 2px solid #fff;",
" }",
" ",
" .logger {",
" color: white;",
" margin: 10px;",
" }",
" ",
" .outset {",
" -webkit-box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" -moz-box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" box-shadow: 0px 0px 15px -2px rgba(0,0,0,0.75);",
" }",
" ",
" .inset {",
" -webkit-box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" -moz-box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" box-shadow: inset 0px 0px 15px -2px rgba(0,0,0,0.75);",
" }",
"</style>"
],
"solutions": [
""
],
"tests": [
"assert((editor.match(/\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[\\d\\]\\s*?\\)\\.html\\(\\s*?\\'\\<img\\s?src\\s?=\\s?\"\\'\\s?\\+\\s?images\\[\\w+\\s*\\-\\s*1\\]\\s?\\+\\s?\\'\"\\>\\'\\s*?\\);/gi) && editor.match(/\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[\\d\\]\\s*?\\)\\.html\\(\\s*?\\'\\<img\\s?src\\s?=\\s?\"\\'\\s?\\+\\s?images\\[\\w+\\s*\\-\\s*1\\]\\s?\\+\\s?\\'\"\\>\\'\\s*?\\);/gi).length >= 3), 'Use the provided code three times. One for each slot.')",
"assert(editor.match(/\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[0\\]\\s*?\\)/gi), 'You should have used <code>$&#40;&#39;.slot&#39;&#41;[0]</code> at least once.')",
"assert(editor.match(/\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[1\\]\\s*?\\)/gi), 'You should have used <code>$&#40;&#39;.slot&#39;&#41;[1]</code> at least once.')",
"assert(editor.match(/\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[2\\]\\s*?\\)/gi), 'You should have used <code>$&#40;&#39;.slot&#39;&#41;[2]</code> at least once.')",
"assert(editor.match(/slotOne/gi) && editor.match(/slotOne/gi).length >= 7, 'You should have used the <code>slotOne</code> value at least once.')",
"assert(editor.match(/slotTwo/gi) && editor.match(/slotTwo/gi).length >= 8, 'You should have used the <code>slotTwo</code> value at least once.')",
"assert(editor.match(/slotThree/gi) && editor.match(/slotThree/gi).length >= 7, 'You should have used the <code>slotThree</code> value at least once.')"
],
"type": "waypoint",
"challengeType": 0,
"isBeta": true,
"nameEs": "Dale a tu máquina tragamonedas JavaScript algunas imágenes con estilo",
"descriptionEs": [
"Ahora añadamos algunas imágenes en nuestras casillas.",
"Ya hemos creado las imágenes por ti en una matriz llamada <code>images</code>. Podemos utilizar diferentes índices para tomara cada una de estas. ",
"Aquí está como haríamos que la primera casilla muestre una imagen diferente dependiendo del número aleatorio que se genere:",
"<code>$($('.slot')[0]).html('&lt;img src = \"' + images[slotOne-1] + '\"&gt;');</code>",
"Configura las tres casillas de manera análoga, a continuación, pulsa el botón \"Go\" para jugar con la máquina tragamonedas."
]
}
]
}