diff --git a/seed/challenges/01-front-end-development-certification/basic-javascript.json b/seed/challenges/01-front-end-development-certification/basic-javascript.json
index f346831d08..4818cf354a 100644
--- a/seed/challenges/01-front-end-development-certification/basic-javascript.json
+++ b/seed/challenges/01-front-end-development-certification/basic-javascript.json
@@ -1,6 +1,6 @@
{
"name": "Basic JavaScript",
- "order": 6,
+ "order": "6",
"time": "5h",
"challenges": [
{
@@ -13,26 +13,15 @@
"// This is a comment.
",
"The slash-star-star-slash comment will comment out everything between the /*
and the */
characters:",
"/* This is also a comment */
",
- "Try creating one of each."
+ "
Instructions
Try creating one of each type of comment."
],
"tests": [
"assert(editor.getValue().match(/(\\/\\/)...../g), 'message: Create a //
style comment that contains at least five letters.');",
"assert(editor.getValue().match(/(\\/\\*)[\\w\\W]{5,}(?=\\*\\/)/gm), 'message: Create a /* */
style comment that contains at least five letters.');",
"assert(editor.getValue().match(/(\\*\\/)/g), 'message: Make sure that you close the comment with a */
.');"
],
- "challengeSeed": [],
"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:",
- "// Este es un comentario.
",
- "El comentario de barra-estrella-estrella-barra, comentará todo lo que haya entre los caracteres /*
y */
:",
- "/* Este es también un comentario */
",
- "Trata de crear uno de cada uno."
- ]
+ "challengeType": "1"
},
{
"id": "bd7123c9c441eddfaeb5bdef",
@@ -40,10 +29,10 @@
"description": [
"In computer science, data structures
are things that hold data. JavaScript has seven of these. For example, the Number
data structure holds numbers.",
"Let's learn about the most basic data structure of all: the Boolean
. Booleans can only hold the value of either true or false. They are basically little on-off switches.",
- "Let's modify our welcomeToBooleans
function so that it will return true
instead of false
when the run button is clicked."
+ "Instructions
Modify the welcomeToBooleans
function so that it will return true
instead of false
when the run button is clicked."
],
"tests": [
- "assert(typeof welcomeToBooleans() === 'boolean', 'message: The welcomeToBooleans()
function should return a boolean (true/false) value.');",
+ "assert(typeof(welcomeToBooleans()) === 'boolean', 'message: The welcomeToBooleans()
function should return a boolean (true/false) value.');",
"assert(welcomeToBooleans() === true, 'message: welcomeToBooleans()
should return true.');"
],
"challengeSeed": [
@@ -51,7 +40,7 @@
"",
"// Only change code below this line.",
"",
- " return false;",
+ " return false; // Change this line",
"",
"// Only change code above this line.",
"}"
@@ -60,13 +49,7 @@
"welcomeToBooleans();"
],
"type": "waypoint",
- "challengeType": 1,
- "nameEs": "Entiende los valores booleanos",
- "descriptionEs": [
- "En informática las estructuras de datos
son cosas que contienen datos. JavaScript tiene siete de estas. Por ejemplo, la estructura de datos Número
contiene números. ",
- "Vamos a aprender acerca de la estructura de datos más básica de todas: el Boolean
. 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 welcomeToBooleans
para que devuelva true
en lugar de false
cuando se pulse el botón de ejecución."
- ]
+ "challengeType": "1"
},
{
"id": "bd7123c9c443eddfaeb5bdef",
@@ -75,249 +58,199 @@
"When we store data in a data structure
, we call it a variable
. These variables are no different from the x and y variables you use in math.",
"Let's create our first variable and call it \"myName\".",
"You'll notice that in myName
, we didn't use a space, and that the \"N\" is capitalized. JavaScript variables are written in camel case
. An example of camel case is: camelCase.",
- "Now, use the var
keyword to create a variable called myName
. Set its value to your name, in double quotes.",
+ "Instructions
Use the var
keyword to create a variable called myName
. Set its value to your name, in double quotes.",
+ "Hint",
"Look at the ourName
example if you get stuck."
],
"tests": [
- "assert((function(){if(typeof myName !== \"undefined\" && typeof myName === \"string\" && myName.length > 0){return true;}else{return false;}})(), 'message: myName
should be a string that contains at least one character in it.');"
+ "assert((function(){if(typeof(myName) !== \"undefined\" && typeof(myName) === \"string\" && myName.length > 0){return true;}else{return false;}})(), 'message: myName
should be a string that contains at least one character in it.');"
],
"challengeSeed": [
+ "// Example",
"var ourName = \"Free Code Camp\";",
"",
+ "// Only change code below this line",
""
],
"tail": [
- "if(typeof myName !== \"undefined\"){(function(v){return v;})(myName);}"
+ "if(typeof(myName) !== \"undefined\"){(function(v){return v;})(myName);}"
],
"type": "waypoint",
- "challengeType": 1,
- "nameEs": "Declara variables en JavaScript",
- "descriptionEs": [
- "Cuando almacenamos datos en una estructura de datos
, la llamamos una variable
. 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 myName
, no usamos un espacio, y que la \" N\"se escribe con mayúscula. Las variables en JavaScript se escriben con capitalización camello (camel case)
. Un ejemplo de capitalización camello: capitalizacionCamello.",
- "Ahora, utiliza la palabra clave var
para crear una variable llamada myName
. Establecele como valor tu nombre, entre comillas dobles. ",
- "Mira el ejemplo con ourName
si te quedas atascado."
- ]
+ "challengeType": "1"
},
{
- "id": "bd7123c9c444eddfaeb5bdef",
- "title": "Declare String Variables",
+ "id": "56533eb9ac21ba0edf2244a8",
+ "title": "Storing Values with the Equal Operator",
"description": [
- "In the previous challenge, we used the code var myName = \"your name\"
. This is what we call a String
variable. It is nothing more than a \"string\" of characters. JavaScript strings are always wrapped in quotes.",
- "Now let's create two new string variables: myFirstName
and myLastName
and assign them the values of your first and last name, respectively."
+ "In Javascript, you can store a value in a variable with the =
or assignment operator.",
+ "myVariable = 5;
",
+ "Assigns the value 5
to myVariable
.",
+ "Assignment always goes from right to left. Everything to the right of the =
operator is resolved before the value is assigned to the variable to the left of the operator.",
+ "myVar = 5;
",
+ "myNum = myVar;
",
+ "Assigns 5
to myVar
and then resolves myVar
to 5
again and assigns it to myNum
.",
+ "Instructions
Assign the value 7 to variable a
",
+ "Assign the contents of a
to variable b
."
],
+ "releasedOn": "11/27/2015",
"tests": [
- "assert((function(){if(typeof myFirstName !== \"undefined\" && typeof myFirstName === \"string\" && myFirstName.length > 0){return true;}else{return false;}})(), 'message: myFirstName
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: myLastName
should be a string with at least one character in it.');"
+ "assert(/var a;/.test(editor.getValue()) && /var b = 2;/.test(editor.getValue()), 'message: Do not change code above the line');",
+ "assert(typeof a === 'number' && a === 7, 'message: a
should have a value of 7');",
+ "assert(typeof b === 'number' && b === 7, 'message: b
should have a value of 7');",
+ "assert(editor.getValue().match(/b\\s*=\\s*a\\s*;/g), 'message: a
should be assigned to b
with =
');"
],
"challengeSeed": [
- "var firstName = \"Alan\";",
- "var lastName = \"Turing\";",
+ "// Setup",
+ "var a;",
+ "var b = 2;",
"",
- "",
- "// Only change code above this line.",
- "",
- "if(typeof myFirstName !== \"undefined\" && typeof myLastName !== \"undefined\"){(function(){return myFirstName + ', ' + myLastName;})();}"
+ "// Only change code below this line",
+ " "
+ ],
+ "tail": [
+ "(function(a,b){return \"a = \" + a + \", b = \" + b;})(a,b);"
+ ],
+ "solutions": [
+ "var a;",
+ "var b=2;",
+ "a = 7;",
+ "b = a;7"
],
"type": "waypoint",
- "challengeType": 1,
- "nameEs": "Declara variables tipo cadena",
- "descriptionEs": [
- "En el reto anterior, se utilizó el código myName var = \"su nombre\"
. Esto es lo que llamamos una variable tipo cadena
. 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: myFirstName
y myLastName
y asignarles los valores de tu nombre y tu apellido, respectivamente."
- ]
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
},
{
- "id": "bd7123c9c448eddfaeb5bdef",
- "title": "Check the Length Property of a String Variable",
+ "id": "56533eb9ac21ba0edf2244a9",
+ "title": "Initializing Variables with the Equal Operator",
"description": [
- "Data structures
have properties
. For example, strings
have a property called .length
that will tell you how many characters are in the string.",
- "For example, if we created a variable var firstName = \"Charles\"
, we could find out how long the string \"Charles\" is by using the firstName.length
property.",
- "Use the .length
property to count the number of characters in the lastName
variable."
+ "It is common to initialize a variable to a starting value on the same line as it is defined.",
+ "",
+ "var myVar = 0;
",
+ "Creates a new variable called myVar
and assigns it an inital value of 0
.",
+ "",
+ "Instructions
Define a variable a
with var
and initialize it to a value of 9
."
],
+ "releasedOn": "11/27/2015",
"tests": [
- "assert((function(){if(typeof lastNameLength !== \"undefined\" && typeof lastNameLength === \"number\" && lastNameLength === 8){return true;}else{return false;}})(), 'message: lastNameLength
should be equal to eight.');",
- "assert((function(){if(editor.getValue().match(/\\.length/gi) && editor.getValue().match(/\\.length/gi).length >= 2 && editor.getValue().match(/var lastNameLength \\= 0;/gi) && editor.getValue().match(/var lastNameLength \\= 0;/gi).length >= 1){return true;}else{return false;}})(), 'message: You should be getting the length of lastName
by using .length
like this: lastName.length
.');"
+ "assert(/var\\s+a\\s*=\\s*9\\s*/.test(editor.getValue()), 'message: Initialize a
to a value of 9
');"
],
"challengeSeed": [
- "var firstNameLength = 0;",
- "var lastNameLength = 0;",
- "var firstName = \"Ada\";",
+ "// Example",
+ "var ourVar = 19;",
"",
- "firstNameLength = firstName.length;",
- "",
- "var lastName = \"Lovelace\";",
- "",
- "// Only change code below this line.",
- "",
- "lastNameLength = lastName;",
- "",
- "",
- "",
- "// Only change code above this line.",
- "",
- "if(typeof lastNameLength !== \"undefined\"){(function(){return lastNameLength;})();}"
+ "// 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;"
],
"type": "waypoint",
- "challengeType": 1,
- "nameEs": "Comprueba la propiedad longitud (length) de una variable tipo cadena",
- "descriptionEs": [
- "Las estructuras de datos
tienen propiedades
. Por ejemplo, las cadenas
tienen una propiedad llamada .length
que te dirá cuántos caracteres hay en la cadena.",
- "Por ejemplo, si creamos una variable var firstName=\"Charles\"
, podemos averiguar la longitud de la cadena \"Charles\" usando la propiedad firstName.length
. ",
- "Usa la propiedad .length
para contar el número de caracteres en el variable lastName
."
- ]
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
},
{
- "id": "bd7123c9c549eddfaeb5bdef",
- "title": "Use Bracket Notation to Find the First Character in a String",
+ "id": "56533eb9ac21ba0edf2244aa",
+ "title": "Understanding Uninitialized Variables",
"description": [
- "Bracket notation
is a way to get a character at a specific index
within a string.",
- "Computers don't start counting at 1 like humans do. They start at 0.",
- "For example, the character at index 0 in the word \"Charles\" is \"C\". So if var firstName = \"Charles\"
, you can get the value of the first letter of the string by using firstName[0]
.",
- "Use bracket notation
to find the first character in the lastName
variable and assign it to firstLetterOfLastName
.",
- "Try looking at the firstLetterOfFirstName
variable declaration if you get stuck."
+ "When Javascript variables are declared, they have an inital value of undefined. If you do a mathematical operation on an undefined
variable your result will be NaN which means \"Not a Number\". If you concatanate a string with an undefined
variable, you will get a literal string of \"undefined\".",
+ "Instructions
Initialize the three variables a
, b
, and c
with 5
, 10
, and \"I am a\"
respectively so that they will not be undefined
."
],
+ "releasedOn": "11/27/2015",
"tests": [
- "assert((function(){if(typeof firstLetterOfLastName !== \"undefined\" && editor.getValue().match(/\\[0\\]/gi) && typeof firstLetterOfLastName === \"string\" && firstLetterOfLastName === \"L\"){return true;}else{return false;}})(), 'message: The firstLetterOfLastName
variable should have the value of L
.');"
+ "assert(typeof a === 'number' && a === 6, 'message: a
should be defined and have a value of 6
');",
+ "assert(typeof b === 'number' && b === 15, 'message: b
should be defined and have a value of 15
');",
+ "assert(!/undefined/.test(c) && c === \"I am a String!\", 'message: c
should not contain undefined
and should have a value of \"I am a String!\"');",
+ "assert(/a = a \\+ 1;/.test(editor.getValue()) && /b = b \\+ 5;/.test(editor.getValue()) && /c = c \\+ \" String!\";/.test(editor.getValue()), 'message: Do not change code below the line');"
],
"challengeSeed": [
- "var firstLetterOfFirstName = \"\";",
- "var firstLetterOfLastName = \"\";",
+ "// Initialize these three variables",
+ "var a;",
+ "var b;",
+ "var c;",
"",
- "var firstName = \"Ada\";",
+ "// Do not change code below this line",
"",
- "firstLetterOfFirstName = firstName[0];",
- "",
- "var lastName = \"Lovelace\";",
- "",
- "firstLetterOfLastName = lastName;",
- "",
- "",
- "// Only change code above this line.",
- "",
- "(function(v){return v;})(firstLetterOfLastName);"
+ "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;",
+ "var b = 10;",
+ "var c = \"I am a\";",
+ "a = a + 1;",
+ "b = b + 5;",
+ "c = c + \" String!\";"
],
"type": "waypoint",
- "challengeType": 1,
- "nameEs": "Usa la notación de corchetes para encontrar el primer acaracter de una cadena",
- "descriptionEs": [
- "La notación de corchetes
es una forma de obtener el caracter en un índice
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 var firstName = \"Charles\"
, puedes obtener la primera letra de la cadena usando firstName[0]
.",
- "Usa la notación de corchetes
para encontrar el primer caracter en la variable lastName
y asignarlo a firstLetterOfLastName
.",
- "Si te atascas intenta mirar la declaración de la variable firstLetterOfFirstName
."
- ]
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
},
{
- "id": "bd7123c9c450eddfaeb5bdef",
- "title": "Use Bracket Notation to Find the Nth Character in a String",
+ "id": "56533eb9ac21ba0edf2244ab",
+ "title": "Understanding Case Sensitivity in Variables",
"description": [
- "You can also use bracket notation
to get the character at other positions within a string.",
- "Remember that computers start counting at 0, so the first character is actually the zeroth character.",
- "Let's try to set thirdLetterOfLastName
to equal the third letter
of the lastName
variable.",
- "Try looking at the secondLetterOfFirstName
variable declaration if you get stuck."
+ "In Javascript all variables and function names are case sensitive. This means that capitalization matters.",
+ "MYVAR
is not the same as MyVar
nor myvar
. It is possible to have mulitpe distinct variables with the same name but different capitalization. It is strongly reccomended that for sake of clarity you do not use this language feature.",
+ "Best Practice
Variables in Javascript should use camelCase. In camelCase, variables made of multiple words have the first word in all lowercase and the first letter of each subsequent word capitalized.
",
+ "Examples:var someVariable;var anotherVariableName;var thisVariableNameIsTooLong;
",
+ "Instructions
Correct the variable assignements so their names match their variable declarations above."
],
+ "releasedOn": "11/27/2015",
"tests": [
- "assert(thirdLetterOfLastName === 'v', 'message: The thirdLetterOfLastName
variable should have the value of v
.');"
+ "assert(StUdLyCapVaR === 10, 'message: StUdLyCapVaR has the correct case');",
+ "assert(properCamelCase === \"A String\", 'message: properCamelCase has the correct case');",
+ "assert(TitleCaseOver === 9000, 'message: TitleCaseOver has the correct case');"
],
"challengeSeed": [
- "var firstName = \"Ada\";",
+ "// Setup",
+ "var StUdLyCapVaR;",
+ "var properCamelCase;",
+ "var TitleCaseOver;",
"",
- "var secondLetterOfFirstName = firstName[1];",
+ "// Only change code below this line",
"",
- "var lastName = \"Lovelace\";",
+ "STUDLYCAPVAR = 10;",
+ "PRoperCAmelCAse = \"A String\";",
+ "tITLEcASEoVER = 9000;",
+ ""
+ ],
+ "solutions": [
+ "var StUdLyCapVaR;",
+ "var properCamelCase;",
+ "var TitleCase;",
"",
- "var thirdLetterOfLastName = lastName;",
- "",
- "",
- "// Only change code above this line.",
- "",
- "(function(v){return v;})(thirdLetterOfLastName);"
+ "StUdLyCapVaR = 10;",
+ "properCamelCase = \"A String\";",
+ "TitleCaseOver = \"9000\";"
],
"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 notación de corchetes
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 thirdLetterOfLastName
la tercera letra
de la variable lastName
.",
- "Si te atascas intenta mirar la declaración de la variable secondLetterOfFirstName
."
- ]
- },
- {
- "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 var firstName = \"Charles\"
, you can get the value of the last letter of the string by using firstName[firstName.length - 1]
.",
- "Use bracket notation
to find the last character in the lastName
variable.",
- "Try looking at the lastLetterOfFirstName
variable declaration if you get stuck."
- ],
- "tests": [
- "assert(lastLetterOfLastName === \"e\", 'message: lastLetterOfLastName
should be \"e\".');",
- "assert(editor.getValue().match(/\\.length/g).length === 2, 'message: You have to use .length
to get the last letter.');"
- ],
- "challengeSeed": [
- "var firstName = \"Ada\";",
- "",
- "var lastLetterOfFirstName = firstName[firstName.length - 1];",
- "",
- "var lastName = \"Lovelace\";",
- "",
- "var lastLetterOfLastName = lastName;",
- "",
- "",
- "// Only change code above this line.",
- "",
- "(function(v){return v;})(lastLetterOfLastName);"
- ],
- "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 var firstName = \"Charles\"
, se puede obtener la última letra usando firstName[firstName.length - 1]
. ",
- "Utiliza notación de corchetes
para encontrar el último caracter de la variabel lastName
.",
- "Si te atascas intenta mirando la declaración de la variable lastLetterOfFirstName
."
- ]
- },
- {
- "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 var firstName = \"Charles\"
string by using firstName[firstName.length - 3]
",
- "Use bracket notation
to find the second-to-last character in the lastName
string.",
- "Try looking at the thirdToLastLetterOfFirstName
variable declaration if you get stuck."
- ],
- "tests": [
- "assert(secondToLastLetterOfLastName === 'c', 'message: secondToLastLetterOfLastName
should be \"c\".');",
- "assert(editor.getValue().match(/\\.length/g).length === 2, 'message: You have to use .length
to get the second last letter.');"
- ],
- "challengeSeed": [
- "var firstName = \"Ada\";",
- "",
- "var thirdToLastLetterOfFirstName = firstName[firstName.length - 3];",
- "",
- "var lastName = \"Lovelace\";",
- "",
- "var secondToLastLetterOfLastName = lastName;",
- "",
- "",
- "// Only change code above this line.",
- "",
- "(function(v){return v;})(secondToLastLetterOfLastName);"
- ],
- "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 var firstName = \"Charles\"
utilizando firstName[firstName.length - 3]
",
- "Usa notación de corchete
para encontrar el segundo último caracter de la cadena en lastName
.",
- "Si te atascas intenta mirando la declaración de la variable thirdToLastLetterOfFirstName
."
- ]
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
},
{
"id": "cf1111c1c11feddfaeb3bdef",
@@ -325,26 +258,21 @@
"description": [
"Let's try to add two numbers using JavaScript.",
"JavaScript uses the +
symbol for addition.",
- "Change the 0
so that sum will equal 20
."
+ "Instructions
Change the 0
so that sum will equal 20
."
],
"tests": [
- "assert((function(){if(sum === 20 && editor.getValue().match(/\\+/g).length >= 2){return true;}else{return false;}})(), 'message: Make the variable sum
equal 20.');"
+ "assert(sum === 20, 'message: sum
should equal 20
');",
+ "assert(/\\+/.test(editor.getValue()), 'message: Use the +
operator');"
],
"challengeSeed": [
"var sum = 10 + 0;",
- "",
- "// Only change code above this line.",
- "",
+ ""
+ ],
+ "tail": [
"(function(z){return 'sum='+z;})(sum);"
],
"type": "waypoint",
- "challengeType": 1,
- "nameEs": "Suma dos números con JavaScript",
- "descriptionEs": [
- "Intentemos sumar dos números con JavaScript.",
- "JavaScript utiliza el símbolo +
para la adición.",
- "Cambie el 0
para que la suma seá igual a 20
."
- ]
+ "challengeType": "1"
},
{
"id": "cf1111c1c11feddfaeb4bdef",
@@ -352,26 +280,25 @@
"description": [
"We can also subtract one number from another.",
"JavaScript uses the -
symbol for subtraction.",
- "Change the 0
so that difference will equal 12
."
+ "Instructions
Change the 0
so that difference will equal 12
."
],
"tests": [
- "assert((function(){if(difference === 12 && editor.getValue().match(/\\-/g)){return true;}else{return false;}})(), 'message: Make the variable difference
equal 12.');"
+ "assert(difference === 12, 'message: Make the variable difference
equal 12.');",
+ "assert(/\\d+\\s*-\\s*\\d+/.test(editor.getValue()),'message: User the -
operator');"
],
"challengeSeed": [
"var difference = 45 - 0;",
"",
- "// Only change code above this line.",
- "",
+ ""
+ ],
+ "tail": [
"(function(z){return 'difference='+z;})(difference);"
],
+ "solutions": [
+ "var difference = 45 - 33;"
+ ],
"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 -
de sustracción",
- "Cambia el 0
para que la diferencia sea 12
."
- ]
+ "challengeType": "1"
},
{
"id": "cf1231c1c11feddfaeb5bdef",
@@ -379,26 +306,25 @@
"description": [
"We can also multiply one number by another.",
"JavaScript uses the *
symbol for multiplication.",
- "Change the 0
so that product will equal 80
."
+ "Instructions
Change the 0
so that product will equal 80
."
],
"tests": [
- "assert((function(){if(product === 80 && editor.getValue().match(/\\*/g)){return true;}else{return false;}})(), 'message: Make the variable product
equal 80.');"
+ "assert(product === 80,'message: Make the variable product
equal 80');",
+ "assert(/\\*/.test(editor.getValue()), 'message: Use the *
operator');"
],
"challengeSeed": [
"var product = 8 * 0;",
"",
- "// Only change code above this line.",
- "",
- "(function(z){return 'product='+z;})(product);"
+ ""
+ ],
+ "tail": [
+ "(function(z){return 'product = '+z;})(product);"
+ ],
+ "solutions": [
+ "var product = 8 * 10;"
],
"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 *
de la multiplicación.",
- "Cambie el 0
para que el producto sea igual a 80
."
- ]
+ "challengeType": "1"
},
{
"id": "cf1111c1c11feddfaeb6bdef",
@@ -406,52 +332,125 @@
"description": [
"We can also divide one number by another.",
"JavaScript uses the /
symbol for division.",
- "Change the 0
so that quotient will equal 2
."
+ "Instructions
Change the 0
so that quotient will equal 2
."
],
"tests": [
- "assert((function(){if(quotient === 2 && editor.getValue().match(/var\\s*?quotient\\s*?\\=\\s*?\\d+\\s*?\\/\\s*?\\d+\\s*?;/g)){return true;}else{return false;}})(), 'message: Make the variable quotient
equal 2.');"
+ "assert(quotient === 2, 'message: Make the variable quotient
equal 2.');",
+ "assert(/\\d+\\s*\\/\\s*\\d+/.test(editor.getValue()), 'message: Use the /
operator');"
],
"challengeSeed": [
"var quotient = 66 / 0;",
"",
- "// Only change code above this line.",
- "",
- "(function(z){return 'quotient='+z;})(quotient);"
+ ""
+ ],
+ "tail": [
+ "(function(z){return 'quotient = '+z;})(quotient);"
],
"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 /
para dividir.",
- "Cambia el 0
para que el cociente sea igual a 2
."
- ]
+ "challengeType": "1"
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244ac",
+ "title": "Increment a Number with Javascript",
+ "description": [
+ "You can easily increment or add one to a Javascript variable with the ++
operator.",
+ "i++;
",
+ "is the equivilent of",
+ "i = i + 1;
",
+ "Instructions
Change the code to use the ++
operator on myVar
"
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(myVar === 88, 'message: myVar
should equal 88
');",
+ "assert(/[+]{2}/.test(editor.getValue()), 'message: Use the ++
operator');",
+ "assert(/var myVar = 87;/.test(editor.getValue()), 'message: Do not change code above the line');"
+ ],
+ "challengeSeed": [
+ "var myVar = 87;",
+ "",
+ "// Only change code below this line",
+ "myVar = myVar + 1;",
+ ""
+ ],
+ "tail": [
+ "(function(z){return 'myVar = ' + z;})(myVar);"
+ ],
+ "solutions": [
+ "var myVar = 87;",
+ "myVar++;"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244ad",
+ "title": "Decrement a Number with Javascript",
+ "description": [
+ "You can easily decrement or decrease by one a Javascript variable with the --
operator.",
+ "i--;
",
+ "is the equivilent of",
+ "i = i - 1;
",
+ "Instructions
Change the code to use the --
operator on myVar
"
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(myVar === 10, 'message: myVar
should equal 10
');",
+ "assert(/myVar[-]{2}/.test(editor.getValue()), 'message: Use the --
operator on myVar
');",
+ "assert(/var myVar = 11;/.test(editor.getValue()), 'message: Do not change code above the line');"
+ ],
+ "challengeSeed": [
+ "var myVar = 11;",
+ "",
+ "// Only change code below this line",
+ "myVar = myVar - 1;",
+ ""
+ ],
+ "tail": [
+ "(function(z){return 'myVar = ' + z;})(myVar);"
+ ],
+ "solutions": [
+ "var myVar = 87;",
+ "myVar--;"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
},
{
"id": "cf1391c1c11feddfaeb4bdef",
"title": "Create Decimal Numbers with JavaScript",
"description": [
- "JavaScript number variables can also have decimals.",
+ "JavaScript number variables can also have decimal points. Decimal numbers are sometimes refered to as floating point numbers or floats. ",
+ "Note",
+ "Not all real numbers can be accurately represented in floating point
. This can lead to rounding errors. Details Here.",
+ "",
"Let's create a variable myDecimal
and give it a decimal value."
],
"tests": [
- "assert((function(){if(typeof myDecimal !== \"undefined\" && typeof myDecimal === \"number\" && editor.getValue().match(/\\./g).length >=2){return true;}else{return false;}})(), 'message: myDecimal
should be a decimal point number.');"
+ "assert(typeof myDecimal === \"number\", 'message: myDecimal
should be a number.');",
+ "assert(editor.getValue().match(/\\d+\\.\\d+/g).length >= 2, 'message: myDecimal
should have a decimal point'); "
],
"challengeSeed": [
"var ourDecimal = 5.7;",
"",
+ "// Only change code below this line",
"",
- "// Only change code above this line.",
- "",
- "(function(){if(typeof myDecimal !== \"undefined\"){return myDecimal;}})();"
+ ""
+ ],
+ "tail": [
+ "(function(){if(typeof(myDecimal) !== \"undefined\"){return myDecimal;}})();"
],
"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 myDecimal
y a darle un valor decimal."
- ]
+ "challengeType": "1"
},
{
"id": "bd7993c9c69feddfaeb7bdef",
@@ -462,24 +461,19 @@
"Change the 0.0
so that product will equal 5.0
."
],
"tests": [
- "assert((function(){if(product === 5.0 && editor.getValue().match(/\\*/g)){return true;}else{return false;}})(), 'message: Make the variable product
equal 5.0.');"
+ "assert(product === 5.0, 'message: The variable product
should equal 5.0
.');",
+ "assert(/\\*/.test(editor.getValue()), 'message: You should use the *
operator');"
+ ],
+ "tail": [
+ "(function(y){return 'product = '+y;})(product);"
],
"challengeSeed": [
"var product = 2.0 * 0.0;",
"",
- "",
- "// Only change code above this line.",
- "",
- "(function(y){return 'product='+y;})(product);"
+ ""
],
"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 0.0
para que el producto sea igual a 5.0
."
- ]
+ "challengeType": "1"
},
{
"id": "bd7993c9ca9feddfaeb7bdef",
@@ -489,244 +483,1088 @@
"Change the 0.0
so that your quotient will equal 2.2
."
],
"tests": [
- "assert((function(){if(quotient === 2.2 && editor.getValue().match(/\\//g)){return true;}else{return false;}})(), 'message: Make the variable quotient
equal 2.2
.');"
+ "assert(quotient === 2.2, 'message: The variable quotient
should equal 2.2
.');",
+ "assert(/\\//.test(editor.getValue()), 'message: You should use the /
operator');"
],
"challengeSeed": [
"var quotient = 0.0 / 2.0;",
"",
- "",
- "// Only change code above this line.",
- "",
- "(function(y){return 'quotient='+y;})(quotient);"
+ ""
+ ],
+ "tail": [
+ "(function(y){return 'quotient = '+y;})(quotient);"
],
"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 0.0
para que tu cociente sea igual a 2.2
."
- ]
+ "challengeType": "1"
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244ae",
+ "title": "Find a Remainder with Modulus",
+ "description": [
+ "The modulus operator %
gives the remainder of the division of two numbers.",
+ "5 % 2
is 1
because",
+ "Math.floor(5 / 2) === 2
2 * 2 === 4
5 - 4 === 1
",
+ "Usage",
+ "Modulus can be helpful in creating alternating or cycling values. For example, in a loop an increasing variable myVar % 2
will alternate between 0 and 1 as myVar goes between even and odd numbers respectively.",
+ "Instructions
Set remainder
equal to the remainder of 11 divided by 3 using the modulus operator."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(remainder === 2, 'message: The value of remainder
should be 2
');",
+ "assert(/\\d+\\s*%\\s*\\d+/.test(editor.getValue()), 'message: You should use the %
operator');"
+ ],
+ "challengeSeed": [
+ "var quotient = Math.floor(11 / 3);",
+ "",
+ "// Only change code below this line",
+ "",
+ "var remainder;",
+ "",
+ ""
+ ],
+ "tail": [
+ "(function(y){return 'remainder = '+y;})(remainder);"
+ ],
+ "solutions": [
+ ""
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244af",
+ "title": "Assignment with Plus Equals",
+ "description": [
+ "In Javascript it is common to need to modify the contents of a variable mathematically. Remember that everything to the right of the equals sign is evaluated first, so we can say:",
+ "myVar = myVar + 5;
",
+ "to add 5
to myVar
. Since this is such a common pattern, there are operators which do both a mathematical operation and assignement in one step.",
+ "One such operator is the +=
operator.",
+ "myVar += 5;
will add 5
to myVar
.",
+ "Instructions
Convert the assignements for a
, b
, and c
to use the +=
operator."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(a === 15, 'message: a
should equal 15
');",
+ "assert(b === 26, 'message: b
should equal 26
');",
+ "assert(c === 19, 'message: c
should equal 19
');",
+ "assert(editor.getValue().match(/\\+=/g).length === 3, 'message: You should use the +=
operator for each variable');",
+ "assert(/var a = 3;/.test(editor.getValue()) && /var b = 17;/.test(editor.getValue()) && /var c = 12;/.test(editor.getValue()), 'message: Do not modify the code above the line');"
+ ],
+ "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;",
+ "var b = 17;",
+ "var c = 12;",
+ "",
+ "a += 12;",
+ "b += 9;",
+ "c += 7;"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244b0",
+ "title": "Assignment with Minus Equals",
+ "description": [
+ "Like the +=
operator, -=
subtracts a number from a variable.",
+ "myVar = myVar - 5;
",
+ "Will subtract 5
from myVar
. This can be rewritten as: ",
+ "myVar -= 5;
",
+ "Instructions
Convert the assignements for a
, b
, and c
to use the -=
operator."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(a === 5, 'message: a
should equal 5
');",
+ "assert(b === -6, 'message: b
should equal -6
');",
+ "assert(c === 2, 'message: c
should equal 2
');",
+ "assert(editor.getValue().match(/-=/g).length === 3, 'message: You should use the -=
operator for each variable');",
+ "assert(/var a = 11;/.test(editor.getValue()) && /var b = 9;/.test(editor.getValue()) && /var c = 3;/.test(editor.getValue()), 'message: Do not modify the code above the line');"
+ ],
+ "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;",
+ "var b = 9;",
+ "var c = 3;",
+ "",
+ "a -= 6;",
+ "b -= 15;",
+ "c -= 1;",
+ "",
+ ""
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244b1",
+ "title": "Assignment with Times Equals",
+ "description": [
+ "Yhe *=
operator multiplies a variable by a number.",
+ "myVar = myVar * 5;
",
+ "Will multiply myVar
by 5
. This can be rewritten as: ",
+ "myVar *= 5;
",
+ "Instructions
Convert the assignements for a
, b
, and c
to use the *=
operator."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(a === 25, 'message: a
should equal 25
');",
+ "assert(b === 36, 'message: b
should equal 36
');",
+ "assert(c === 46, 'message: c
should equal 46
');",
+ "assert(editor.getValue().match(/\\*=/g).length === 3, 'message: You should use the *=
operator for each variable');",
+ "assert(/var a = 5;/.test(editor.getValue()) && /var b = 12;/.test(editor.getValue()) && /var c = 4\\.6;/.test(editor.getValue()), 'message: Do not modify the code above the line');"
+ ],
+ "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 = 20;",
+ "var b = 12;",
+ "var c = 96;",
+ "",
+ "a *= 5;",
+ "b *= 3;",
+ "c *= 10;"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244b2",
+ "title": "Assignment with Divided by Equals",
+ "description": [
+ "The /=
operator divides a variable by another number.",
+ "myVar = myVar / 5;
",
+ "Will divide myVar
by 5
. This can be rewritten as: ",
+ "myVar /= 5;
",
+ "Instructions
Convert the assignments for a
, b
, and c
to use the /=
operator."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(a === 4, 'message: a
should equal 4
');",
+ "assert(b === 27, 'message: b
should equal 27
');",
+ "assert(c === 3, 'message: c
should equal 3
');",
+ "assert(editor.getValue().match(/\\/=/g).length === 3, 'message: You should use the /=
operator for each variable');",
+ "assert(/var a = 48;/.test(editor.getValue()) && /var b = 108;/.test(editor.getValue()) && /var c = 33;/.test(editor.getValue()), 'message: Do not modify the code above the line');"
+ ],
+ "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;",
+ "var b = 108;",
+ "var c = 33;",
+ "",
+ "a /= 12;",
+ "b /= 4;",
+ "c /= 11;"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "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 Tc
representing a temperature in Celsius. Create a variable Tf
and apply the algorithm to assign it the corrasponding temperature in Fahrenheit."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(typeof convert(0) === 'number', 'message: convert(0)
should return a number');",
+ "assert(convert(-30) === -22, 'message: convert(-30)
should return a value of -22
');",
+ "assert(convert(-10) === 14, 'message: convert(-10)
should return a value of 14
');",
+ "assert(convert(0) === 32, 'message: convert(0)
should return a value of 32
');",
+ "assert(convert(20) === 68, 'message: convert(20)
should return a value of 68
');",
+ "assert(convert(30) === 86, 'message: convert(30)
should return a value of 86
');"
+ ],
+ "challengeSeed": [
+ "function convert(Tc) {",
+ " // Only change code below this line",
+ "",
+ "",
+ " // Only change code above this line",
+ " if(typeof Tf !== 'undefined') {",
+ "\treturn Tf;",
+ " } else {",
+ " return \"Tf not defined\";",
+ " }",
+ "}",
+ "",
+ "// Change the inputs below to test your code",
+ "convert(30);"
+ ],
+ "solutions": [
+ "function convert(Tc) {",
+ " var Tf = Tc * 9/5 + 32;",
+ " if(typeof Tf !== 'undefined') {",
+ "\treturn Tf;",
+ " } else {",
+ " return \"Tf not defined\";",
+ " }",
+ "}"
+ ],
+ "type": "bonfire",
+ "challengeType": "5",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "bd7123c9c444eddfaeb5bdef",
+ "title": "Declare String Variables",
+ "description": [
+ "Previously we have used the code var myName = \"your name\"
. This is what we call a String
variable. It is nothing more than a \"string\" of characters. JavaScript strings are always wrapped in quotes.",
+ "Instructions
Create two new string variables: myFirstName
and myLastName
and assign them the values of your first and last name, respectively."
+ ],
+ "tests": [
+ "assert((function(){if(typeof(myFirstName) !== \"undefined\" && typeof(myFirstName) === \"string\" && myFirstName.length > 0){return true;}else{return false;}})(), 'message: myFirstName
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: myLastName
should be a string with at least one character in it.');"
+ ],
+ "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\";",
+ "var myLastName = \"Turing\";"
+ ],
+ "type": "waypoint",
+ "challengeType": "1"
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244b5",
+ "title": "Escaping Literal Quotes in Strings",
+ "description": [
+ "When you are defining a string you must start and end with a double or single quote. What happens when you need a literal quote inside of your string?",
+ "In Javascript you can escape a quote inside a string by placing a backslash (\\
) in front of the quote. This signals Javascript that the following quote is not the end of the string, but should instead should appear inside the string.",
+ "Instruction
Use backslashes to assign the following to myStr
:
\"I am a \"double quoted\" string inside \"double quotes\"\"
"
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(editor.getValue().match(/\\\\\"/g).length === 4 && editor.getValue().match(/[^\\\\]\"/g).length === 2, 'message: You should use two double quotes ("
) and four escaped double quotes (\"
) ');"
+ ],
+ "challengeSeed": [
+ "var myStr; // Change this line",
+ "",
+ ""
+ ],
+ "solutions": [
+ "var myStr = \"I am a \\\"double quoted\\\" string inside \\\"double quotes\\\"\";"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244b4",
+ "title": "Quoting Strings with Single Quotes",
+ "description": [
+ "Strings in Javascript may be declared with both 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.",
+ "\"This string has \\\"double quotes\\\" in it\"
",
+ "The value in using one or the other has to do with the need to escape quotes of the same type. If you have a string with many double quotes, this can be difficult to write and to read. Instead, use single quotes:",
+ "'This string has \"double quotes\" in it'
",
+ "Instructions
Change the provided string from double to single quotes and remove the escaping."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(!/\\\\/g.test(editor.getValue()), 'message: Remove all the backslashes
(\\
)');",
+ "assert(editor.getValue().match(/\"/g).length === 4 && editor.getValue().match(/'/g).length === 2, 'message: You should have two single quotes '
and four double quotes "
')"
+ ],
+ "challengeSeed": [
+ "var myStr = \"Link\";",
+ "",
+ ""
+ ],
+ "solutions": [
+ "var myStr = 'Link';"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244b6",
+ "title": "Escape Sequences in Strings",
+ "description": [
+ "Quotes are not the only character than can be escaped inside a string. Here is a table of common escape sequences:",
+ "Code | Output |
---|
\\' | single quote |
\\\" | double quote |
\\\\ | backslash |
\\n | new line |
\\r | carriage return |
\\t | tab |
\\b | backspace |
\\f | form feed |
",
+ "Note that the backslash itself must be escaped in order to display as a backslash.",
+ "Instructions
Encode the following sequence, seperated by spaces:
backslash tab tab carriage return new line
and assign it to myStr
"
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(myStr === \"\\\\ \\t \\t \\r \\n\", 'message: myStr
should have the escape sequences for backslash tab tab carriage return new line
seperated by spaces');"
+ ],
+ "challengeSeed": [
+ "var myStr; // Change this line",
+ "",
+ ""
+ ],
+ "solutions": [
+ ""
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244b7",
+ "title": "Concatanting Strings with the Plus Operator",
+ "description": [
+ "In Javascript the +
operator for strings is called the concatanation operator. You can build strings out of other strings by concatanating them together.",
+ "Instructions
Build myStr
from the strings \"This is the start. \"
and \"This is the end.\"
using the +
operator.",
+ ""
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(myStr === \"This is the start. This is the end.\", 'message: myStr
should have a value of This is the start. This is the end
');",
+ "assert(editor.getValue().match(/\"\\s*\\+\\s*\"/g).length > 1, 'message: Use the +
operator to build myStr
');"
+ ],
+ "challengeSeed": [
+ "// Example",
+ "var ourStr = \"I come first. \" + \"I come second.\";",
+ "",
+ "// Only change code below this line",
+ "",
+ "var myStr;",
+ "",
+ ""
+ ],
+ "solutions": [
+ "var myStr = \"This is the start. \" + \"This is the end.\";"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244b8",
+ "title": "Concatanting Strings with the Plus Equals Operator",
+ "description": [
+ "We can also use the +=
operator to concatanae a string onto the end of an existing string. This can be very helpful to break a long string over several lines.",
+ "Instructions
",
+ "Build myStr
over several lines by concatanating these two strings:
\"This is the first line. \"
and \"This is the second line.\"
using the +=
operator."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(myStr === \"This is the first line. This is the second line.\", 'message: myStr
should have a value of This is the first line. This is the second line.
');",
+ "assert(editor.getValue().match(/\\w\\s*\\+=\\s*\"/g).length > 1 && editor.getValue().match(/\\w\\s*\\=\\s*\"/g).length > 1, 'message: Use the +=
operator to build myStr
');"
+ ],
+ "challengeSeed": [
+ "// Example",
+ "var ourStr = \"I come first. \";",
+ "ourStr += \"I come second.\";",
+ "",
+ "// Only change code below this line",
+ "",
+ "var myStr;",
+ "",
+ ""
+ ],
+ "solutions": [
+ "var myStr = \"This is the first line. \";",
+ "myStr += \"This is the second line.\";"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244b9",
+ "title": "Constructing Strings with Variables",
+ "description": [
+ "Sometimes you will need to build a string, Mad Libs style. By using the concatanation operator (+
) you can insert one or more varaibles into a string you're building.",
+ "Instructions
Set myName
and build myStr
with myName
between the strings \"My name is \"
and \" and I am swell!\"
"
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(typeof myName !== 'undefined' && myName.length > 2, 'message: myName
should be set to a string at least 3 characters long');",
+ "assert(editor.getValue().match(/\"\\s*\\+\\s*myName\\s*\\+\\s*\"/g).length > 0, 'message: Use two +
operators to build myStr
with myName inside it');"
+ ],
+ "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;",
+ "",
+ ""
+ ],
+ "solutions": [
+ "var myName = \"Bob\";",
+ "var myStr = \"My name is \" + myName + \" and I am swell!\";"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244ed",
+ "title": "Appending Variables to Strings",
+ "description": [
+ "Just as we can build a string over multiple lines out of string literals, we can also append variables to a string using the plus equals (+=
) operator.",
+ "Instructions
Set someAdjective
and append it to myStr
using the +=
operator."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(typeof someAdjective !== 'undefined' && someAdjective.length > 2, 'message: someAdjective
should be set to a string at least 3 characters long');",
+ "assert(editor.getValue().match(/\\w\\s*\\+=\\s*someAdjective\\s*;/).length > 0, 'message: Append someAdjective
to myStr
using the +=
operator');"
+ ],
+ "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 \";",
+ ""
+ ],
+ "solutions": [
+ "var anAdjective = \"awesome!\";",
+ "var ourStr = \"Free Code Camp is \";",
+ "ourStr += anAdjective;",
+ "",
+ "var someAdjective = \"neat\";",
+ "var myStr = \"Learning to code is \";",
+ "myStr += someAdjective;"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "bd7123c9c448eddfaeb5bdef",
+ "title": "Check the Length Property of a String Variable",
+ "description": [
+ "Data structures
have properties
. For example, strings
have a property called .length
that will tell you how many characters are in the string.",
+ "For example, if we created a variable var firstName = \"Charles\"
, we could find out how long the string \"Charles\" is by using the firstName.length
property.",
+ "Instructions
Use the .length
property to count the number of characters in the lastName
variable and assign it to lastNameLength
."
+ ],
+ "tests": [
+ "assert((function(){if(typeof(lastNameLength) !== \"undefined\" && typeof(lastNameLength) === \"number\" && lastNameLength === 8){return true;}else{return false;}})(), 'message: lastNameLength
should be equal to eight.');",
+ "assert((function(){if(editor.getValue().match(/\\.length/gi) && editor.getValue().match(/\\.length/gi).length >= 2 && editor.getValue().match(/var lastNameLength \\= 0;/gi) && editor.getValue().match(/var lastNameLength \\= 0;/gi).length >= 1){return true;}else{return false;}})(), 'message: You should be getting the length of lastName
by using .length
like this: lastName.length
.');"
+ ],
+ "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;})();}"
+ ],
+ "solution": "var lastNameLength = 0;\nvar lastName = \"Lovelace\";\nlastNameLength = lastName.length;",
+ "type": "waypoint",
+ "challengeType": "1"
+ },
+ {
+ "id": "bd7123c9c549eddfaeb5bdef",
+ "title": "Use Bracket Notation to Find the First Character in a String",
+ "description": [
+ "Bracket notation
is a way to get a character at a specific index
within a string.",
+ "Computers don't start counting at 1 like humans do. They start at 0. This is refered to as Zero-based indexing.",
+ "For example, the character at index 0 in the word \"Charles\" is \"C\". So if var firstName = \"Charles\"
, you can get the value of the first letter of the string by using firstName[0]
.",
+ "Instructions
Use bracket notation
to find the first character in the lastName
variable and assign it to firstLetterOfLastName
.",
+ "Hint
Try looking at the firstLetterOfFirstName
variable declaration if you get stuck."
+ ],
+ "tests": [
+ "assert((function(){if(typeof(firstLetterOfLastName) !== \"undefined\" && editor.getValue().match(/\\[0\\]/gi) && typeof(firstLetterOfLastName) === \"string\" && firstLetterOfLastName === \"L\"){return true;}else{return false;}})(), 'message: The firstLetterOfLastName
variable should have the value of L
.');"
+ ],
+ "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 = \"\";",
+ "var lastName = \"Lovelace\";",
+ "",
+ "// Only change code below this line",
+ "firstLetterOfLastName = lastName.length"
+ ],
+ "type": "waypoint",
+ "challengeType": "1"
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244ba",
+ "title": "Understand String Immutability",
+ "description": [
+ "In Javascript, strings are immutable, which means that they cannot be changed or modified once created. For example, this code:",
+ "var myStr = \"Bob\";
myStr[0] = \"J\";
",
+ "will not change the contents of myStr
to \"Job\", because the contents of myStr cannot be altered. Note that this does not mean that myStr
cannot be change, just that individual characters cannot be changes. The only way to change myStr
would be to overwrite the contents with a new string, like this:",
+ "var myStr = \"Bob\";
myStr = \"Job\";
",
+ "Instructions
Correct the assignment to myStr
to achieve the desired effect."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(myStr === \"Hello World\", 'message: myStr
should have a value of Hello World
');",
+ "assert(/myStr = \"Jello World\"/.test(editor.getValue()), 'message: Do not change the code above the line');"
+ ],
+ "tail": [
+ "(function(v){return \"myStr = \" + v;})(myStr);"
+ ],
+ "challengeSeed": [
+ "// Setup",
+ "var myStr = \"Jello World\";",
+ "",
+ "// Only change code below this line",
+ "",
+ "myStr[0] = \"H\"; // Fix Me",
+ "",
+ ""
+ ],
+ "solutions": [
+ "var myStr = \"Jello World\";",
+ "myStr = \"Hello World\";"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "bd7123c9c450eddfaeb5bdef",
+ "title": "Use Bracket Notation to Find the Nth Character in a String",
+ "description": [
+ "You can also use bracket notation
to get the character at other positions within a string.",
+ "Remember that computers start counting at 0, so the first character is actually the zeroth character.",
+ "Instructions
Let's try to set thirdLetterOfLastName
to equal the third letter
of the lastName
variable.",
+ "Hint
Try looking at the secondLetterOfFirstName
variable declaration if you get stuck."
+ ],
+ "tests": [
+ "assert(thirdLetterOfLastName === 'v', 'message: The thirdLetterOfLastName
variable should have the value of v
.');"
+ ],
+ "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\";",
+ "var thirdLetterOfLastName = lastName[2];"
+ ],
+ "type": "waypoint",
+ "challengeType": "1"
+ },
+ {
+ "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 var firstName = \"Charles\"
, you can get the value of the last letter of the string by using firstName[firstName.length - 1]
.",
+ "Instructions
Use bracket notation
to find the last character in the lastName
variable.",
+ "Hint
Try looking at the lastLetterOfFirstName
variable declaration if you get stuck."
+ ],
+ "tests": [
+ "assert(lastLetterOfLastName === \"e\", 'message: lastLetterOfLastName
should be \"e\".');",
+ "assert(editor.getValue().match(/\\.length/g).length === 2, 'message: You have to use .length
to get the last letter.');"
+ ],
+ "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 lastName = \"Lovelace\";",
+ "var lastLetterOfLastName = lastName[lastName.length - 1];"
+ ],
+ "type": "waypoint",
+ "challengeType": "1"
+ },
+ {
+ "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 var firstName = \"Charles\"
string by using firstName[firstName.length - 3]
",
+ "Instructions
Use bracket notation
to find the second-to-last character in the lastName
string.",
+ " Hint
Try looking at the thirdToLastLetterOfFirstName
variable declaration if you get stuck."
+ ],
+ "tests": [
+ "assert(secondToLastLetterOfLastName === 'c', 'message: secondToLastLetterOfLastName
should be \"c\".');",
+ "assert(editor.getValue().match(/\\.length/g).length === 2, 'message: You have to use .length
to get the second last letter.');"
+ ],
+ "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 lastName = \"Lovelace\";",
+ "var secondToLastLetterOfLastName = lastName[lastName.length - 2];"
+ ],
+ "type": "waypoint",
+ "challengeType": "1"
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244bb",
+ "title": "Word Blanks",
+ "description": [
+ "We will now use our knowledge of strings to build a \"Mad Libs\" style word game we're calling \"Word Blanks\". We have provided a framework for testing your results with different words. ",
+ "You will need to use string operators to build a new string, result
, using the provided variables: ",
+ "myNoun
, myAdjative
, myVerb
, and myAdverb
.",
+ "The tests will run your function with several different inputs to make sure it works properly."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(typeof wordBlanks(\"\",\"\",\"\",\"\") === 'string', 'message: wordBlanks(\"\",\"\",\"\",\"\")
should return a string');",
+ "assert(wordBlanks(\"\",\"\",\"\",\"\").length > 50, 'message: wordBlanks(\"\",\"\",\"\",\"\")
should return at least 50 characters with empty inputs');",
+ "assert(/dog/.test(test1) && /big/.test(test1) && /ran/.test(test1) && /quickly/.test(test1),'message: wordBlanks(\"dog\", \"big\", \"ran\", \"quickly\")
should contain all of the passed words.');",
+ "assert(/cat/.test(test2) && /little/.test(test2) && /hit/.test(test2) && /slowly/.test(test2),'message: wordBlanks(\"cat\", \"little\", \"hit\", \"slowly\")
should contain all of the passed words.');"
+ ],
+ "challengeSeed": [
+ "function wordBlanks(myNoun, myAdjative, myVerb, myAdverb) {",
+ " var result = \"\";",
+ " // Your code below this line",
+ "",
+ "",
+ " // Your code above this line",
+ "\treturn 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, myAdjative, myVerb, myAdverb) {",
+ " var result = \"\";",
+ " result = \"Once there was a \" + myNoun + \" which was very \" + myAdjative + \". \";",
+ "\tresult += \"It \" + myVerb + \" \" + myAdverb + \" around the yard.\";",
+ "\treturn result;",
+ "}"
+ ],
+ "type": "bonfire",
+ "challengeType": "5",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
},
{
"id": "bd7993c9c69feddfaeb8bdef",
"title": "Store Multiple Values in one Variable using JavaScript Arrays",
"description": [
"With JavaScript array
variables, we can store several pieces of data in one place.",
- "You start an array declaration with an opening square bracket, end it with a closing square bracket, and put a comma between each entry, like this: var sandwich = [\"peanut butter\", \"jelly\", \"bread\"]
.",
- "Now let's create a new array called myArray
that contains both a string
and a number
(in that order).",
- "Refer to the commented code in the text editor if you get stuck."
+ "You start an array declaration with an opening square bracket, end it with a closing square bracket, and put a comma between each entry, like this:
var sandwich = [\"peanut butter\", \"jelly\", \"bread\"]
.",
+ "Instructions
Create a new array called myArray
that contains both a string
and a number
(in that order).",
+ "Hint
Refer to the example code in the text editor if you get stuck."
],
"tests": [
- "assert(typeof myArray == 'object', 'message: myArray
should be an array
.');",
- "assert(typeof myArray[0] !== 'undefined' && typeof myArray[0] == 'string', 'message: The first item in myArray
should be a string
.');",
- "assert(typeof myArray[1] !== 'undefined' && typeof myArray[1] == 'number', 'message: The second item in myArray
should be a number
.');"
+ "assert(typeof(myArray) == 'object', 'message: myArray
should be an array
.');",
+ "assert(typeof(myArray[0]) !== 'undefined' && typeof(myArray[0]) == 'string', 'message: The first item in myArray
should be a string
.');",
+ "assert(typeof(myArray[1]) !== 'undefined' && typeof(myArray[1]) == 'number', 'message: The second item in myArray
should be a number
.');"
],
"challengeSeed": [
+ "// Example",
"var array = [\"John\", 23];",
"",
"// Only change code below this line.",
- "",
"var myArray = [];",
- "",
- "// Only change code above this line.",
- "",
+ ""
+ ],
+ "tail": [
"(function(z){return z;})(myArray);"
],
+ "solutions": [
+ "var myArray = [\"The Answer\", 42];"
+ ],
"type": "waypoint",
- "challengeType": 1,
- "nameEs": "Almacena múltiples valores en una variable utilizando vectores en JavaScript",
- "descriptionEs": [
- "Con las variables tipo vector
(o en inglés array
) 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í: var sandwich = [\"mantequilla de maní\", \"jalea\" , \"pan\"]
. ",
- "Ahora vamos a crear un nuevo vector llamado myArray
que contenga una cadena
y un número
(en ese orden).",
- "Consulta el código comentado en el editor de texto si te atascas."
- ]
+ "challengeType": "1"
},
{
"id": "cf1111c1c11feddfaeb7bdef",
"title": "Nest one Array within Another Array",
"description": [
- "You can also nest arrays within other arrays, like this: [[\"Bulls\", 23]]
.",
- "Let's now go create a nested array called myArray
."
+ "You can also nest arrays within other arrays, like this: [[\"Bulls\", 23]]
. This is also called a Multi-dimensional Array.",
+ "Instructions
Create a nested array called myArray
."
],
"tests": [
"assert(Array.isArray(myArray) && myArray.some(Array.isArray), 'message: myArray
should have at least one array nested within another array.');"
],
"challengeSeed": [
+ "// Example",
"var ourArray = [[\"the universe\", \"everything\", 42]];",
"",
"// Only change code below this line.",
- "",
"var myArray = [];",
- "",
- "// Only change code above this line.",
- "",
- "if(typeof myArray !== \"undefined\"){(function(){return myArray;})();}"
+ ""
+ ],
+ "tail": [
+ "if(typeof(myArray) !== \"undefined\"){(function(){return myArray;})();}"
+ ],
+ "solutions": [
+ "var myArray = [[1,2,3]];"
],
"type": "waypoint",
- "challengeType": 1,
- "nameEs": "Anida un vector dentro de otro vector",
- "descriptionEs": [
- "También puedes anidar vectores dentro de otros vectores, como este: [[\"Bulls\", 23]]
.",
- "Ahora vamos a crear un vector anidado llamado myArray
."
- ]
+ "challengeType": "1"
},
{
"id": "bg9997c9c79feddfaeb9bdef",
"title": "Access Array Data with Indexes",
"description": [
"We can access the data inside arrays using indexes
.",
- "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.",
+ "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 zero-based indexing, so the first element in an array is element 0
",
"For example:",
"var array = [1,2,3];
",
"array[0]; //equals 1
",
"var data = array[1];
",
- "Create a variable called myData
and set it to equal the first value of myArray
."
+ "Instructions
Create a variable called myData
and set it to equal the first value of myArray
."
],
"tests": [
- "assert((function(){if(typeof myArray != 'undefined' && typeof myData != 'undefined' && myArray[0] == myData){return true;}else{return false;}})(), 'message: The variable myData
should equal the first value of myArray
.');"
+ "assert((function(){if(typeof(myArray) != 'undefined' && typeof(myData) != 'undefined' && myArray[0] == myData){return true;}else{return false;}})(), 'message: The variable myData
should equal the first value of myArray
.');"
],
"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.",
- "",
- "",
- "// Only change code above this line.",
- "",
- "if(typeof myArray !== \"undefined\" && typeof myData !== \"undefined\"){(function(y,z){return 'myArray = ' + JSON.stringify(y) + ', myData = ' + JSON.stringify(z);})(myArray, myData);}"
+ ""
+ ],
+ "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];",
+ "var myData = myArray[0];"
],
"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 índices
.",
- "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:",
- "var array = [1,2,3];
",
- "array[0]; //es igual a 1
",
- "var data = array[1];
",
- "Crea una variable llamada myData code> y asignale el primer valor del vector myArray
."
- ]
+ "challengeType": "1"
},
{
"id": "cf1111c1c11feddfaeb8bdef",
"title": "Modify Array Data With Indexes",
"description": [
- "We can also modify the data stored in arrays by using indexes.",
+ "Unlike strings, the contents of arrays can are mutable and can be freely changed.",
"For example:",
"var ourArray = [3,2,1];
",
"ourArray[0] = 1; // equals [1,2,1]
",
- "Now modify the data stored at index 0 of myArray
to the value of 3."
+ "Instructions
Modify the data stored at index 0
of myArray
to a value of 3
."
],
"tests": [
- "assert((function(){if(typeof myArray != 'undefined' && myArray[0] == 3 && myArray[1] == 2 && myArray[2] == 3){return true;}else{return false;}})(), 'message: myArray
should now be [3,2,3].');",
+ "assert((function(){if(typeof(myArray) != 'undefined' && myArray[0] == 3 && myArray[1] == 2 && myArray[2] == 3){return true;}else{return false;}})(), 'message: myArray
should now be [3,2,3].');",
"assert((function(){if(editor.getValue().match(/myArray\\[0\\]\\s?=\\s?/g)){return true;}else{return false;}})(), 'message: You should be using correct index to modify the value in myArray
.');"
],
"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.",
"",
- "",
- "",
- "// Only change code above this line.",
- "",
- "if(typeof myArray !== \"undefined\"){(function(){return myArray;})();}"
+ ""
+ ],
+ "tail": [
+ "if(typeof(myArray) !== \"undefined\"){(function(){return myArray;})();}"
+ ],
+ "solutions": [
+ "var myArray = [1,2,3];",
+ "myArray[0] = 3;"
],
"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:",
- "var ourArray = [3,2,1];
",
- "ourArray[0] = 1; // equals [1,2,1]
",
- "Ahora establece el dato almacenado en el índice 0 de myArray
para que sea el valor 3."
- ]
+ "challengeType": "1"
},
{
- "id": "bg9994c9c69feddfaeb9bdef",
- "title": "Manipulate Arrays With pop()",
+ "id": "56592a60ddddeae28f7aa8e1",
+ "title": "Access Multi-Dimensional Arrays With Indexes",
"description": [
- "Another way to change the data in an array is with the .pop()
function.",
- ".pop()
is used to \"pop\" a value off of the end of an array. We can store this \"popped off\" variable by performing pop()
within a variable declaration.",
- "Any type of data structure can be \"popped\" off of an array - numbers, strings, even nested arrays.",
- "Use the .pop()
function to remove the last item from myArray
, assigning the \"popped off\" value to removedFromMyArray
."
+ "One way to think of a multi-dimensional array, is as an array of arrays. When you use brackets to access your array, the first set of bracket refers to the outer-most array, and each subsequent level of brackets refers to the next level in.",
+ "For example:",
+ "var arr = [
[1,2,3],
[4,5,6],
[7,8,9],
[[10,11,12], 13, 14]
];
",
+ "arr[0]; // equals [1,2,3]
",
+ "arr[1][2]; // equals 6
",
+ "arr[3][0][1]; // equals 11
",
+ "Instructions
Read from myArray
using bracket notation so that myData is equal to 8
"
],
"tests": [
- "assert((function(d){if(d[0] == 'John' && d[1] == 23 && d[2] == undefined){return true;}else{return false;}})(myArray), 'message: myArray
should only contain [\"John\", 23]
.');",
- "assert((function(d){if(d[0] == 'cat' && d[1] == 2 && d[2] == undefined){return true;}else{return false;}})(removedFromMyArray), 'message: removedFromMyArray
should only contain [\"cat\", 2]
.');"
+ "assert(myData === 8, 'message: myData
should be equal to 8
.');",
+ "assert(/myArray\\[2\\]\\[1\\]/g.test(editor.getValue()), 'message: You should be using bracket notation to read the value from myArray
.');"
],
"challengeSeed": [
- "var ourArray = [1,2,3];",
- "",
- "var removedFromOurArray = ourArray.pop(); // removedFromOurArray now equals 3, and ourArray now equals [1,2]",
- "",
- "var myArray = [\"John\", 23, [\"cat\", 2]];",
+ "// Setup",
+ "var myArray = [[1,2,3],[4,5,6], [7,8,9], [[10,11,12], 13, 14]];",
"",
"// Only change code below this line.",
- "",
- "var removedFromMyArray;",
- "",
- "// Only change code above this line.",
- "",
- "(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);"
+ "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]];",
+ "var myData = myArray[2][1];"
],
"type": "waypoint",
- "challengeType": 1,
- "nameEs": "Manipula vectores con pop()",
- "descriptionEs": [
- "Otra forma de cambiar los datos en un vector es con la función .pop()
.",
- ".pop()
se utiliza para \"sacar\" el valor final de un vector. Podemos almacenar el valor \"sacado\" asignando pop
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 .pop()
para sacar el último elemento de myArray
y asigna ese valor \"sacado\" a removedFromMyArray
."
- ]
+ "challengeType": "1"
},
{
"id": "bg9995c9c69feddfaeb9bdef",
"title": "Manipulate Arrays With push()",
"description": [
- "Not only can you pop()
data off of the end of an array, you can also push()
data onto the end of an array.",
- "Push [\"dog\", 3]
onto the end of the myArray
variable."
+ "An easy way to append data to the end of an array is via the push()
method. push()
takes a value and \"pushes\" it onto the end of the array.",
+ "var arr = [1,2,3];
",
+ "arr.push(4);
",
+ "// arr is now [1,2,3,4]
",
+ "Instructions
Push [\"dog\", 3]
onto the end of the myArray
variable."
],
"tests": [
- "assert((function(d){if(d[2] != undefined && d[0] == 'John' && d[1] == 23 && d[2][0] == 'dog' && d[2][1] == 3 && d[2].length == 2){return true;}else{return false;}})(myArray), 'message: myArray
should now equal [\"John\", 23, [\"dog\", 3]]
.');"
+ "\nassert((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: myArray
should now equal [[\"John\", 23], [\"cat\", 2], [\"dog\", 3]]
.');"
],
"challengeSeed": [
- "var ourArray = [\"Stimpson\", \"J\", [\"cat\"]];",
+ "// Example",
+ "var ourArray = [\"Stimpson\", \"J\", \"cat\"];",
+ "ourArray.push([\"happy\", \"joy\"]); ",
+ "// ourArray now equals [\"Stimpson\", \"J\", \"cat\", [\"happy\", \"joy\"]]",
"",
- "ourArray.pop(); // ourArray now equals [\"Stimpson\", \"J\"]",
- "",
- "ourArray.push([\"happy\", \"joy\"]); // ourArray now equals [\"Stimpson\", \"J\", [\"happy\", \"joy\"]]",
- "",
- "var myArray = [\"John\", 23, [\"cat\", 2]];",
- "",
- "myArray.pop();",
+ "// Setup",
+ "var myArray = [[\"John\", 23], [\"cat\", 2]];",
"",
"// Only change code below this line.",
"",
- "",
- "",
- "// Only change code above this line.",
- "",
+ "\t"
+ ],
+ "tail": [
"(function(z){return 'myArray = ' + JSON.stringify(z);})(myArray);"
],
+ "solutions": [
+ "var myArray = [[\"John\", 23], [\"cat\", 2]];",
+ "myArray.push([\"dog\",3]);"
+ ],
"type": "waypoint",
- "challengeType": 1,
- "nameEs": "Manipula vectores con push()",
- "descriptionEs": [
- "No sólo se pueden sacar datos del final de un vector con pop()
, también puedes empujar (push()
) datos al final del vector.",
- "Empuja [\"dog\", 3]
al final de la variable myArray
."
- ]
+ "challengeType": "1"
+ },
+ {
+ "id": "bg9994c9c69feddfaeb9bdef",
+ "title": "Manipulate Arrays With pop()",
+ "description": [
+ "Another way to change the data in an array is with the .pop()
function. ",
+ ".pop()
is used to \"pop\" a value off of the end of an array. We can store this \"popped off\" variable by performing pop()
within a variable declaration.",
+ "Any type of data structure can be \"popped\" off of an array - numbers, strings, even nested arrays.",
+ "Instructions
Use the .pop()
function to remove the last item from myArray
, assigning the \"popped off\" value to removedFromMyArray
."
+ ],
+ "tests": [
+ "assert((function(d){if(d[0][0] == 'John' && d[0][1] == 23 && d[2] == undefined){return true;}else{return false;}})(myArray), 'message: myArray
should only contain [[\"John\", 23]]
.');",
+ "assert((function(d){if(d[0] == 'cat' && d[1] == 2 && d[2] == undefined){return true;}else{return false;}})(removedFromMyArray), 'message: removedFromMyArray
should only contain [\"cat\", 2]
.');"
+ ],
+ "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": [
+ ""
+ ],
+ "type": "waypoint",
+ "challengeType": "1"
},
{
"id": "bg9996c9c69feddfaeb9bdef",
@@ -734,34 +1572,37 @@
"description": [
"pop()
always removes the last element of an array. What if you want to remove the first?",
"That's where .shift()
comes in. It works just like .pop()
, except it removes the first element instead of the last.",
- "Use the .shift()
function to remove the first item from myArray
, assigning the \"shifted off\" value to removedFromMyArray
."
+ "Instructions
Use the .shift()
function to remove the first item from myArray
, assigning the \"shifted off\" value to removedFromMyArray
."
],
"tests": [
- "assert((function(d){if(d[0] == 23 && d[1][0] == 'dog' && d[1][1] == 3 && d[2] == undefined){return true;}else{return false;}})(myArray), 'message: myArray
should now equal [23, [\"dog\", 3]]
.');",
- "assert((function(d){if(d === 'John' && typeof removedFromMyArray === 'string'){return true;}else{return false;}})(removedFromMyArray), 'message: removedFromMyArray
should contain \"John\"
.');"
+ "assert((function(d){if(d[0][0] == 'dog' && d[0][1] == 3 && d[1] == undefined){return true;}else{return false;}})(myArray), 'message: myArray
should now equal [[\"dog\", 3]]
.');",
+ "assert((function(d){if(d[0] === 'John' && d[1] === 23 && typeof(removedFromMyArray) === 'object'){return true;}else{return false;}})(removedFromMyArray), 'message: removedFromMyArray
should contain [\"John\", 23]
.');"
],
"challengeSeed": [
+ "// Example",
"var ourArray = [\"Stimpson\", \"J\", [\"cat\"]];",
+ "removedFromOurArray = ourArray.shift();",
+ "// removedFromOurArray now equals \"Stimpson\" and ourArray now equals [\"J\", [\"cat\"]].",
"",
- "var 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]];",
"",
"// Only change code below this line.",
- "",
- "var removedFromMyArray;"
- ],
- "tail":[
- "(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);"
+ "var removedFromMyArray = myArray.shift();"
],
"type": "waypoint",
- "challengeType": 1,
- "nameEs": "Manipula vectores con shift()",
- "descriptionEs": [
- "pop()
siempre elimina el último elemento de un vector. ¿Qué pasa si quieres quitar el primero?",
- "Ahí es donde entra .shift()
. Funciona igual que .pop ()
, excepto que elimina el primer elemento en lugar del pasado. ",
- "Usa la función .shift()
para eliminar el primer elemento de myArray
, y el elemento que saques asignalo a removedFromMyArra
"
- ]
+ "challengeType": "1"
},
{
"id": "bg9997c9c69feddfaeb9bdef",
@@ -769,90 +1610,1603 @@
"description": [
"Not only can you shift
elements off of the beginning of an array, you can also unshift
elements onto the beginning of an array.",
"unshift()
works exactly like push()
, but instead of adding the element at the end of the array, unshift()
adds the element at the beginning of the array.",
- "Add \"Paul\"
onto the beginning of the myArray
variable using unshift()
."
+ "Instructions
Add [\"Paul\",35]
onto the beginning of the myArray
variable using unshift()
."
],
"tests": [
- "assert((function(d){if(typeof d[0] === \"string\" && d[0].toLowerCase() == 'paul' && d[1] == 23 && d[2][0] != undefined && d[2][0] == 'dog' && d[2][1] != undefined && d[2][1] == 3){return true;}else{return false;}})(myArray), 'message: myArray
should now have [\"Paul\", 23, [\"dog\", 3]]).');"
+ "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: myArray
should now have [[\"Paul\", 35], [\"dog\", 3]]).');"
],
"challengeSeed": [
- "var ourArray = [\"Stimpson\", \"J\", [\"cat\"]];",
- "",
- "ourArray.shift(); // ourArray now equals [\"J\", [\"cat\"]]",
- "",
- "ourArray.unshift(\"happy\"); // ourArray now equals [\"happy\", \"J\", [\"cat\"]]",
- "",
- "var myArray = [\"John\", 23, [\"dog\", 3]];",
+ "// 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.",
"",
- "",
- "",
- "// Only change code above this line.",
- "",
+ ""
+ ],
+ "tail": [
"(function(y, z){return 'myArray = ' + JSON.stringify(y);})(myArray);"
],
+ "solutions": [
+ "var myArray = [[\"John\", 23], [\"dog\", 3]];",
+ "myArray.shift();",
+ "myArray.unshift([\"Paul\", 35]);"
+ ],
"type": "waypoint",
- "challengeType": 1,
- "nameEs": "Manipula vectores con unshift()",
- "descriptionEs": [
- "No sólo se puedes correr
(shift) elementos del comienzo de un vector, también puedes descorrerlos
(unshift) al comienzo.",
- "unshift()
funciona exactamente igual que push()
, pero en lugar de añadir el elemento al final del vector, unshift()
añade el elemento al comienzo del vector. ",
- "Añade \"Paul\"
al comienzo de la variable myArray
usando unshift()
."
- ]
+ "challengeType": "1"
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244bc",
+ "title": "Shopping List",
+ "description": [
+ "Create a shopping list in the variable myList
. The list should be a multi-dimensional array containing several sub-arrays. ",
+ "The first element in each sub-array should contain a string with the name of the item. The second element should be a number representing the quantity. IE:",
+ "[\"Chocolate Bar\", 15]
",
+ "There should be at least 5 sub-arrays in the list."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(isArray, 'message: myList
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');"
+ ],
+ "challengeSeed": [
+ "var myList = [];",
+ "",
+ ""
+ ],
+ "tail": [
+ "var count = 0;",
+ "var isArray = true;",
+ "var hasString = true;",
+ "var hasNumber = true;",
+ "(function(list){",
+ " if(Array.isArray(myList)) {",
+ " 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 {",
+ " isArray = false;",
+ " return \"myList is not an array\";",
+ " }",
+ "",
+ "})(myList);"
+ ],
+ "solutions": [
+ "var myList = [",
+ " [\"Candy\", 10],",
+ " [\"Potatoes\", 12],",
+ " [\"Eggs\", 12],",
+ " [\"Catfood\", 1],",
+ " [\"Toads\", 9]",
+ "];"
+ ],
+ "type": "bonfire",
+ "challengeType": "5",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
},
{
"id": "bg9997c9c89feddfaeb9bdef",
"title": "Write Reusable JavaScript with Functions",
"description": [
- "In JavaScript, we can divide up our code into reusable parts called functions.",
+ "In JavaScript, we can divide up our code into reusable parts called functions.",
"Here's an example of a function:",
- "function functionName(a, b) {
",
- " return a + b;
",
+ "function functionName() {
",
+ " console.log(\"Hello World\");
",
"}
",
- "After writing the above lines in our code, we can then pass values to our function and the result following the return
statement will be returned.",
- "For example, we can pass numbers 4
and 2
by “calling” the function later in our code like this: functionName(4, 2)
.",
- "In this example, the function will return the number 6
as this is the result of 4 + 2
.",
- "Create and call a function called myFunction
that returns the sum of a
and b
."
+ "You can call or invoke this function by using its name followed by parenthese, like this:",
+ "functionName();
",
+ "Each time the function is called it will print out the message \"Hello World\" on the dev console. All of the code between the curly braces will be executed every time the function is called.",
+ "Instructions
Create a function called myFunction
which prints \"Hi World\" to the dev console. Call that function."
],
"tests": [
- "assert((function(){if(typeof f !== \"undefined\" && f === a + b){return true;}else{return false;}})(), 'message: Your function should return the value of a + b
.');"
+ "console.log(\"1 '\" + logOutput + \"'\", \"op: \" + /Hi World/.test(logOutput)); assert(\"Hi World\" === logOutput, 'message: myFunction
should output \"Hi World\"');",
+ "assert(typeof myFunction === 'function', 'message: myFunction
should be a function');"
],
"challengeSeed": [
- "var a = 4;",
- "var b = 5;",
- "",
- "function ourFunction(a, b) {",
- " return a - b;",
+ "// Example",
+ "function ourFunction() {",
+ " console.log(\"Heyya, World\");",
"}",
"",
+ "// Only change code below this line",
+ "",
+ ""
+ ],
+ "tail": [
+ "var logOutput = \"\";",
+ "var oldLog = console.log;",
+ "function capture() {",
+ " console.log = function (message) {",
+ " logOutput = message.trim();",
+ " oldLog.apply(console, arguments);",
+ " };",
+ "}",
+ "",
+ "function uncapture() {",
+ " console.log = oldLog;",
+ "}",
+ "",
+ "if (typeof myFunction !== \"function\") { ",
+ " (function() { return \"myFunction is not defined\"; })();",
+ "} else {",
+ " capture();",
+ " myFunction(); ",
+ " uncapture();",
+ " (function() { return logOutput || \"console.log never called\"; })();",
+ "}"
+ ],
+ "solutions": [
+ "function myFunction() {",
+ " console.log(\"Hi World\");",
+ "}"
+ ],
+ "type": "waypoint",
+ "challengeType": "1"
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244bd",
+ "title": "Passing Values to Functions with Arguments",
+ "description": [
+ "Functions can take input in the form of parameters. Parameters
are variables that take on the value of the arguments which are passed in to the function. Here is a function with two parameters, param1
and param2
:",
+ "function testFunct(param1, param2) {
",
+ " console.log(param1, param2);
",
+ "}
",
+ "Then we can call testFunction
:",
+ "testFunction(\"Hello\", \"World\");
",
+ "We have passed two arguments, \"Hello\" and \"World\". Inside the function, param1
will equal \"Hello\" and param2
will equal \"World\". Note that you could call testFunction
again with different arguments and the parameters would take on the value of the new arguments.",
+ "Instructions
Create a function called myFunction
that accepts two arguements and outputs their sum to console.log
"
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert((function(){if(typeof(f) !== \"undefined\" && f === a + b){return true;}else{return false;}})(), 'message: Your function should ouput the value of a + b
.');"
+ ],
+ "challengeSeed": [
+ "// Example",
+ "function ourFunction(a, b) {",
+ " console.log(a - b);",
+ "}",
+ "ourFunction(10, 5); // Outputs 5",
+ "",
"// Only change code below this line.",
"",
"",
+ ""
+ ],
+ "tail": [
+ ""
+ ],
+ "solutions": [
+ ""
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244be",
+ "title": "Global Scope and Functions",
+ "description": [
+ "In Javascript, scope refers to the visibility of variables."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(1===1, 'message: message here');"
+ ],
+ "challengeSeed": [
"",
"",
- "// Only change code above this line.",
+ ""
+ ],
+ "tail": [
+ ""
+ ],
+ "solutions": [
+ ""
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244bf",
+ "title": "Local Scope and Functions",
+ "description": [
+ "In Javascript, Scope
is the test of variables, object, and functions you have access to. Variables which are defined within a function and parameters are local, which means they are only visible within that function. ",
+ "Here is a function test
with a local variable called loc
.",
+ "function test() {
var loc = \"foo\";
console.log(local1); // \"foo\"
}
test();
console.log(loc); // \"undefined\"
",
+ "loc
is not defined outside of the function."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(1===1, 'message: message here');"
+ ],
+ "challengeSeed": [
"",
- "if(typeof myFunction !== \"undefined\"){",
- "var f=myFunction(a,b);",
- "(function(){return f;})();",
+ "",
+ ""
+ ],
+ "tail": [
+ ""
+ ],
+ "solutions": [
+ ""
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244c0",
+ "title": "Global vs. Local Scope in Functions",
+ "description": [
+ "Show how global and local scopes interact"
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(1===1, 'message: message here');"
+ ],
+ "challengeSeed": [
+ "",
+ "",
+ ""
+ ],
+ "solutions": [
+ ""
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244c1",
+ "title": "Context for Functions",
+ "description": [
+ "Show how each instance of a function has its own values/context"
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(1===1, 'message: message here');"
+ ],
+ "challengeSeed": [
+ "",
+ "",
+ ""
+ ],
+ "tail": [
+ ""
+ ],
+ "solutions": [
+ ""
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244c2",
+ "title": "Return a Value from a Function with Return",
+ "description": [
+ "We can pass values into a function with arguments. You can use a return
statement to send a value back out of a function.",
+ "For Example:",
+ "function plusThree(num) {
return num + 3;
}
var answer = plusThree(5); // 8
",
+ "plusThree
takes an argument for num
and returns a value equal to num + 3
.",
+ "Instructions
Create a function timesFive
that accepts one argument, multiplies it by 5
, and returns the new value."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(typeof timesFive === 'function', 'message: timesFive
should be a function');",
+ "assert(timesFive(5) === 25, 'message: timesFive(5)
should return 25
');",
+ "assert(timesFive(2) === 10, 'message: timesFive(2)
should return 10
');",
+ "assert(timesFive(0) === 0, 'message: timesFive(0)
should return 0
');"
+ ],
+ "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) {",
+ " return num * 5;",
"}"
],
"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:",
- "function nombreDeFuncion(a, b) {
",
- "& nbsp; & nbsp; return a + b;
",
- "}
",
- "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 return
será retornado.",
- "Por ejemplo, podemos pasar los números 4
y 2
al \"llamar\" la función más adelante en nuestro código, así: nombreDeFuncion(4, 2) code >. ",
- "En este ejemplo, la función devolverá el número 6
, ya que es el resultado de 4 + 2
.",
- "Crea y llama una función de nombre myFunction
que devuelva la suma de a
y b
."
- ]
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244c3",
+ "title": "Assignment with a Returned Value",
+ "description": [
+ "If you'll recall from our discussion of Storing Values with the Equal Operator, everything to the right of the equal sign is resolved before the value is assigned. This means we can take the return value of a function and assign it to a variable.",
+ "Assume we have pre-defined a function sum
which adds two numbers together, then: ",
+ "var ourSum = sum(5, 12);
",
+ "will call sum
, which returns a value of 17
and assigns it to ourSum
.",
+ "Instructions
"
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(1===1, 'message: message here');"
+ ],
+ "challengeSeed": [
+ "// Setup",
+ "function process(num) {",
+ " return (num + 3) / 5;",
+ "}",
+ "",
+ "// Only change code below this line",
+ "var processed = 0; // Change this line",
+ ""
+ ],
+ "tail": [
+ ""
+ ],
+ "solutions": [
+ ""
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244c4",
+ "title": "Return Early Pattern for Functions",
+ "description": [
+ "Explain how to use return early for functions"
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(1===1, 'message: message here');"
+ ],
+ "challengeSeed": [
+ "",
+ "",
+ ""
+ ],
+ "tail": [
+ ""
+ ],
+ "solutions": [
+ ""
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244c5",
+ "title": "Optional Arguments for Functions",
+ "description": [
+ ""
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(1===1, 'message: message here');"
+ ],
+ "challengeSeed": [
+ "",
+ "",
+ ""
+ ],
+ "tail": [
+ ""
+ ],
+ "solutions": [
+ ""
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244c6",
+ "title": "Checkpoint: Functions",
+ "description": [
+ "Note: Function Length tips - 10-20 lines, etc"
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(1===1, 'message: message here');"
+ ],
+ "challengeSeed": [
+ "",
+ "",
+ ""
+ ],
+ "tail": [
+ ""
+ ],
+ "solutions": [
+ ""
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "cf1111c1c12feddfaeb3bdef",
+ "title": "Use Conditional Logic with If Statements",
+ "description": [
+ "We can use if
statements in JavaScript to only execute code if a certain condition is met.",
+ "if
statements require a boolean condition to evaluate. If the boolean evaluates to true, the statement inside the curly braces executes. If it evaluates to false, the code will not execute.",
+ "For example:",
+ "function test(myVal) {
if (myVal > 10) {
return \"Greater Than\";
}
return \"Not Greater Than\";
}
",
+ "If myVal
is greater than 10
, the function will return \"Greater Than\". If it is not, the function will return \"Not Greater Than\".",
+ "Instructions
Create an if
statement inside the function to return \"Yes\"
if testMe
is greater than 5
. Return \"No\"
if it is less than 5
."
+ ],
+ "tests": [
+ "assert(typeof myFunction === \"function\", 'message: myFunction
should be a function');",
+ "assert(typeof myFunction(4) === \"string\", 'message: myFunction(4)
should return a string');",
+ "assert(typeof myFunction(6) === \"string\", 'message: myFunction(6)
should return a string');",
+ "assert(myFunction(4) === \"No\", 'message: myFunction(4)
should \"No\"');",
+ "assert(myFunction(5) === \"No\", 'message: myFunction(5)
should \"No\"');",
+ "assert(myFunction(6) === \"Yes\", 'message: myFunction(6)
should \"Yes\"');"
+ ],
+ "challengeSeed": [
+ "// Example",
+ "function ourFunction(testMe) {",
+ " if (testMe > 10) { ",
+ " return \"Yes\";",
+ " }",
+ " return \"No\";",
+ "}",
+ "",
+ "// Setup",
+ "function myFunction(testMe) {",
+ "",
+ " // Only change code below this line.",
+ "",
+ "",
+ "",
+ " // Only change code above this line.",
+ "",
+ "}",
+ "",
+ "// Change this value to test",
+ "myFunction(10);"
+ ],
+ "solutions": [
+ "function myFunction(testMe) {",
+ " if (testMe > 5) {",
+ " return 'Yes';",
+ " }",
+ " return 'No';",
+ "}"
+ ],
+ "type": "waypoint",
+ "challengeType": "1"
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244d0",
+ "title": "Comparison with the Equality Operator",
+ "description": [
+ "There are many Comparison Operators in Javascript. All of these operators return a boolean true
or false
value.",
+ "The most basic operators is the equality operator ==
. The equality operator compares to values and returns true if they're equivilent or false if they are not. Note that equality is different from assignement (=
), which returns the value to the right of the operator.",
+ "function equalityTest(myVal) {
if (myVal == 10) {
return \"Equal\";
}
return \"Not Equal\";
}
",
+ "If myVal
is equal to 10
, the function will return \"Equal\". If it is not, the function will return \"Not Equal\".",
+ "The equality operator will do it's best to convert values for comparison, for example:",
+ " 1 == 1 // true
\"1\" == 1 // true
1 == '1' // true
0 == false // true
0 == null // false
0 == undefined // false
null == undefined // true
",
+ "Instructions
Add the equality operator
to the indicated line so the function will return \"Equal\" when val
is equivilent to 12
"
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(myTest(10) === \"Not Equal\", 'message: myTest(10)
should return \"Not Equal\"');",
+ "assert(myTest(12) === \"Equal\", 'message: myTest(12)
should return \"Equal\"');",
+ "assert(myTest(\"12\") === \"Equal\", 'message: myTest(\"12\")
should return \"Equal\"');",
+ "assert(editor.getValue().match(/val\\s*==\\s*\\d+/g).length > 0, 'message: You should use the ==
operator');"
+ ],
+ "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) {",
+ " if (val == 12) {",
+ " return \"Equal\";",
+ " }",
+ " return \"Not Equal\";",
+ "}"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244d1",
+ "title": "Comparison with the Strict Equality Operator",
+ "description": [
+ "Strict equality (===
) is the counterpart to the equality operator (==
). Unlike the equality operator, strict equality tests both the type and value of the compared elements.",
+ "Examples3 === 3 // true
3 === '3' // false
",
+ "Instructions
Change the equality operator to a strict equality on the if
statement so the function will return \"Equal\" when val
is strictltly equal to 7
"
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(myTest(10) === \"Not Equal\", 'message: myTest(10)
should return \"Not Equal\"');",
+ "assert(myTest(7) === \"Equal\", 'message: myTest(7)
should return \"Equal\"');",
+ "assert(myTest(\"7\") === \"Not Equal\", 'message: myTest(\"7\")
should return \"Not Equal\"');",
+ "assert(editor.getValue().match(/val\\s*===\\s*\\d+/g).length > 0, 'message: You should use the ===
operator');"
+ ],
+ "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) {",
+ " if (val == 7) {",
+ " return \"Equal\";",
+ " }",
+ " return \"Not Equal\";",
+ "}"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244d2",
+ "title": "Comparison with the Inequality Operator",
+ "description": [
+ "The inequality operator (!=
) is the opposite of the equality operator. It means \"Not Equal\" and returns false
where equality would return true
and vice versa. Like the equality operator, the inequality operator will convert types.",
+ "Examples1 != 2 // true
1 != \"1\" // false
1 != '1' // false
1 != true // false
0 != false // false
",
+ "Instructions
Add the inequality operator !=
to the if
statement so the function will return \"Not Equal\" when val
is not equivilent to 99
"
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(myTest(99) === \"Equal\", 'message: myTest(99)
should return \"Equal\"');",
+ "assert(myTest(\"99\") === \"Equal\", 'message: myTest(\"99\")
should return \"Equal\"');",
+ "assert(myTest(12) === \"Not Equal\", 'message: myTest(12)
should return \"Not Equal\"');",
+ "assert(myTest(\"12\") === \"Not Equal\", 'message: myTest(\"12\")
should return \"Not Equal\"');",
+ "assert(myTest(\"bob\") === \"Not Equal\", 'message: myTest(\"bob\")
should return \"Not Equal\"');",
+ "assert(editor.getValue().match(/val\\s*!=\\s*\\d+/g).length > 0, 'message: You should use the !=
operator');"
+ ],
+ "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) {",
+ " if (val != 99) {",
+ " return \"Not Equal\";",
+ " }",
+ " return \"Equal\";",
+ "}"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244d3",
+ "title": "Comparison with the Strict Inequality Operator",
+ "description": [
+ "The inequality operator (!==
) is the opposite of the strict equality operator. It means \"Strictly Not Equal\" and returns false
where strict equality would return true
and vice versa. Strict inequality will not convert types.",
+ "Examples3 !== 3 // false
3 !== '3' // true
4 !== 3 // true
",
+ "Instructions
Add the strict inequality operator
to the if
statement so the function will return \"Not Equal\" when val
is not strictly equal to 17
"
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(myTest(17) === \"Equal\", 'message: myTest(17)
should return \"Equal\"');",
+ "assert(myTest(\"17\") === \"Not Equal\", 'message: myTest(\"17\")
should return \"Not Equal\"');",
+ "assert(myTest(12) === \"Not Equal\", 'message: myTest(12)
should return \"Not Equal\"');",
+ "assert(myTest(\"bob\") === \"Not Equal\", 'message: myTest(\"bob\")
should return \"Not Equal\"');",
+ "assert(editor.getValue().match(/val\\s*!==\\s*\\d+/g).length > 0, 'message: You should use the !==
operator');"
+ ],
+ "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) {",
+ " if (val != 17) {",
+ " return \"Not Equal\";",
+ " }",
+ " return \"Equal\";",
+ "}"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244d4",
+ "title": "Comparison with the Greater Than Operator",
+ "description": [
+ "The greater than operator (>
) compares the values of two numbers. If the number to the left is greater than the number to the right, it returns true
. If the number on the left is less than or equal to the number on the right, it returns false
. Like the equality operator, greater than converts data types.",
+ "Examples 5 > 3 // true
7 > '3' // true
2 > 3 // false
'1' > 9 // false
",
+ "Instructions
Add the greater than
operator to the indicated lines so that the return statements make sense."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(myTest(0) === \"10 or Under\", 'message: myTest(0)
should return \"10 or Under\"');",
+ "assert(myTest(10) === \"10 or Under\", 'message: myTest(10)
should return \"10 or Under\"');",
+ "assert(myTest(11) === \"Over 10\", 'message: myTest(11)
should return \"Over 10\"');",
+ "assert(myTest(99) === \"Over 10\", 'message: myTest(99)
should return \"Over 10\"');",
+ "assert(myTest(100) === \"Over 10\", 'message: myTest(100)
should return \"Over 10\"');",
+ "assert(myTest(101) === \"Over 100\", 'message: myTest(101)
should return \"Over 100\"');",
+ "assert(myTest(150) === \"Over 100\", 'message: myTest(150)
should return \"Over 100\"');\nassert(editor.getValue().match(/val\\s*>\\s*\\d+/g).length > 1, 'message: You should use the >
operator at least twice');"
+ ],
+ "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) {",
+ " if (val > 100) { // Change this line",
+ " return \"Over 100\";",
+ " }",
+ " if (val > 10) { // Change this line",
+ " return \"Over 10\";",
+ " }",
+ " return \"10 or Under\";",
+ "}"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244d5",
+ "title": "Comparison with the Greater Than Equal To Operator",
+ "description": [
+ "The greater than equal to operator (>=
) compares the values of two numbers. If the number to the left is greater than or equal the number to the right, it returns true
. If the number on the left is less than the number on the right, it returns false
. Like the equality operator, greater than equal to converts data types.",
+ "Examples 6 >= 6 // true
7 >= '3' // true
2 >= 3 // false
'7' >= 9 // false
",
+ "Instructions
Add the greater than equal to
operator to the indicated lines so that the return statements make sense."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(myTest(0) === \"9 or Under\", 'message: myTest(0)
should return \"9 or Under\"');",
+ "assert(myTest(9) === \"9 or Under\", 'message: myTest(9)
should return \"9 or Under\"');",
+ "assert(myTest(10) === \"10 or Over\", 'message: myTest(10)
should return \"10 or Over\"');",
+ "assert(myTest(11) === \"10 or Over\", 'message: myTest(10)
should return \"10 or Over\"');",
+ "assert(myTest(19) === \"10 or Over\", 'message: myTest(19)
should return \"10 or Over\"');",
+ "assert(myTest(20) === \"20 or Over\", 'message: myTest(100)
should return \"20 or Over\"');",
+ "assert(myTest(21) === \"20 or Over\", 'message: myTest(101)
should return \"20 or Over\"');",
+ "assert(editor.getValue().match(/val\\s*>=\\s*\\d+/g).length > 1, 'message: You should use the >=
operator at least twice');"
+ ],
+ "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": [
+ ""
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244d6",
+ "title": "Comparison with the Less Than Operator",
+ "description": [
+ "The less than
operator (<
) compares the values of two numbers. If the number to the left is less than the number to the right, it returns true
. If the number on the left is greater than or equal to the number on the right, it returns false
. Like the equality operator, less than
converts data types.",
+ "Examples 2 < 5 // true
'3' < 7 // true
5 < 5 // false
3 < 2 // false
'8' < 4 // false
",
+ "Instructions
Add the less than
operator to the indicated lines so that the return statements make sense."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(myTest(0) === \"Under 25\", 'message: myTest(0)
should return \"Under 25\"');",
+ "assert(myTest(24) === \"Under 25\", 'message: myTest(24)
should return \"Under 25\"');",
+ "assert(myTest(25) === \"Under 55\", 'message: myTest(25)
should return \"Under 55\"');",
+ "assert(myTest(54) === \"Under 55\", 'message: myTest(54)
should return \"Under 55\"');",
+ "assert(myTest(55) === \"55 or Over\", 'message: myTest(55)
should return \"55 or Over\"');",
+ "assert(myTest(99) === \"55 or Over\", 'message: myTest(99)
should return \"55 or Over\"');",
+ "assert(editor.getValue().match(/val\\s*<\\s*\\d+/g).length > 1, 'message: You should use the <
operator at least twice');"
+ ],
+ "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": [
+ ""
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244d7",
+ "title": "Comparison with the Less Than Equal To Operator",
+ "description": [
+ "The less than equal to
operator (<=
) compares the values of two numbers. If the number to the left is less than or equl the number to the right, it returns true
. If the number on the left is greater than the number on the right, it returns false
. Like the equality operator, less than equal to
converts data types.",
+ "Examples 4 <= 5 // true
'7' <= 7 // true
5 <= 5 // true
3 <= 2 // false
'8' <= 4 // false
",
+ "Instructions
Add the less than equal to
operator to the indicated lines so that the return statements make sense."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(myTest(0) === \"Smaller Than 12\", 'message: myTest(0)
should return \"Smaller Than 12\"');",
+ "assert(myTest(11) === \"Smaller Than 12\", 'message: myTest(11)
should return \"Smaller Than 12\"');",
+ "assert(myTest(12) === \"Smaller Than 24\", 'message: myTest(12)
should return \"Smaller Than 24\"');",
+ "assert(myTest(23) === \"Smaller Than 24\", 'message: myTest(23)
should return \"Smaller Than 24\"');",
+ "assert(myTest(24) === \"25 or More\", 'message: myTest(24)
should return \"24 or More\"');",
+ "assert(myTest(55) === \"25 or More\", 'message: myTest(55)
should return \"24 or More\"');",
+ "assert(editor.getValue().match(/val\\s*<=\\s*\\d+/g).length > 1, 'message: You should use the <=
operator at least twice');"
+ ],
+ "challengeSeed": [
+ "function myTest(val) {",
+ " if (val) { // Change this line",
+ " return \"Smaller Than 12\";",
+ " }",
+ " ",
+ " if (val) { // Change this line",
+ " return \"Smaller Than 24\";",
+ " }",
+ "",
+ " return \"25 or More\";",
+ "}",
+ "",
+ "// Change this value to test",
+ "myTest(10);",
+ ""
+ ],
+ "solutions": [
+ ""
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244d8",
+ "title": "Comparisons with the Logical And Operator",
+ "description": [
+ "Sometimes you will need to test more than one thing at a time. The logical and operator (&&
) returns true
if and only if the operands to the left and right of it are true.",
+ "The same effect could be achieved by nesting an if statement inside another if:",
+ "if (num < 10) {
if (num > 5) {
return \"Yes\";
}
}
return \"No\";
Will only return \"Yes\" if num
is between 6
and 9
. The same logic can be written as:if (num < 10 && num > 5) {
return \"Yes\";
}return \"No\";
",
+ "Instructions
Combine the two if statements into one statement which returns \"Yes\"
if val
is less than or equal to 50
and greater than or equal to 25
. Otherwise, return \"No\"
."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(editor.getValue().match(/&&/g).length === 1, 'message: You should use the &&
operator once');",
+ "assert(editor.getValue().match(/if/g).length === 1, 'message: You should only have one if
statement');",
+ "assert(myTest(0) === \"No\", 'message: myTest(0)
should return \"No\"');",
+ "assert(myTest(24) === \"No\", 'message: myTest(24)
should return \"No\"');",
+ "assert(myTest(25) === \"Yes\", 'message: myTest(25)
should return \"Yes\"');",
+ "assert(myTest(49) === \"Yes\", 'message: myTest(30)
should return \"Yes\"');",
+ "assert(myTest(50) === \"Yes\", 'message: myTest(50)
should return \"Yes\"');",
+ "assert(myTest(51) === \"No\", 'message: myTest(51)
should return \"No\"');",
+ "assert(myTest(75) === \"No\", 'message: myTest(75)
should return \"No\"');",
+ "assert(myTest(51) === \"No\", 'message: myTest(51)
should return \"No\"');"
+ ],
+ "challengeSeed": [
+ "function myTest(val) {",
+ " // Only change code below this line",
+ "",
+ " if (val) {",
+ " if (val) {",
+ " return \"Yes\";",
+ "\t }",
+ " }",
+ "",
+ " // Only change code above this line",
+ " return \"No\";",
+ "}",
+ "",
+ "// Change this value to test",
+ "myTest(10);"
+ ],
+ "solutions": [
+ "function myTest(val) {",
+ " if (val >= 25 && val <= 50) {",
+ " return \"Yes\";",
+ " }",
+ " return \"No\";",
+ "}"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244d9",
+ "title": "Comparisons with the Logical Or Operator",
+ "description": [
+ "The logical or operator (||
) returns true
if either ofoperands is true, or false if neither is true.",
+ "The pattern below should look familiar from prior waypoints:",
+ "if (num > 10) {
return \"No\";
}
if (num < 5) {
return \"No\";
}
return \"Yes\";
Will only return \"Yes\" if num
is between 5
and 10
. The same logic can be written as:if (num > 10 || num < 5) {
return \"No\";
}return \"Yes\";
",
+ "Instructions
Combine the two if statements into one statement which returns \"Inside\"
if val
is between 10
and 20
, inclusive. Otherwise, return \"Outside\"
."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(editor.getValue().match(/\\|\\|/g).length === 1, 'message: You should use the ||
operator once');",
+ "assert(editor.getValue().match(/if/g).length === 1, 'message: You should only have one if
statement');",
+ "assert(myTest(0) === \"Outside\", 'message: myTest(0)
should return \"Outside\"');",
+ "assert(myTest(9) === \"Outside\", 'message: myTest(9)
should return \"Outside\"');",
+ "assert(myTest(10) === \"Inside\", 'message: myTest(10)
should return \"Inside\"');",
+ "assert(myTest(15) === \"Inside\", 'message: myTest(15)
should return \"Inside\"');",
+ "assert(myTest(19) === \"Inside\", 'message: myTest(19)
should return \"Inside\"');",
+ "assert(myTest(20) === \"Inside\", 'message: myTest(20)
should return \"Inside\"');",
+ "assert(myTest(21) === \"Outside\", 'message: myTest(21)
should return \"Outside\"');",
+ "assert(myTest(25) === \"Outside\", 'message: myTest(25)
should return \"Outside\"');"
+ ],
+ "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) {",
+ " if (val < 10 || val > 20) {",
+ " return \"Outside\";",
+ " }",
+ " return \"Inside\";",
+ "}"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "5664820f61c48e80c9fa476c",
+ "title": "Golf Code",
+ "description": [
+ "In the game of golf each hole has a par for the average number of strokes needed to sink the ball. Depending on how far above or below par
your stokes
are, there is a different nickname.",
+ "Your function will be passed a par
and strokes
. Return strings according to this table:",
+ "Stokes | Return |
---|
1 | \"Hole-in-one!\" |
<= par - 2 | \"Eagle\" |
par - 1 | \"Birdie\" |
par | \"Par\" |
par + 1 | \"Bogey\" |
par + 2 | \"Double Bogey\" |
>= par + 3 | \"Go Home!\" |
",
+ "par
and strokes
will always be numeric and positive."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(golfScore(4, 1) === \"Hole-in-one!\", 'message: golfScore(4, 1)
should return \"Hole-in-one!\"');",
+ "assert(golfScore(4, 2) === \"Eagle\", 'message: golfScore(4, 2)
should return \"Eagle\"');",
+ "assert(golfScore(5, 2) === \"Eagle\", 'message: golfScore(4, 2)
should return \"Eagle\"');",
+ "assert(golfScore(4, 3) === \"Birdie\", 'message: golfScore(4, 3)
should return \"Birdie\"');",
+ "assert(golfScore(4, 4) === \"Par\", 'message: golfScore(4, 4)
should return \"Par\"');",
+ "assert(golfScore(5, 5) === \"Par\", 'message: golfScore(5, 5)
should return \"Par\"');",
+ "assert(golfScore(4, 5) === \"Bogey\", 'message: golfScore(4, 5)
should return \"Bogey\"');",
+ "assert(golfScore(4, 6) === \"Double Bogey\", 'message: golfScore(4, 6)
should return \"Double Bogey\"');",
+ "assert(golfScore(4, 7) === \"Go Home!\", 'message: golfScore(4, 7)
should return \"Go Home!\"');",
+ "assert(golfScore(5, 9) === \"Go Home!\", 'message: golfScore(5, 9)
should return \"Go Home!\"');"
+ ],
+ "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) {",
+ " if (strokes === 1) {",
+ " return \"Hole-in-one!\";",
+ " }",
+ " ",
+ " if (strokes <= par - 2) {",
+ " return \"Eagle\";",
+ " }",
+ " ",
+ " if (strokes === par - 1) {",
+ " return \"Birdie\";",
+ " }",
+ " ",
+ " if (strokes === par) {",
+ " return \"Par\";",
+ " }",
+ " ",
+ " if (strokes === par + 1) {",
+ " return \"Bogey\";",
+ " }",
+ " ",
+ " if(strokes === par + 2) {",
+ " return \"Double Bogey\";",
+ " }",
+ " ",
+ " return \"Go Home!\";",
+ "}"
+ ],
+ "type": "bonfire",
+ "challengeType": "5",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244da",
+ "title": "Introducing Else Statements",
+ "description": [
+ "When a condition for an if
statement is true, the block of code following it is executed. What about when that condition is false? Normally nothing would happen. With an else
statement, an alternate block of code can be executed.",
+ "if (num > 10) {
return \"Bigger than 10\";
} else {
return \"10 or Less\";
}
",
+ "Instructions
Combine the if
statements into a single statement."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(editor.getValue().match(/if/g).length === 1, 'message: You should only have one if
statement');",
+ "assert(/else/g.test(editor.getValue()), 'message: You should use an else
statement');",
+ "assert(myTest(4) === \"5 or Smaller\", 'message: myTest(4)
should return \"5 or Smaller\"');",
+ "assert(myTest(5) === \"5 or Smaller\", 'message: myTest(5)
should return \"5 or Smaller\"');",
+ "assert(myTest(6) === \"Bigger than 5\", 'message: myTest(6)
should return \"Bigger than 5\"');",
+ "assert(myTest(10) === \"Bigger than 5\", 'message: myTest(10)
should return \"Bigger than 5\"');",
+ "assert(/var result = \"\";/.test(editor.getValue()) && /return result;/.test(editor.getValue()), 'message: Do not change the code above or below the lines.');"
+ ],
+ "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) {",
+ " var result = \"\";",
+ " if(val > 5) {",
+ " result = \"Bigger than 5\";",
+ " } else {",
+ " result = \"5 or Smaller\";",
+ " }",
+ " return result;",
+ "}"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244db",
+ "title": "Introducing Else If Statements",
+ "description": [
+ "If you have multiple conditions that need to be met, you can chain if
statements together with else if
statements.",
+ "if (num > 15) {
return \"Bigger then 15\";
} else if (num < 5) {
return \"Smaller than 5\";
} else {
return \"Between 5 and 15\";
}
",
+ "InstructionsConvert the logic to use else if
statements."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(editor.getValue().match(/else/g).length > 1, 'message: You should have at least two else
statements');",
+ "assert(editor.getValue().match(/if/g).length > 1, 'message: You should have at least two if
statements');",
+ "assert(myTest(0) === \"Smaller than 5\", 'message: myTest(4)
should return \"Smaller than 5\"');",
+ "assert(myTest(5) === \"Between 5 and 10\", 'message: myTest(5)
should return \"Smaller than 5\"');",
+ "assert(myTest(7) === \"Between 5 and 10\", 'message: myTest(7)
should return \"Between 5 and 10\"');",
+ "assert(myTest(10) === \"Between 5 and 10\", 'message: myTest(10)
should return \"Between 5 and 10\"');",
+ "assert(myTest(12) === \"10 or Bigger\", 'message: myTest(12)
should return \"10 or Bigger\"');"
+ ],
+ "challengeSeed": [
+ "function myTest(val) {",
+ " if(val > 10) {",
+ " return \"10 or Bigger\";",
+ " }",
+ " ",
+ " if(val < 5) {",
+ " return \"Smaller than 5\";",
+ " }",
+ " ",
+ " return \"Between 5 and 10\";",
+ "}",
+ " ",
+ "// Change this value to test",
+ "myTest(7);",
+ ""
+ ],
+ "solutions": [
+ "function myTest(val) {",
+ " if(val > 10) {",
+ " return \"10 or Bigger\";",
+ " } else if(val < 5) {",
+ " return \"Smaller than 5\";",
+ " } else {",
+ " return \"Between 5 and 10\";",
+ " }",
+ "}"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244dc",
+ "title": "Chaining If/Else Statements",
+ "description": [
+ "if...else if
statements can be chained together for complex logic. Here is pseudocode of multiple chained if
/else if
statements:",
+ "if(condition1) {
statement1
} else if (condition1) {
statement1
} else if (condition3) {
statement3
. . .
} else {
statementN
}
",
+ "Instructions
Write chained if
/else if
statements to fulfill the following conditions:",
+ "num < 5
- return \"Tiny\"
num < 10
- return \"Small\"
num < 15
- return \"Medium\"
num < 20
- return \"Large\"
num >= 20
- return \"Huge\""
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(editor.getValue().match(/else/g).length > 3, 'message: You should have at least four else
statements');",
+ "assert(editor.getValue().match(/if/g).length > 3, 'message: You should have at least four if
statements');",
+ "assert(editor.getValue().match(/return/g).length === 5, 'message: You should have five return
statements');",
+ "assert(myTest(0) === \"Tiny\", 'message: myTest(0)
should return \"Tiny\"');",
+ "assert(myTest(4) === \"Tiny\", 'message: myTest(4)
should return \"Tiny\"');",
+ "assert(myTest(5) === \"Small\", 'message: myTest(5)
should return \"Small\"');",
+ "assert(myTest(8) === \"Small\", 'message: myTest(8)
should return \"Small\"');",
+ "assert(myTest(10) === \"Medium\", 'message: myTest(10)
should return \"Medium\"');",
+ "assert(myTest(14) === \"Medium\", 'message: myTest(14)
should return \"Medium\"');",
+ "assert(myTest(15) === \"Large\", 'message: myTest(15)
should return \"Large\"');",
+ "assert(myTest(17) === \"Large\", 'message: myTest(17)
should return \"Large\"');",
+ "assert(myTest(20) === \"Huge\", 'message: myTest(20)
should return \"Huge\"');",
+ "assert(myTest(25) === \"Huge\", 'message: myTest(25)
should return \"Huge\"');"
+ ],
+ "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) {",
+ " if (num < 5) {",
+ " return \"Tiny\";",
+ " } else if (num < 10) {",
+ " return \"Small\";",
+ " } else if (num < 15) {",
+ " return \"Medium\";",
+ " } else if (num < 20) {",
+ " return \"Large\";",
+ " } else {",
+ " return \"Huge\";",
+ " }",
+ "}"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244dd",
+ "title": "Selecting from many options with Switch Statements",
+ "description": [
+ "If you have many options to choose from use a switch
statement A switch
statement tests a value and has many case
statements which define that value can be, shown here in pseudocode:",
+ "switch (num) {
case value1:
statement1
break;
value2:
statement2;
break;
...
valueN:
statementN;
}
",
+ "case
values are tested with strict equality (===
). The break
tells Javascript to stop executing statements. If the break
is omitted, the next statement will be executed.",
+ "Instructions
Write a switch statement to set answer
for the following conditions:
1
- \"alpha\"
2
- \"beta\"
3
- \"gamma\"
4
- \"delta\""
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(myTest(1) === \"alpha\", 'message: myTest(1) should have a value of \"alpha\"');",
+ "assert(myTest(2) === \"beta\", 'message: myTest(2) should have a value of \"beta\"');",
+ "assert(myTest(3) === \"gamma\", 'message: myTest(3) should have a value of \"gamma\"');",
+ "assert(myTest(4) === \"delta\", 'message: myTest(4) should have a value of \"delta\"');",
+ "assert(!/else/g.test(editor.getValue()) || !/if/g.test(editor.getValue()), 'message: You should not use any if
or else
statements');",
+ "assert(editor.getValue().match(/break/g).length > 2, 'message: You should have at least 3 break
statements');"
+ ],
+ "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) {",
+ " var answer = \"\";",
+ "",
+ " switch (val) {",
+ " case 1:",
+ " answer = \"alpha\";",
+ " break;",
+ " case 2:",
+ " answer = \"beta\";",
+ " break;",
+ " case 3:",
+ " answer = \"gamma\";",
+ " break;",
+ " case 4:",
+ " answer = \"delta\";",
+ " }",
+ " return answer; ",
+ "}"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244de",
+ "title": "Adding a default option in Switch statements",
+ "description": [
+ "In a switch
statement you may not be able to specify all possible values as case
statements. Instead, you can use the default
statement where a case
would go. Think of it like an else
statement for switch
.",
+ "A default
statement should be the last \"case
\" in the list.",
+ "switch (num) {
case value1:
statement1
break;
value2:
statement2;
break;
...
default:
defaultStatement;
}
",
+ "Instructions
Write a switch statement to set answer
for the following conditions:
\"a\"
- \"apple\"
\"b\"
- \"bird\"
\"c\"
- \"cat\"
default
- \"stuff\""
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(myTest(\"a\") === \"apple\", 'message: myTest(\"a\") should have a value of \"apple\"');",
+ "assert(myTest(\"b\") === \"bird\", 'message: myTest(\"b\") should have a value of \"bird\"');",
+ "assert(myTest(\"c\") === \"cat\", 'message: myTest(\"c\") should have a value of \"cat\"');",
+ "assert(myTest(\"d\") === \"stuff\", 'message: myTest(\"d\") should have a value of \"stuff\"');",
+ "assert(myTest(4) === \"stuff\", 'message: myTest(4) should have a value of \"stuff\"');",
+ "assert(!/else/g.test(editor.getValue()) || !/if/g.test(editor.getValue()), 'message: You should not use any if
or else
statements');",
+ "assert(editor.getValue().match(/break/g).length > 2, 'message: You should have at least 3 break
statements');"
+ ],
+ "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) {",
+ " var answer = \"\";",
+ "",
+ " switch(val) {",
+ " case \"a\":",
+ " answer = \"apple\";",
+ " break;",
+ " case \"b\":",
+ " answer = \"bird\";",
+ " break;",
+ " case \"c\":",
+ " answer = \"cat\";",
+ " break;",
+ " default:",
+ " answer = \"stuff\";",
+ " }",
+ " return answer; ",
+ "}"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244df",
+ "title": "Multiple Identical Options in Switch Statements",
+ "description": [
+ "If the break
statement is ommitted from a switch
statement case
, the following case
statement(s). If you have mutiple inputs with the same output, you can represent them in a switch
statement like this:",
+ "switch(val) {
case 1:
case 2:
case 3:
result = \"1, 2, or 3\";
break;
case 4:
result = \"4 alone\";
}
",
+ "Cases for 1, 2, and 3 will all produce the same result.",
+ "Instructions
Write a switch statement to set answer
for the following ranges:
1-3
- \"Low\"
4-6
- \"Mid\"
7-9
- \"High\"",
+ "Note
You will need to have a case
statement for each number in the range."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(myTest(1) === \"Low\", 'message: myTest(1)
should return \"Low\"');",
+ "assert(myTest(2) === \"Low\", 'message: myTest(2)
should return \"Low\"');",
+ "assert(myTest(3) === \"Low\", 'message: myTest(3)
should return \"Low\"');",
+ "assert(myTest(4) === \"Mid\", 'message: myTest(4)
should return \"Mid\"');",
+ "assert(myTest(5) === \"Mid\", 'message: myTest(5)
should return \"Mid\"');",
+ "assert(myTest(6) === \"Mid\", 'message: myTest(6)
should return \"Mid\"');",
+ "assert(myTest(7) === \"High\", 'message: myTest(7)
should return \"High\"');",
+ "assert(myTest(8) === \"High\", 'message: myTest(8)
should return \"High\"');",
+ "assert(myTest(9) === \"High\", 'message: myTest(9)
should return \"High\"');",
+ "assert(!/else/g.test(editor.getValue()) || !/if/g.test(editor.getValue()), 'message: You should not use any if
or else
statements');",
+ "assert(editor.getValue().match(/case/g).length === 9, 'message: You should have nine case
statements');"
+ ],
+ "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) {",
+ " var answer = \"\";",
+ " ",
+ " switch (val) {",
+ " case 1:",
+ " case 2:",
+ " case 3:",
+ " answer = \"Low\";",
+ " break;",
+ " case 4:",
+ " case 5:",
+ " case 6:",
+ " answer = \"Mid\";",
+ " break;",
+ " case 7:",
+ " case 8:",
+ " case 9:",
+ " answer = \"High\";",
+ " }",
+ " ",
+ " return answer; ",
+ "}"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244e0",
+ "title": "Replacing If/Else chains with Switch",
+ "description": [
+ "If you have many options to choose from, a switch
statement can be easier to write than many chained if
/if else
statements. The following:",
+ "if(val === 1) {
answer = \"a\";
} else if(val === 2) {
answer = \"b\";
} else {
answer = \"c\";
}
",
+ "can be replaced with:",
+ "switch (val) {
case 1:
answer = \"a\";
break;
case 2:
answer = \"b\";
break;
default:
answer = \"c\";
}
",
+ "Instructions
Change the chained if
/if else
statements into a switch
statement."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(!/else/g.test(editor.getValue()), 'message: You should not use any else
statements');",
+ "assert(!/if/g.test(editor.getValue()), 'message: You should not use any if
statements');",
+ "assert(editor.getValue().match(/break/g).length === 4, 'message: You should have four break
statements');",
+ "assert(myTest(\"bob\") === \"Marley\", 'message: myTest(\"bob\")
should be \"Marley\"');",
+ "assert(myTest(42) === \"The Answer\", 'message: myTest(42)
should be \"The Answer\"');",
+ "assert(myTest(1) === \"There is no #1\", 'message: myTest(1)
should be \"There is no #1\"');",
+ "assert(myTest(99) === \"Missed me by this much!\", 'message: myTest(99)
should be \"Missed me by this much!\"');",
+ "assert(myTest(7) === \"Ate Nine\", 'message: myTest(7)
should be \"Ate Nine\"');"
+ ],
+ "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) {",
+ " var answer = \"\";",
+ "",
+ " switch (val) {",
+ " case \"bob\":",
+ " answer = \"Marley\";",
+ " break;",
+ " case 42:",
+ " answer = \"The Answer\";",
+ " break;",
+ " case 1:",
+ " answer = \"There is no #1\";",
+ " break;",
+ " case 99:",
+ " answer = \"Missed me by this much!\";",
+ " break;",
+ " case 7:",
+ " answer = \"Ate Nine\";",
+ " }",
+ " return answer; ",
+ "}"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "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 Card Counting. ",
+ "Having more high cards remaining in the deck favors the player. Each card is assigned a value according to the table below. When the count is positive, the player should bet high. When the count is zero or negative, the player should bet low.",
+ "Value | Cards |
---|
+1 | 2, 3, 4, 5, 6 |
0 | 7, 8, 9 |
-1 | 10, 'J', 'Q', 'K','A' |
",
+ "You will write a card counting function. It will recieve a card
parameter and increment or decrement the global count
variable according to the card's value (see table). The function will then return the current count and the string \"Bet\"
if the count if positive, or \"Hold\"
if the count is zero or negative.",
+ "Example Output",
+ "-3 Hold
5 Bet
"
+ ],
+ "releasedOn": "11/27/2015",
+ "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 \"5 Bet\"
');",
+ "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 \"0 Hold\"
');",
+ "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 \"-5 Hold\"
');",
+ "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 \"-1 Hold\"
');"
+ ],
+ "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;",
+ "function cc(card) {",
+ " switch(card) {",
+ " case 2:",
+ " case 3:",
+ " case 4:",
+ " case 5:",
+ " case 6:",
+ " count++;",
+ " break;",
+ " case 10:",
+ " case 'J':",
+ " case 'Q':",
+ " case 'K':",
+ " case 'A':",
+ " count--;",
+ " }",
+ " if(count > 0) {",
+ " return count + \" Bet\";",
+ " } else {",
+ " return count + \" Hold\";",
+ " }",
+ "}"
+ ],
+ "type": "bonfire",
+ "challengeType": "5",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
},
{
"id": "bg9998c9c99feddfaeb9bdef",
@@ -861,24 +3215,19 @@
"You may have heard the term object
before.",
"Objects are similar to arrays
, except that instead of using indexes to access and modify their data, you access the data in objects through what are called properties
.",
"Here's a sample object:",
- "var cat = {
",
- " \"name\": \"Whiskers\",
",
- " \"legs\": 4,
",
- " \"tails\": 1,
",
- " \"enemies\": [\"Water\", \"Dogs\"]
",
- "};
",
- "
",
+ "var cat = {
\"name\": \"Whiskers\",
\"legs\": 4,
\"tails\": 1,
\"enemies\": [\"Water\", \"Dogs\"]
};
",
"Objects are useful for storing data in a structured way, and can represent real world objects, like a cat.",
- "Let's try to make an object that represents a dog called myDog
which contains the properties \"name\"
(a string), \"legs\"
, \"tails\"
and \"friends\"
.",
+ "Instructions
Make an object that represents a dog called myDog
which contains the properties \"name\"
(a string), \"legs\"
, \"tails\"
and \"friends\"
.",
"You can set these object properties to whatever values you want, as long \"name\"
is a string, \"legs\"
and \"tails\"
are numbers, and \"friends\"
is an array."
],
"tests": [
- "assert((function(z){if(z.hasOwnProperty(\"name\") && z.name !== undefined && typeof z.name === \"string\"){return true;}else{return false;}})(myDog), 'message: myDog
should contain the property name
and it should be a string
.');",
- "assert((function(z){if(z.hasOwnProperty(\"legs\") && z.legs !== undefined && typeof z.legs === \"number\"){return true;}else{return false;}})(myDog), 'message: myDog
should contain the property legs
and it should be a number
.');",
- "assert((function(z){if(z.hasOwnProperty(\"tails\") && z.tails !== undefined && typeof z.tails === \"number\"){return true;}else{return false;}})(myDog), 'message: myDog
should contain the property tails
and it should be a number
.');",
+ "assert((function(z){if(z.hasOwnProperty(\"name\") && z.name !== undefined && typeof(z.name) === \"string\"){return true;}else{return false;}})(myDog), 'message: myDog
should contain the property name
and it should be a string
.');",
+ "assert((function(z){if(z.hasOwnProperty(\"legs\") && z.legs !== undefined && typeof(z.legs) === \"number\"){return true;}else{return false;}})(myDog), 'message: myDog
should contain the property legs
and it should be a number
.');",
+ "assert((function(z){if(z.hasOwnProperty(\"tails\") && z.tails !== undefined && typeof(z.tails) === \"number\"){return true;}else{return false;}})(myDog), 'message: myDog
should contain the property tails
and it should be a number
.');",
"assert((function(z){if(z.hasOwnProperty(\"friends\") && z.friends !== undefined && Array.isArray(z.friends)){return true;}else{return false;}})(myDog), 'message: myDog
should contain the property friends
and it should be an array
.');"
],
"challengeSeed": [
+ "// Example",
"var ourDog = {",
" \"name\": \"Camper\",",
" \"legs\": 4,",
@@ -893,51 +3242,182 @@
"",
"",
"",
- "};",
- "",
- "// Only change code above this line.",
- "",
+ "};"
+ ],
+ "tail": [
"(function(z){return z;})(myDog);"
],
+ "solutions": [
+ ""
+ ],
"type": "waypoint",
- "challengeType": 1,
- "nameEs": "Construye objetos en JavaScript",
- "descriptionEs": [
- "Es posible que haya oído el término objeto
antes.",
- "Los objetos son similares a los vectores
, excepto que en lugar de utilizar los índices para acceder y modificar sus datos, pueden accederse mediante lo que se llama propiedades
.",
- "Esto es un objeto de ejemplo:",
- "var cat = {
",
- " \"name\": \"Whiskers\",
",
- " \"legs\": 4,
",
- " \"tails\": 1,
",
- " \"enemies\": [\"Water\", \"Dogs\"]
",
- "};
",
- "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 mydog
y contendrá las propiedades \"name\"
(una cadena con el nombre), \"legs\"
(piernas), \"tails\"
(colas) y \"friends\" (amigos)
. ",
- "Podrás establecer estas propiedades del objeto en los valores que desees, siempre y cuando \"name\"
sea una cadena, \"legs\"
y \"tails\"
sean números, y \"friends\"
sea un vector."
- ]
+ "challengeType": "1"
+ },
+ {
+ "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 (.
) and bracket notation ([]
), 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 .
to read an object property:",
+ "var myObj = {
prop1: \"val1\",
prop2: \"val2\"
};
myObj.prop1; // val1
myObj.prop2; // val2
",
+ "Instructions
Read the values of the properties hat
and shirt
of testObj
using dot notation."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(typeof hatValue === 'string' , 'message: hatValue
should be a string');",
+ "assert(hatValue === 'ballcap' , 'message: The value of hatValue
should be \"ballcap\"
');",
+ "assert(typeof shirtValue === 'string' , 'message: shirtValue
should be a string');",
+ "assert(shirtValue === 'jersey' , 'message: The value of shirtValue
should be \"jersey\"
');\nassert(editor.getValue().match(/testObj\\.\\w+/g).length > 1, 'message: You should use dot notation twice');"
+ ],
+ "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 = {",
+ " \"hat\": \"ballcap\",",
+ " \"shirt\": \"jersey\",",
+ " \"shoes\": \"cleats\"",
+ "};",
+ "",
+ "var hatValue = testObj.hat; ",
+ "var shirtValue = testObj.shirt;"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244c8",
+ "title": "Accessing Objects Properties with Bracket Notation",
+ "description": [
+ "The second way to access the properties of an objectis bracket notation ([]
). 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:",
+ "var myObj = {
\"Space Name\": \"Kirk\",
\"More Space\": \"Spock\"
};
myObj[\"Space Name\"]; // Kirk
myObj['More Space']; // Spock
",
+ "Note that property names with spaces in them must be in quotes (single or double).",
+ "Instructions
Read the values of the properties \"an entree\"
and \"the drink\"
of testObj
using bracket notation."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(typeof entreeValue === 'string' , 'message: entreeValue
should be a string');",
+ "assert(entreeValue === 'hamburger' , 'message: The value of entreeValue
should be \"hamburger\"
');",
+ "assert(typeof drinkValue === 'string' , 'message: drinkValue
should be a string');",
+ "assert(drinkValue === 'water' , 'message: The value of drinkValue
should be \"water\"
');",
+ "assert(editor.getValue().match(/testObj\\[('|\")[^'\"]+\\1\\]/g).length > 1, 'message: You should use bracket notation twice');"
+ ],
+ "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 + \"', shirtValue = '\" + b + \"'\"; })(entreeValue,drinkValue);"
+ ],
+ "solutions": [
+ "var testObj = {",
+ " \"an entree\": \"hamburger\",",
+ " \"my side\": \"veggies\",",
+ " \"the drink\": \"water\"",
+ "};",
+ "var entreeValue = testObj[\"an entree\"];",
+ "var drinkValue = testObj['the drink'];"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "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 itterating through lists of object properties or for doing lookups.",
+ "Here is an example of using a variable to access a property:",
+ "var someProp = \"propName\";
var myObj = {
propName: \"Some Value\"
}
myObj[someProp]; // \"Some Value\"
",
+ "Note that we do not use quotes around the variable name when using it to access the property because we are using the value of the variable, not the name",
+ "Instructions
Use the playerNumber
variable to lookup player 16
in testObj
using bracket notation."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(typeof playerNumber === 'number', 'message: playerNumber
should be a number');",
+ "assert(typeof player === 'string', 'message: The variable player
should be a string');",
+ "assert(player === 'Montana', 'message: The value of player
should be \"Montana\"');",
+ "assert(/testObj\\[\\s*playerNumber\\s*\\]/.test(editor.getValue()),'message: You should use bracket notation to access testObj
');"
+ ],
+ "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": [
+ ""
+ ],
+ "solutions": [
+ ""
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
},
{
"id": "bg9999c9c99feddfaeb9bdef",
- "title": "Update the Properties of a JavaScript Object",
+ "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.",
+ "After you've created a JavaScript object, you can update its properties at any time just like you would update any other variable. You can use either dot or bracket notation to update.",
"For example, let's look at ourDog
:",
- "var ourDog = {
",
- " \"name\": \"Camper\",
",
- " \"legs\": 4,
",
- " \"tails\": 1,
",
- " \"friends\": [\"everything!\"]
",
- "};
",
+ "var ourDog = {
\"name\": \"Camper\",
\"legs\": 4,
\"tails\": 1,
\"friends\": [\"everything!\"]
};
",
"Since he's a particularly happy dog, let's change his name to \"Happy Camper\". Here's how we update his object's name property:",
- "ourDog.name = \"Happy Camper\";
",
- "Now when we run return ourDog.name
, instead of getting \"Camper\", we'll get his new name, \"Happy Camper\".",
- "Let's update the myDog
object's name property. Let's change her name from \"Coder\" to \"Happy Coder\"."
+ "ourDog.name = \"Happy Camper\";
or",
+ "outDog[\"name\"] = \"Happy Camper\";
",
+ "Now when we evaluate ourDog.name
, instead of getting \"Camper\", we'll get his new name, \"Happy Camper\".",
+ "Instructions
Update the myDog
object's name property. Let's change her name from \"Coder\" to \"Happy Coder\". You can use either dot or bracket notation."
],
"tests": [
- "assert(/happy coder/gi.test(myDog.name), 'message: Update myDog
's \"name\"
property to equal \"Happy Coder\".');"
+ "assert(/happy coder/gi.test(myDog.name), 'message: Update myDog
's \"name\"
property to equal \"Happy Coder\".');",
+ "assert(/\"name\": \"Coder\"/.test(editor.getValue()), 'message: Do not edit the myDog
definition');"
],
"challengeSeed": [
+ "// Example",
"var ourDog = {",
" \"name\": \"Camper\",",
" \"legs\": 4,",
@@ -947,6 +3427,7 @@
"",
"ourDog.name = \"Happy Camper\";",
"",
+ "// Setup",
"var myDog = {",
" \"name\": \"Coder\",",
" \"legs\": 4,",
@@ -956,44 +3437,32 @@
"",
"// Only change code below this line.",
"",
- "",
- "",
- "// Only change code above this line.",
- "",
+ ""
+ ],
+ "tail": [
"(function(z){return z;})(myDog);"
],
"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 ourDog
:",
- "var ourDog = {
",
- " \"name\": \"Camper\",
",
- " \"legs\": 4,
",
- " \"tails\": 1,
",
- " \"friends\": [\"everything!\"]
",
- "};
",
- "Dado que es un perro particularmente feliz, vamos a cambiar su nombre a \"Happy Camper\". Así es como actualizamos la propiedad nombre del objeto: ",
- "ourDog.name = \"Happy Camper\";
",
- "Ahora, cuando ejecutemos return ourDog.name
, en lugar de obtener \"Camper\", vamos a recibir su nuevo nombre, \"Happy Camper\".",
- "Vamos a actualizar la propiedad del objeto mydog
. Cambiemos su nombre de \"Coder\" a \"Happy Coder\"."
- ]
+ "challengeType": "1"
},
{
"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.",
+ "You can add new properties to existing JavaScript objects the same way you would modify them. ",
"Here's how we would add a \"bark\"
property to ourDog
:",
- "ourDog.bark = \"bow-wow\";
",
- "Now when we run return ourDog.bark
, we'll get his bark, \"bow-wow\".",
- "Let's add a \"bark\"
property to myDog
and set it to a dog sound, such as \"woof\"."
+ "ourDog.bark = \"bow-wow\";
",
+ "or",
+ "ourDog[\"bark\"] = \"bow-wow\";
",
+ "Now when we evaluate ourDog.bark
, we'll get his bark, \"bow-wow\".",
+ "Instructions
Add a \"bark\"
property to myDog
and set it to a dog sound, such as \"woof\". You may use either dot or bracket notation."
],
"tests": [
- "assert(myDog.bark !== undefined, 'message: Add the property \"bark\"
to myDog
.');"
+ "assert(myDog.bark !== undefined, 'message: Add the property \"bark\"
to myDog
.');",
+ "assert(!/bark[^\\n]:/.test(editor.getValue()), 'message: Do not add \"bark\"
to the setup section');"
],
"challengeSeed": [
+ "// Example",
"var ourDog = {",
" \"name\": \"Camper\",",
" \"legs\": 4,",
@@ -1003,6 +3472,7 @@
"",
"ourDog.bark = \"bow-wow\";",
"",
+ "// Setup",
"var myDog = {",
" \"name\": \"Happy Coder\",",
" \"legs\": 4,",
@@ -1011,23 +3481,22 @@
"};",
"",
"// Only change code below this line.",
- "",
- "",
- "",
- "// Only change code above this line.",
- "",
+ ""
+ ],
+ "tail": [
"(function(z){return z;})(myDog);"
],
+ "solutions": [
+ "var myDog = {",
+ " \"name\": \"Happy Coder\",",
+ " \"legs\": 4,",
+ " \"tails\": 1,",
+ " \"friends\": [\"Free Code Camp Campers\"]",
+ "};",
+ "myDog.bark = \"Woof Woof\";"
+ ],
"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 \"bark\"
(ladra) a nuestro objeto ourDog
:",
- "ourDog.bark = \"bow-wow\";
",
- "Ahora, cuando ejecutemos return ourDog.bark
, vamos a recbir su ladrido, \" bow-wow \".",
- "Vamos a añadir una propiedad ladra
a myDog
y a ponerle un sonido de perro, tal como \"woof\"."
- ]
+ "challengeType": "1"
},
{
"id": "bg9999c9c99fdddfaeb9bdef",
@@ -1035,12 +3504,14 @@
"description": [
"We can also delete properties from objects like this:",
"delete ourDog.bark;
",
- "Let's delete the \"tails\"
property from myDog
."
+ "Instructions
Delete the \"tails\"
property from myDog
. You may use either dot or bracket notation."
],
"tests": [
- "assert(myDog.tails === undefined, 'message: Delete the property \"tails\"
from myDog
.');"
+ "assert(myDog.tails === undefined, 'message: Delete the property \"tails\"
from myDog
.');",
+ "assert(editor.getValue().match(/\"tails\": 1/g).length > 1, 'message: Do not modify the myDog
setup');"
],
"challengeSeed": [
+ "// Example",
"var ourDog = {",
" \"name\": \"Camper\",",
" \"legs\": 4,",
@@ -1051,6 +3522,7 @@
"",
"delete ourDog.bark;",
"",
+ "// Setup",
"var myDog = {",
" \"name\": \"Happy Coder\",",
" \"legs\": 4,",
@@ -1061,20 +3533,364 @@
"",
"// Only change code below this line.",
"",
- "",
- "",
- "// Only change code above this line.",
- "",
+ ""
+ ],
+ "tail": [
"(function(z){return z;})(myDog);"
],
+ "solutions": [
+ "// Setup",
+ "var myDog = {",
+ " \"name\": \"Happy Coder\",",
+ " \"legs\": 4,",
+ " \"tails\": 1,",
+ " \"friends\": [\"Free Code Camp Campers\"],",
+ " \"bark\": \"woof\"",
+ "};",
+ "delete myDog.tails;"
+ ],
"type": "waypoint",
- "challengeType": 1,
- "nameEs": "Elimina propiedades de un objeto JavaScript",
- "descriptionEs": [
- "También podemos eliminar propiedades de los objetos de esta manera:",
- "delete ourDog.bark;
",
- "Borremos la propiedad \"tails\"
de myDog
."
- ]
+ "challengeType": "1"
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244ca",
+ "title": "Using Objects for Lookups",
+ "description": [
+ "Objects can be thought of as a key/value storage, like a dictonary. If you have tabular data, you can use an object to \"lookup\" values rather than a switch
statement or an if...else
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:",
+ "var alpha = {
1:\"Z\"
2:\"Y\"
3:\"X\"
...
4:\"W\"
24:\"C\"
25:\"B\"
26:\"A\"
};
alpha[2]; // \"Y\"
alpha[24]; // \"C\"
",
+ "Instructions
Convert the switch statement into a lookup table called lookup
. Use it to lookup val
and return the associated string."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(numberLookup(0) === 'zero', 'message: numberLookup(0)
should equal \"zero\"
');",
+ "assert(numberLookup(1) === 'one', 'message: numberLookup(1)
should equal \"one\"
');",
+ "assert(numberLookup(2) === 'two', 'message: numberLookup(2)
should equal \"two\"
');",
+ "assert(numberLookup(3) === 'three', 'message: numberLookup(3)
should equal \"three\"
');",
+ "assert(numberLookup(4) === 'four', 'message: numberLookup(4)
should equal \"four\"
');",
+ "assert(numberLookup(5) === 'five', 'message: numberLookup(5)
should equal \"five\"
');",
+ "assert(numberLookup(6) === 'six', 'message: numberLookup(6)
should equal \"six\"
');",
+ "assert(numberLookup(7) === 'seven', 'message: numberLookup(7)
should equal \"seven\"
');",
+ "assert(numberLookup(8) === 'eight', 'message: numberLookup(8)
should equal \"eight\"
');",
+ "assert(numberLookup(9) === 'nine', 'message: numberLookup(9)
should equal \"nine\"
');",
+ "assert(!/case|switch|if/g.test(editor.getValue()), 'message: You should not use case
, switch
, or if
statements');"
+ ],
+ "challengeSeed": [
+ "// Setup",
+ "function numberLookup(val) {",
+ " var result = \"\";",
+ "",
+ " // Only change code below this line",
+ " switch(val) {",
+ " case 0: ",
+ " result = \"zero\";",
+ " break;",
+ " case 1: ",
+ " result = \"one\";",
+ " break;",
+ " case 2: ",
+ " result = \"two\";",
+ " break;",
+ " case 3: ",
+ " result = \"three\";",
+ " break;",
+ " case 4: ",
+ " result = \"four\";",
+ " break;",
+ " case 5: ",
+ " result = \"five\";",
+ " break;",
+ " case 6: ",
+ " result = \"six\";",
+ " break;",
+ " case 7: ",
+ " result = \"seven\";",
+ " break;",
+ " case 8: ",
+ " result = \"eight\";",
+ " break;",
+ " case 9: ",
+ " result = \"nine\";",
+ " break;",
+ " }",
+ "",
+ " // Only change code above this line",
+ " return result;",
+ "}",
+ "",
+ ""
+ ],
+ "solutions": [
+ "function numberLookup(val) {",
+ " var result = \"\";",
+ "",
+ " var lookup = {",
+ " 0:\"zero\",",
+ " 1:\"one\",",
+ " 2:\"two\",",
+ " 3:\"three\",",
+ " 4:\"four\",",
+ " 5:\"five\",",
+ " 6:\"six\",",
+ " 7:\"seven\",",
+ " 8:\"eight\",",
+ " 9:\"nine\"",
+ " };",
+ " result = lookup[val];",
+ "",
+ " return result;",
+ "}"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244cb",
+ "title": "Introducing JavaScript Object Notation (JSON)",
+ "description": [
+ "JavaScript Object Notation or JSON
uses the format of Javascript Objects to store data. JSON is flexible becuase it allows for data structures with arbitrary combinations of strings, numbers, booleans, arrays, and objects. ",
+ "Here is an example of a JSON object:",
+ "var ourMusic = [
{
\"artist\": \"Daft Punk\",
\"title\": \"Homework\",
\"release_year\": 1997,
\"formats\": [
\"CD\",
\"Cassette\",
\"LP\" ],
\"gold\": true
}
];
",
+ "This is an array of objects and the object has various peices of metadata about an album. It also has a nested array of formats. Additional album records could be added to the top level array.",
+ "Instructions
Add a new album to the myMusic
JSON object. Add artist
and title
strings, release_year
year, and a formats
array of strings."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(Array.isArray(myMusic), 'message: myMusic
should be an array');",
+ "assert(myMusic.length > 1, 'message: myMusic
should have at least two elements');",
+ "assert(typeof myMusic[1] === 'object', 'message: myMusic[1]
should be an object');",
+ "assert(Object.keys(myMusic[1]).length > 3, 'message: myMusic[1]
should have at least 4 properties');",
+ "assert(myMusic[1].hasOwnProperty('artist') && typeof myMusic[1].artist === 'string', 'message: myMusic[1]
should contain an artist
property which is a string');",
+ "assert(myMusic[1].hasOwnProperty('title') && typeof myMusic[1].title === 'string', 'message: myMusic[1]
should contain a title
property which is a string');",
+ "assert(myMusic[1].hasOwnProperty('release_year') && typeof myMusic[1].release_year === 'number', 'message: myMusic[1]
should contain a release_year
property which is a number');",
+ "assert(myMusic[1].hasOwnProperty('formats') && Array.isArray(myMusic[1].formats), 'message: myMusic[1]
should contain a formats
property which is an array');",
+ "assert(typeof myMusic[1].formats[0] === 'string' && myMusic[1].formats.length > 1, 'message: formats
should be an array of strings with at least two elements');"
+ ],
+ "challengeSeed": [
+ "var myMusic = [",
+ " {",
+ " \t\"artist\": \"Billy Joel\",",
+ " \"title\": \"Piano Man\",",
+ " \"release_year\": 1993,",
+ " \"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 = [",
+ " {",
+ " \t\"artist\": \"Billy Joel\",",
+ " \"title\": \"Piano Man\",",
+ " \"release_year\": 1993,",
+ " \"formats\": [ ",
+ " \"CS\", ",
+ " \"8T\", ",
+ " \"LP\" ],",
+ " \"gold\": true",
+ " }, ",
+ " {",
+ " \"artist\": \"ABBA\",",
+ " \"title\": \"Ring Ring\",",
+ " \"release_year\": 1973,",
+ " \"formats\": [ ",
+ " \"CS\", ",
+ " \"8T\", ",
+ " \"LP\",",
+ "\t \"CD\",",
+ "\t]",
+ " }",
+ "}",
+ " // Add record here",
+ "];"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "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:",
+ "var ourStorage = {
\"desk\": {
\"drawer\": \"stapler\"
},
\"cabinet\": {
\"top drawer\": {
\"folder1\": \"a file\",
\"folder2\": \"secrets\"
},
\"bottom drawer\": \"soda\"
}
}
ourStorage.cabinet[\"top drawer\"].folder2; // \"secrets\"
ourStoage.desk.drawer; // \"stapler\"
",
+ "Instructions
Access the myStorage
JSON object to retrieve the contents of the glove box
. Only use object notation for properties with a space in their name."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(gloveBoxContents === \"maps\", 'message: gloveBoxContents
should equal \"maps\"');",
+ "assert(/=\\s*myStorage\\.car\\.inside\\[([\"'])glove box\\1\\]/.test(editor.getValue()), 'message: Use dot and bracket notation to access myStorage
');"
+ ],
+ "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 gloveBoxContents != 'undefined') { return \"gloveBoxContents = \", x} else return \"gloveBoxContents is undefined\";})(gloveBoxContents);"
+ ],
+ "solutions": [
+ "var myStorage = {",
+ " \"car\": {",
+ " \"inside\": {",
+ " \"glove box\": \"maps\",",
+ " \"passenger seat\": \"crumbs\"",
+ " },",
+ " \"outside\": {",
+ " \"trunk\": \"jack\"",
+ " }",
+ " }",
+ "};",
+ "var gloveBoxContents = myStorage.car.inside['glove box']; // Change this line"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "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:",
+ "var ourPets = {
\"cats\": [
\"Meowzer\",
\"Fluffy\",
\"Kit-Cat\"
],
\"dogs:\" [
\"Spot\",
\"Bowser\",
\"Frankie\"
]
};
ourPets.cats[1]; // \"Fluffy\"
ourPets.dogs[0]; // \"Spot\"
",
+ "Instructions
Retrieve the second tree using object dot and array bracket notation."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(secondTree === \"pine\", 'message: secondTree
should equal \"pine\"');",
+ "assert(/=\\s*myPlants\\[1\\].list\\[1\\]/.test(editor.getValue()), 'message: Use dot and bracket notation to access myPlants
');"
+ ],
+ "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": [
+ ""
+ ],
+ "solutions": [
+ ""
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244ce",
+ "title": "Arbitrary Nesting in JSON",
+ "description": [
+ "Retrieve a value from an arbitary JSON"
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(1===1, 'message: message here');"
+ ],
+ "challengeSeed": [
+ "",
+ "",
+ ""
+ ],
+ "solutions": [
+ ""
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244cf",
+ "title": "Checkpoint: Objects",
+ "description": [
+ ""
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(1===1, 'message: message here');"
+ ],
+ "challengeSeed": [
+ "",
+ "",
+ ""
+ ],
+ "tail": [
+ ""
+ ],
+ "solutions": [
+ ""
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
},
{
"id": "cf1111c1c11feddfaeb5bdef",
@@ -1088,54 +3904,34 @@
"The condition
statement is evaluated at the beginning of every loop iteration and will continue as long as it evalutes to true
. When condition
is false
at the start of the iteration, the loop will stop executing. This means if condition
starts as false
, your loop will never execute.",
"The final-expression
is executed at the end of each loop iteration, prior to the next condition
check and is usually used to increment or decrement your loop counter.",
"In the following example we initialize with i = 0
and iterate while our condition i < 5
is true. We'll increment i
by 1
in each loop iteration with i++
as our final-expression
.",
- "var ourArray = [];
",
- "for (var i = 0; i < 5; i++) {
",
- " ourArray.push(i);
",
- "}
",
+ "var ourArray = [];
for (var i = 0; i < 5; i++) {
ourArray.push(i);
}
",
"ourArray
will now contain [0,1,2,3,4]
.",
- "Let's use a for
loop to work to push the values 1 through 5 onto myArray
."
+ "Instructions
Use a for
loop to work to push the values 1 through 5 onto myArray
."
],
"tests": [
"assert(editor.getValue().match(/for\\s*\\(/g).length > 1, 'message: You should be using a for
loop for this.');",
"assert.deepEqual(myArray, [1,2,3,4,5], 'message: myArray
should equal [1,2,3,4,5]
.');"
],
"challengeSeed": [
+ "// Example",
"var ourArray = [];",
"",
"for (var i = 0; i < 5; i++) {",
" ourArray.push(i);",
"}",
"",
+ "// Setup",
"var myArray = [];",
"",
"// Only change code below this line.",
"",
- "",
- "",
- "// Only change code above this line.",
- "",
- "if(typeof myArray !== \"undefined\"){(function(){return myArray;})();}",
""
],
+ "tail": [
+ "if (typeof(myArray) !== \"undefined\"){(function(){return myArray;})();}"
+ ],
"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:",
- "for ([inicialización]; [condición]; [expresión-final])
",
- "La inicialización
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 condición
se evalúa al principio de cada iteración del ciclo y continuará en el ciclo siempre y cuando sea verdadera (true
). Cuando la condición
sea falsa (false
) al comienzo de la iteración, se detendrá la ejecución del ciclo. Esto significa que si la condición
inicia en el valor falso false
, el ciclo no se ejecutará. ",
- "La expresión final
se ejecuta al final de cada repetición del ciclo, antes del siguiente chequeo de la condición
y se utiliza generalmente para aumentar o disminuir el contador del ciclo.",
- "En el siguiente ejemplo inicializamos con i = 0
e iteramos mientras nuestra condición i <5
sea verdadera. Vamos a incrementar i
en 1
en cada iteración del ciclo con i++
como nuestra expresión final
. ",
- "var ourArray = [];
",
- "for (var i = 0; i < 5; i++) {
",
- " ourArray.push(i);
",
- "}
",
- "ourArray
ahora contendrá [0,1,2,3,4]
.",
- "Vamos a utilizar un ciclo for
para empujar los valores del 1 al 5 en myArray
."
- ]
+ "challengeType": "1"
},
{
"id": "56104e9e514f539506016a5c",
@@ -1143,50 +3939,35 @@
"description": [
"For loops don't have to iterate one at a time. By changing our final-expression
, we can count by even numbers.",
"We'll start at i = 0
and loop while i < 10
. We'll increment i
by 2 each loop with i += 2
.",
- "var ourArray = [];
",
- "for (var i = 0; i < 10; i += 2) {
",
- " ourArray.push(i);
",
- "}
",
+ "var ourArray = [];
for (var i = 0; i < 10; i += 2) {
ourArray.push(i);
}
",
"ourArray
will now contain [0,2,4,6,8]
.",
- "Let's change our initialization
and final-expression
so we can count by odd numbers.",
- "Push the odd numbers from 1 through 9 to myArray
using a for
loop."
+ "Let's change our initialization
so we can count by odd numbers.",
+ "Instructions
Push the odd numbers from 1 through 9 to myArray
using a for
loop."
],
"tests": [
"assert(editor.getValue().match(/for\\s*\\(/g).length > 1, 'message: You should be using a for
loop for this.');",
"assert.deepEqual(myArray, [1,3,5,7,9], 'message: myArray
should equal [1,3,5,7,9]
.');"
],
"challengeSeed": [
+ "// Example",
"var ourArray = [];",
"",
"for (var i = 0; i < 10; i += 2) {",
" ourArray.push(i);",
"}",
"",
+ "// Setup",
"var myArray = [];",
"",
"// Only change code below this line.",
"",
- "",
- "",
- "// Only change code above this line.",
- "",
- "if(typeof myArray !== \"undefined\"){(function(){return myArray;})();}",
""
],
+ "tail": [
+ "if(typeof(myArray) !== \"undefined\"){(function(){return myArray;})();}"
+ ],
"type": "waypoint",
- "challengeType": 1,
- "nameEs": "Itera por los números pares con un ciclo for",
- "descriptionEs": [
- "Los ciclos for
no siempre iteran incrementado de a uno. Cambiando nuestra expresión final
, podemos contar los números pares.",
- "Vamos a empezar con i = 0
e iterar mientras i <10
. Vamos a incrementar i
de a 2 en cada iteración i + = 2
. ",
- "var ourArray = [];
",
- "for (var i = 0; i < 10; i += 2) {
",
- " ourArray.push(i);
",
- "}
",
- "ourArray
ahora contendrá [0,2,4,6,8]
.",
- "Vamos a cambiar nuestra inicialización
y expresión final
para que podamos contar los números impares.",
- "Empuja los números impares del 1 al 9 en myArray
utilizando un ciclo for
."
- ]
+ "challengeType": "1"
},
{
"id": "56105e7b514f539506016a5e",
@@ -1195,50 +3976,115 @@
"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 initialization
, condition
, and final-expression
.",
"We'll start at i = 10
and loop while i > 0
. We'll decrement i
by 2 each loop with i -= 2
.",
- "var ourArray = [];
",
- "for (var i = 10; i > 0; i -= 2) {
",
- " ourArray.push(i);
",
- "}
",
+ "var ourArray = [];
for (var i=10; i > 0; i-=2) {
ourArray.push(i);
}
",
"ourArray
will now contain [10,8,6,4,2]
.",
"Let's change our initialization
and final-expression
so we can count backward by twos by odd numbers.",
- "Push the odd numbers from 9 through 1 to myArray
using a for
loop."
+ "Instructions
Push the odd numbers from 9 through 1 to myArray
using a for
loop."
],
"tests": [
"assert(editor.getValue().match(/for\\s*\\(/g).length > 1, 'message: You should be using a for
loop for this.');",
"assert.deepEqual(myArray, [9,7,5,3,1], 'message: myArray
should equal [9,7,5,3,1]
.');"
],
"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;})();}"
+ ],
+ "type": "waypoint",
+ "challengeType": "1"
+ },
+ {
+ "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 for
loop. This code will output each element of the array arr
to the console:",
+ "var arr = [10,9,8,7,6];
for (var i=0; i < arr.length; i++) {
console.log(arr[i]);
}
",
+ "Remember that Arrays have zero-based numbering, which means the last index of the array is length - 1. Our condition for this loop is i < arr.length
, which stops when i
is at length - 1.",
+ "Instructions
Create a variable total
. Use a for
loop to add each element of myArr
to total."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(total !== 'undefined', 'message: total
should be defined');",
+ "assert(total === 20, 'message: total
should equal 20');",
+ "assert(!/20/.test(editor.getValue()), 'message: Do not set total
to 20 directly');"
+ ],
+ "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(t) { if(typeof t !== 'undefined') { return \"Total = \" + t; } else { return \"Total is undefined\";}})(total);"
+ ],
+ "solutions": [
+ "var myArr = [ 2, 3, 4, 5, 6];",
+ "var total = 0;",
+ "",
+ "for (var i = 0; i < myArr.length; i++) {",
+ " total += myArr[i];",
+ "}"
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
+ },
+ {
+ "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:",
+ "var arr = [
[1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
for (var j=0; k < arr[i].length; j++) {
console.log(arr[i][j]);
}
}
",
+ "This outputs each sub-element in arr
one at a time. Note that for the inner loop we are checking the .length
of arr[i]
, since arr[i]
is itself an array."
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(1===1, 'message: message here');"
+ ],
+ "challengeSeed": [
"",
"",
""
],
"tail": [
- "if(typeof myArray !== \"undefined\"){(function(){return myArray;})();}"
+ ""
+ ],
+ "solutions": [
+ ""
],
"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 inicialización
, la condición
y la última-expresión
.",
- "Vamos a empezar con i = 10
e iteraremos mientras i > 0
. Vamos a decrementar i
de a 2 por cada iteración con i -= 2
. ",
- "var ourArray = [];
",
- "for (var i = 10; i > 0; i -= 2) {
",
- " ourArray.push(i);
",
- "}
",
- "ourArray
ahora contendrá [10,8,6,4,2]
.",
- "Vamos a cambiar nuestra inicialización
y la expresión final
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 myArray
utilizando un ciclo for
."
- ]
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
},
{
"id": "cf1111c1c11feddfaeb1bdef",
@@ -1248,7 +4094,7 @@
"Another type of JavaScript loop is called a \"while loop\", because it runs \"while\" something is true and stops once that something is no longer true.",
"var ourArray = [];
",
"var i = 0;
",
- "while (i < 5) {
",
+ "while(i < 5) {
",
" ourArray.push(i);
",
" i++;
",
"}
",
@@ -1268,36 +4114,49 @@
"",
"// Only change code above this line.",
"",
- "if(typeof myArray !== \"undefined\"){(function(){return myArray;})();}",
+ "if(typeof(myArray) !== \"undefined\"){(function(){return myArray;})();}",
""
],
"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í.",
- "var ourArray = [];
",
- "var i = 0;
",
- "while(i < 5) {
",
- " ourArray.push(i);
",
- " i++;
",
- "}
",
- "Intentemos que un ciclo while
empuje valores en un vector.",
- "Empuja los números de 0 a 4 para myArray
utilizando un ciclo while
."
- ]
+ "challengeType": "1"
+ },
+ {
+ "id": "56533eb9ac21ba0edf2244e2",
+ "title": "Checkpoint: Conditionals and Loops",
+ "description": [
+ ""
+ ],
+ "releasedOn": "11/27/2015",
+ "tests": [
+ "assert(1===1, 'message: message here');"
+ ],
+ "challengeSeed": [
+ "",
+ "",
+ ""
+ ],
+ "solutions": [
+ ""
+ ],
+ "type": "waypoint",
+ "challengeType": "1",
+ "nameCn": "",
+ "nameFr": "",
+ "nameRu": "",
+ "nameEs": "",
+ "namePt": ""
},
{
"id": "cf1111c1c11feddfaeb9bdef",
"title": "Generate Random Fractions with JavaScript",
"description": [
"Random numbers are useful for creating random behavior.",
- "JavaScript has a Math.random()
function that generates a random decimal number between 0 and 1.",
+ "JavaScript has a Math.random()
function that generates a random decimal number.",
"Change myFunction
to return a random number instead of returning 0
.",
"Note that you can return a function, just like you would return a variable or value."
],
"tests": [
- "assert(typeof myFunction() === \"number\", 'message: myFunction
should return a random number.');",
+ "assert(typeof(myFunction()) === \"number\", 'message: myFunction
should return a random number.');",
"assert((myFunction()+''). match(/\\./g), 'message: The number returned by myFunction
should be a decimal.');",
"assert(editor.getValue().match(/Math\\.random/g).length >= 0, 'message: You should be using Math.random
to generate the random decimal number.');"
],
@@ -1314,14 +4173,7 @@
"(function(){return myFunction();})();"
],
"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 Math.random()
que genera un número decimal aleatorio.",
- "Cambia myFunction
para que devuelva un número al azar en lugar de devolver 0
.",
- "Ten en cuenta que puedes retornar lo retornado por una función, igual que harías para devolver una variable o valor."
- ]
+ "challengeType": "1"
},
{
"id": "cf1111c1c12feddfaeb1bdef",
@@ -1339,8 +4191,7 @@
"Let's use this technique to generate and return a random whole number between 0 and 9."
],
"tests": [
- "assert(editor.getValue().match(/var\\srandomNumberBetween0and19\\s=\\sMath.floor\\(Math.random\\(\\)\\s\\*\\s20\\);/).length == 1, 'message: The first line of code should not be changed.');",
- "assert(typeof myFunction() === \"number\" && (function(){var r = myFunction();return Math.floor(r) === r;})(), 'message: The result of myFunction
should be a whole number.');",
+ "assert(typeof(myFunction()) === \"number\" && (function(){var r = myFunction();return Math.floor(r) === r;})(), 'message: The result of myFunction
should be a whole number.');",
"assert(editor.getValue().match(/Math.random/g).length > 1, 'message: You should be using Math.random
to generate a random number.');",
"assert(editor.getValue().match(/\\(\\s*?Math.random\\s*?\\(\\s*?\\)\\s*?\\*\\s*?10\\s*?\\)/g) || editor.getValue().match(/\\(\\s*?10\\s*?\\*\\s*?Math.random\\s*?\\(\\s*?\\)\\s*?\\)/g), 'message: You should have multiplied the result of Math.random
by 10 to make it a number that is between zero and nine.');",
"assert(editor.getValue().match(/Math.floor/g).length > 1, 'message: You should use Math.floor
to remove the decimal part of the number.');"
@@ -1361,20 +4212,7 @@
"(function(){return myFunction();})();"
],
"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 Math.random()
para generar un decimal aleatorio.",
- "Entonces vamos a multiplicar este decimal azar por 20.",
- "Por último, vamos a usar otra función, Math.floor()
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:",
- "Math.floor(Math.random() * 20);
",
- "¿Ves como Math.floor
toma (Math.random() * 20)
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."
- ]
+ "challengeType": "1"
},
{
"id": "cf1111c1c12feddfaeb2bdef",
@@ -1422,70 +4260,7 @@
"(function(){return myFunction();})();"
],
"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 min
y un número máximo max
.",
- "He aquí la fórmula que utilizaremos. Tómate un momento para leer y tratar de entender lo que el código está haciendo: ",
- "Math.floor(Math.random() * (max - min + 1)) + min
",
- "Definir dos variables: myMin
y myMax
, y asignales valores enteros.",
- "A continuación, crea una función llamada myFunction
que devuelva un número aleatorio mayor o igual a myMin
, y menor o igual a myMax
. "
- ]
- },
- {
- "id": "cf1111c1c12feddfaeb3bdef",
- "title": "Use Conditional Logic with If and Else Statements",
- "description": [
- "We can use if
statements in JavaScript to only execute code if a certain condition is met.",
- "if
statements require some sort of boolean condition to evaluate.",
- "For example:",
- "var x = 1;
",
- "if (x === 2) {
",
- " return 'x is 2';
",
- "} else {
",
- " return 'x is not 2';
",
- "}
",
- "Let's use if
and else
statements to make a coin-flip game.",
- "Create if
and else
statements to return the string \"heads\"
if the flip variable is zero, or else return the string \"tails\"
if the flip variable is not zero."
- ],
- "tests": [
- "assert(editor.getValue().match(/if/g).length >= 2, 'message: Create a new if statement.');",
- "assert(editor.getValue().match(/else/g).length >= 1, 'message: Created a new else statement.');",
- "assert((function(){var result = myFunction();if(result === 'heads' || result === 'tails'){return true;} else {return false;}})(), 'message: myFunction
should either return heads
or tails
.');",
- "assert((function(){flip = 0; var result = myFunction(); if(result === 'heads'){return true;} else {return false;}})(), 'message: myFunction
should return heads
when flip equals 0');",
- "assert((function(){flip = 1; var result = myFunction(); if(result === 'tails'){return true;} else {return false;}})(), 'message: myFunction
should return tails
when flip equals 1');"
- ],
- "challengeSeed": [
- "var flip = Math.floor(Math.random() * 2);",
- "",
- "function myFunction() {",
- "",
- " // Only change code below this line.",
- "",
- "",
- "",
- " // Only change code above this line.",
- "",
- "}",
- "",
- "var result = myFunction();if(typeof flip !== \"undefined\" && typeof flip === \"number\" && typeof result !== \"undefined\" && typeof result === \"string\"){(function(y,z){return 'flip = ' + y.toString() + ', text = ' + z;})(flip, result);}"
- ],
- "type": "waypoint",
- "challengeType": 1,
- "nameEs": "Usa lógica condicional con instrucciones if y else",
- "descriptionEs": [
- "Podemos usar instrucciones if
(\"if\" es \"si\" en español) en JavaScript para ejecutar código sólo cuando cierta condición se cumpla.",
- "Las instrucciones if
requieren evaluar algún tipo de condición booleana.",
- "Por ejemplo:",
- "if (1 === 2) {
",
- " return true;
",
- "} else {
",
- " return false;
",
- "}
",
- "Vamos a usar la instrucción if
con else
(\"else\" puede traducirse como \"de lo contrario\") para hacer un juego de cara o sello.",
- "Crea una instrucción if
con else
que retorne la cadena \"heads\"
si la variable flip
es cero, o bien que retorne \"tails\"
si la variable flip
no es cero. "
- ]
+ "challengeType": "1"
},
{
"id": "cf1111c1c12feddfaeb6bdef",
@@ -1502,11 +4277,11 @@
"We can do this by replacing the .
part of our regular expression with the word and
."
],
"tests": [
- "assert(myTest==2, 'message: Your regular expression
should find two occurrences of the word and
.');",
+ "assert(test==2, 'message: Your regular expression
should find two occurrences of the word and
.');",
"assert(editor.getValue().match(/\\/and\\/gi/), 'message: Use regular expressions
to find the word and
in testString
.');"
],
"challengeSeed": [
- "var myTest = (function() {",
+ "var test = (function() {",
" var testString = \"Ada Lovelace and Charles Babbage designed the first computer and the software that would have run on it.\";",
" var expressionToGetSoftware = /software/gi;",
"",
@@ -1517,22 +4292,10 @@
" // Only change code above this line.",
"",
" return testString.match(expression).length;",
- "})();(function(){return myTest;})();"
+ "})();(function(){return test;})();"
],
"type": "waypoint",
- "challengeType": 1,
- "nameEs": "Examina un texto con expresiones regulares",
- "descriptionEs": [
- "Las expresiones regulares
se utilizan para encontrar ciertas palabras o patrones dentro de cadenas
.",
- "Por ejemplo, si quisiéramos encontrar la palabra el
en la cadena El perro persiguió al gato el lunes
, podríamos utilizar la siguiente expresión regular
: /el/gi
",
- "Vamos a dividirla un poco:",
- "el
es el patrón con el que queremos coincidir.",
- "g
significa que queremos buscar el patrón en toda la cadena y no sólo la primera ocurrencia.",
- "i
significa que queremos ignorar la capitalización (en mayúsculas o minúsculas) cuando se busque el patrón.",
- "Las expresiones regulares
se escriben rodeando el patrón con símbolos de barra /
.",
- "Vamos a tratar de seleccionar todas las apariciones de la palabra and
en la cadena Ada Lovelace and Charles Babbage designed the first computer and the software that would have run on it
.",
- "Podemos hacer esto sustituyendo la parte .
de nuestra expresión regular por la palabra and
."
- ]
+ "challengeType": "1"
},
{
"id": "cf1111c1c12feddfaeb7bdef",
@@ -1546,10 +4309,10 @@
],
"tests": [
"assert(editor.getValue().match(/\\/\\\\d\\+\\//g), 'message: Use the /\\d+/g
regular expression to find the numbers in testString
.');",
- "assert(myTest === 2, 'message: Your regular expression should find two numbers in testString
.');"
+ "assert(test === 2, 'message: Your regular expression should find two numbers in testString
.');"
],
"challengeSeed": [
- "var myTest = (function() {",
+ "var test = (function() {",
"",
" var testString = \"There are 3 cats but 4 dogs.\";",
"",
@@ -1561,18 +4324,10 @@
"",
" return testString.match(expression).length;",
"",
- "})();(function(){return myTest;})();"
+ "})();(function(){return test;})();"
],
"type": "waypoint",
- "challengeType": 1,
- "nameEs": "Encuentra números con expresiones regulares",
- "descriptionEs": [
- "Podemos usar selectores especiales en las expresiones regulares
para seleccionar un determinado tipo de valor.",
- "Uno de estos selectores es el de dígitos \\d
que se utiliza para hacer coincidir números en una cadena.",
- "Se usa así para hacer coincidir un dígito: /\\d/g
.",
- "Para hacer coincidir números de varios dígtios a menudo se escribe /\\d+/ g
, donde el +
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 \\d
para hacer coincidir todos los números de la cadena, permitiendo la posibilidad de hacer coincidir números de varios dígitos."
- ]
+ "challengeType": "1"
},
{
"id": "cf1111c1c12feddfaeb8bdef",
@@ -1586,10 +4341,10 @@
],
"tests": [
"assert(editor.getValue().match(/\\/\\\\s\\+\\//g), 'message: Use the /\\s+/g
regular expression to find the spaces in testString
.');",
- "assert(myTest === 7, 'message: Your regular expression should find seven spaces in testString
.');"
+ "assert(test === 7, 'message: Your regular expression should find seven spaces in testString
.');"
],
"challengeSeed": [
- "var myTest = (function(){",
+ "var test = (function(){",
" var testString = \"How many spaces are there in this sentence?\";",
"",
" // Only change code below this line.",
@@ -1600,18 +4355,10 @@
"",
" return testString.match(expression).length;",
"",
- "})();(function(){return myTest;})();"
+ "})();(function(){return test;})();"
],
"type": "waypoint",
- "challengeType": 1,
- "nameEs": "Encuentra espacios en blanco con las expresiones regulares",
- "descriptionEs": [
- "También podemos utilizar selectores de expresiones regulares como \\s
para encontrar un espacio en blanco en una cadena.",
- "Los espacios en blanco son \" \"
(espacio), \\r
(el retorno de carro), \\n
(nueva línea), \\t
(tabulador), y \\f
(el avance de página). ",
- "Una expresión regular con el selector de espacios en blanco puede ser:",
- "/\\s+/g
",
- "Se usa para hacer coincidir todos los espacios en blanco en una cadena."
- ]
+ "challengeType": "1"
},
{
"id": "cf1111c1c13feddfaeb3bdef",
@@ -1623,10 +4370,10 @@
],
"tests": [
"assert(editor.getValue().match(/\\/\\\\S\\/g/g), 'message: Use the /\\S/g
regular expression to find non-space characters in testString
.');",
- "assert(myTest === 49, 'message: Your regular expression should find forty nine non-space characters in the testString
.');"
+ "assert(test === 49, 'message: Your regular expression should find forty nine non-space characters in the testString
.');"
],
"challengeSeed": [
- "var myTest = (function(){",
+ "var test = (function(){",
" var testString = \"How many non-space characters are there in this sentence?\";",
"",
" // Only change code below this line.",
@@ -1636,21 +4383,15 @@
" // Only change code above this line.",
"",
" return testString.match(expression).length;",
- "})();(function(){return myTest;})();"
+ "})();(function(){return test;})();"
],
"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, \\s
coincidirá con cualquier espacio en blanco, mientras que \\S
coincidirá con todo lo que no sea espacio en blanco.",
- "Usa /\\S/g
para contar el número de caracteres que no están en blanco en testString
."
- ]
+ "challengeType": "1"
},
{
"id": "cf1111c1c12feddfaeb9bdef",
"title": "Create a JavaScript Slot Machine",
- "isBeta": true,
+ "isBeta": "true",
"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 1
and 3
to represent the possible values of each individual slot.",
@@ -1659,10 +4400,10 @@
"Math.floor(Math.random() * (3 - 1 + 1)) + 1;
"
],
"tests": [
- "assert(typeof runSlots($(\".slot\"))[0] === \"number\" && runSlots($(\".slot\"))[0] > 0 && runSlots($(\".slot\"))[0] < 4, 'message: slotOne
should be a random number.');",
- "assert(typeof runSlots($(\".slot\"))[1] === \"number\" && runSlots($(\".slot\"))[1] > 0 && runSlots($(\".slot\"))[1] < 4, 'message: slotTwo
should be a random number.');",
- "assert(typeof runSlots($(\".slot\"))[2] === \"number\" && runSlots($(\".slot\"))[2] > 0 && runSlots($(\".slot\"))[2] < 4, 'message: slotThree
should be a random number.');",
- "assert((function(){if(code.match(/Math\\.floor\\(\\s?Math\\.random\\(\\)\\s?\\*\\s?\\(\\s?3\\s?\\-\\s?1\\s?\\+\\s?1\\s?\\)\\s?\\)\\s?\\+\\s?1/gi) !== null){return code.match(/slot.*?=.*?\\(.*?\\).*?/gi).length >= 3;}else{return false;}})(), 'message: You should have used Math.floor(Math.random() * (3 - 1 + 1)) + 1;
three times to generate your random numbers.');"
+ "assert(typeof(runSlots($(\".slot\"))[0]) === \"number\" && runSlots($(\".slot\"))[0] > 0 && runSlots($(\".slot\"))[0] < 4, 'slotOne
should be a random number.')",
+ "assert(typeof(runSlots($(\".slot\"))[1]) === \"number\" && runSlots($(\".slot\"))[1] > 0 && runSlots($(\".slot\"))[1] < 4, 'slotTwo
should be a random number.')",
+ "assert(typeof(runSlots($(\".slot\"))[2]) === \"number\" && runSlots($(\".slot\"))[2] > 0 && runSlots($(\".slot\"))[2] < 4, 'slotThree
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 Math.floor(Math.random() * (3 - 1 + 1)) + 1;
three times to generate your random numbers.')"
],
"challengeSeed": [
"fccss",
@@ -1800,20 +4541,12 @@
""
],
"type": "waypoint",
- "challengeType": 0,
- "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 1
y 3
que representen los valores posibles de cada casilla.",
- "Guarda los tres números aleatorios en slotOne
, slotTwo
y slotThree
.",
- "Genera los números aleatorios utilizando el sistema que usamos anteriormente (puedes encontrar una explicación de la fórmula aquí):",
- "Math.floor(Math.random() * (3 - 1 + 1)) + 1;
"
- ]
+ "challengeType": "0"
},
{
"id": "cf1111c1c13feddfaeb1bdef",
"title": "Add your JavaScript Slot Machine Slots",
- "isBeta": true,
+ "isBeta": "true",
"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 null
.",
@@ -1826,7 +4559,7 @@
"If all three numbers match, we should also set the text \"It's A Win\"
to the element with class logger
."
],
"tests": [
- "assert((function(){var data = runSlots();return data === null || data.toString().length === 1;})(), 'message: If all three of our random numbers are the same we should return that number. Otherwise we should return null
.');"
+ "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 null
.')"
],
"challengeSeed": [
"fccss",
@@ -1968,24 +4701,12 @@
""
],
"type": "waypoint",
- "challengeType": 0,
- "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 null
.",
- "null
es una estructura de datos de JavaScript que significa \"nada\".",
- "El usuario gana cuando los tres números coinciden. Cremos una instrucción if
con varias condiciones, a fin de comprobar si todos los números son iguales. ",
- "if(slotOne === slotTwo && slotTwo === slotThree){
",
- " return null;
",
- "}
",
- "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 \"It's A Win\"
en el elemento HTML con clase logger
."
- ]
+ "challengeType": "0"
},
{
"id": "cf1111c1c13feddfaeb2bdef",
"title": "Bring your JavaScript Slot Machine to Life",
- "isBeta": true,
+ "isBeta": "true",
"description": [
"Now we can detect a win. Let's get this slot machine working.",
"Let's use the jQuery selector
$(\".slot\")
to select all of the slots.",
@@ -1995,8 +4716,8 @@
"Use the above selector to display each number in its corresponding slot."
],
"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;}})(), 'message: You should be displaying the result of the slot numbers in the corresponding slots.');",
- "assert((code.match( /\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[\\d\\]\\s*?\\)/gi) && code.match( /\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[\\d\\]\\s*?\\)/gi ).length >= 3 && code.match( /\\.html\\(slotOne\\)/gi ) && code.match( /\\.html\\(slotTwo\\)/gi ) && code.match( /\\.html\\(slotThree\\)/gi )), 'message: You should have used the the selector given in the description to select each slot and assign it the value of slotOne
, slotTwo
and slotThree
respectively.');"
+ "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 slotOne
, slotTwo
and slotThree
respectively.')"
],
"challengeSeed": [
"fccss",
@@ -2146,21 +4867,12 @@
""
],
"type": "waypoint",
- "challengeType": 0,
- "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 selector
de jQuery $(\".slot\")
para seleccionar todas las casillas.",
- "Una vez que todas estén seleccionados, podemos usar notación de corchetes
para acceder a cada casilla individual:",
- "$($(\".slot\")[0]).html(slotOne);
",
- "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."
- ]
+ "challengeType": "0"
},
{
"id": "cf1111c1c11feddfaeb1bdff",
"title": "Give your JavaScript Slot Machine some Stylish Images",
- "isBeta": true,
+ "isBeta": "true",
"description": [
"Now let's add some images to our slots.",
"We've already set up the images for you in an array called images
. We can use different indexes to grab each of these.",
@@ -2169,13 +4881,13 @@
"Set up all three slots like this, then click the \"Go\" button to play the slot machine."
],
"tests": [
- "assert((code.match(/\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[\\d\\]\\s*?\\)\\.html\\(\\s*?\\'\\
\\'\\s*?\\);/gi) && code.match(/\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[\\d\\]\\s*?\\)\\.html\\(\\s*?\\'\\
\\'\\s*?\\);/gi).length >= 3), 'message: Use the provided code three times. One for each slot.');",
- "assert(code.match(/\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[0\\]\\s*?\\)/gi), 'message: You should have used $('.slot')[0]
at least once.');",
- "assert(code.match(/\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[1\\]\\s*?\\)/gi), 'message: You should have used $('.slot')[1]
at least once.');",
- "assert(code.match(/\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[2\\]\\s*?\\)/gi), 'message: You should have used $('.slot')[2]
at least once.');",
- "assert(code.match(/slotOne/gi) && code.match(/slotOne/gi).length >= 7, 'message: You should have used the slotOne
value at least once.');",
- "assert(code.match(/slotTwo/gi) && code.match(/slotTwo/gi).length >= 8, 'message: You should have used the slotTwo
value at least once.');",
- "assert(code.match(/slotThree/gi) && code.match(/slotThree/gi).length >= 7, 'message: You should have used the slotThree
value at least once.');"
+ "assert((editor.match(/\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[\\d\\]\\s*?\\)\\.html\\(\\s*?\\'\\
\\'\\s*?\\);/gi) && editor.match(/\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[\\d\\]\\s*?\\)\\.html\\(\\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 $('.slot')[0]
at least once.')",
+ "assert(editor.match(/\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[1\\]\\s*?\\)/gi), 'You should have used $('.slot')[1]
at least once.')",
+ "assert(editor.match(/\\$\\s*?\\(\\s*?\\$\\s*?\\(\\s*?(?:'|\")\\s*?\\.slot\\s*?(?:'|\")\\s*?\\)\\[2\\]\\s*?\\)/gi), 'You should have used $('.slot')[2]
at least once.')",
+ "assert(editor.match(/slotOne/gi) && editor.match(/slotOne/gi).length >= 7, 'You should have used the slotOne
value at least once.')",
+ "assert(editor.match(/slotTwo/gi) && editor.match(/slotTwo/gi).length >= 8, 'You should have used the slotTwo
value at least once.')",
+ "assert(editor.match(/slotThree/gi) && editor.match(/slotThree/gi).length >= 7, 'You should have used the slotThree
value at least once.')"
],
"challengeSeed": [
"fccss",
@@ -2329,15 +5041,7 @@
""
],
"type": "waypoint",
- "challengeType": 0,
- "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 images
. 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:",
- "$($('.slot')[0]).html('<img src = \"' + images[slotOne-1] + '\">');
",
- "Configura las tres casillas de manera análoga, a continuación, pulsa el botón \"Go\" para jugar con la máquina tragamonedas."
- ]
+ "challengeType": "0"
}
]
-}
+}
\ No newline at end of file