{ "name": "Basic JavaScript", "time": "10 hours", "order": 1, "helpRoom": "HelpJavaScript", "challenges": [ { "id": "bd7123c9c441eddfaeb4bdef", "title": "Comment Your JavaScript Code", "description": [ "Comments are lines of code that JavaScript will intentionally ignore. Comments are a great way to leave notes to yourself and to other people who will later need to figure out what that code does.", "There are two ways to write comments in JavaScript:", "Using // will tell JavaScript to ignore the remainder of the text on the current line:", "
// This is an in-line comment.
", "You can make a multi-line comment beginning with /* and ending with */:", "
/* This is a
multi-line comment */
", "Best Practice
As you write code, you should regularly add comments to clarify the function of parts of your code. Good commenting can help communicate the intent of your code—both for others and for your future self.", "
", "Try creating one of each type of comment." ], "challengeSeed": [ "" ], "solutions": [ "// Fake Comment\n/* Another Comment */" ], "tests": [ "assert(code.match(/(\\/\\/)...../g), 'message: Create a // style comment that contains at least five letters.');", "assert(code.match(/(\\/\\*)([^\\*\\/]{5,})(?=\\*\\/)/gm), 'message: Create a /* */ style comment that contains at least five letters.');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Agrega comentarios a tu código JavaScript", "description": [ "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." ] }, "fr": { "title": "Commentez votre code JavaScript", "description": [ "Les commentaires sont des lignes de code que Javascript va intentionnellement ignorer. Les commentaires sont un bon moyen de laisser des notes à votre intention ou pour d'autres personnes qui devront comprendre ce que fait votre code.", "Il y a deux façons d'écrire des commentaires en JavaScript.", "Utiliser // indiquera à JavaScript d'ignorer le reste du texte sur cette même ligne:", "// Voici un commentaire sur une ligne.", "Vous pouvez commenter plusieurs lignes en commençant par /* et en finissant par */:", "/*Voici un commentaire
sur plusieurs lignes */
", "Conseils", "Lorsque vous écrivez votre code, vous devriez ajouter régulièrement des commentaires pour clarifier l'objectif de certaines parties de votre code. De bons commentaires peuvent aider les autres et vous-même à mieux comprendre votre code.", "
", "Essayez de créer un commentaire de chaque type." ] } } }, { "id": "bd7123c9c443eddfaeb5bdef", "title": "Declare JavaScript Variables", "description": [ "In computer science, data is anything that is meaningful to the computer. JavaScript provides seven different data types which are undefined, null, boolean, string, symbol, number, and object.", "For example, computers distinguish between numbers, such as the number 12, and strings, such as \"12\", \"dog\", or \"123 cats\", which are collections of characters. Computers can perform mathematical operations on a number, but not on a string.", "Variables allow computers to store and manipulate data in a dynamic fashion. They do this by using a \"label\" to point to the data rather than using the data itself. Any of the seven data types may be stored in a variable.", "Variables are similar to the x and y variables you use in mathematics, which means they're a simple name to represent the data we want to refer to. Computer variables differ from mathematical variables in that they can store different values at different times.", "We tell JavaScript to create or declare a variable by putting the keyword var in front of it, like so:", "
var ourName;
", "creates a variable called ourName. In JavaScript we end statements with semicolons.", "Variable names can be made up of numbers, letters, and $ or _, but may not contain spaces or start with a number.", "
", "Use the var keyword to create a variable called myName.", "Hint
Look at the ourName example if you get stuck." ], "challengeSeed": [ "// Example", "var ourName;", "", "// Define myName below this line", "" ], "tail": [ "if(typeof myName !== \"undefined\"){(function(v){return v;})(myName);}" ], "solutions": [ "var myName;" ], "tests": [ "assert(/var\\s+myName\\s*;/.test(code), 'message: You should declare myName with the var keyword, ending with a semicolon');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Declara variables en JavaScript", "description": [ "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." ] }, "fr": { "title": "Déclarer des variables en JavaScript", "description": [ "En informatique, une donnée comporte tout ce qui peut avoir du sens pour l'ordinateur. Javascript dispose de sept types de données différents qui sont undefined, null, boolean, string, symbol, number et object.", "Par exemple, les ordinateurs font la différence entre les nombres tel que 12 et les strings, tels que \"12\", \"dog\", ou \"123 cats\", qui sont des collections de caractères. Les ordinateurs peuvent faire des opérations mathématiques sur un nombre, mais pas sur une chaîne de caractères.", "Les variables permettent aux ordinateurs de stocker et manipuler les données de façon dynamique. Ils font cela en utilisant un
label
qui réfère à la donnée plutôt que d'utiliser la donnée elle-même. Les sept types de données peuvent être stockés dans une variable.", "Les variables sont similaires aux x et y que vous utilisez en mathématiques, ce qui veut dire que ce sont des noms simples qui représentent les données que l'on veut utiliser. Les variables de l'ordinateur diffèrent de celles des mathématiques car elles peuvent stocker différentes valeurs à différents moments.", "On peut dire à JavaScript de créer ou déclarer une variable en la précédant du mot-clé var, comme ceci:", "var notreNom;", "crée une variable appelée notreNom.On termine nos expressions avec un point virgule en JavaScript.", "Le nom d'une variable peut être composé de nombres, lettres et $ ou _, mais ne peut contenir d'espaces ou commencer par un nombre.", "
", "Utilisez le mot-clé var pour créer une variable appelée monNom", "Conseil
Regardez à l'exemple de notreNom si vous vous êtes bloqué." ] } } }, { "id": "56533eb9ac21ba0edf2244a8", "title": "Storing Values with the Assignment Operator", "description": [ "In JavaScript, you can store a value in a variable with the assignment operator.", "myVariable = 5;", "Assigns the Number 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.", "
", "Assign the value 7 to variable a.", "Assign the contents of a to variable b." ], "releasedOn": "January 1, 2016", "head": [ "if (typeof a != 'undefined') {", " a = undefined;", "}", "if (typeof b != 'undefined') {", " b = undefined;", "}" ], "challengeSeed": [ "// Setup", "var a;", "var b = 2;", "", "// Only change code below this line", "" ], "tail": [ "(function(a,b){return \"a = \" + a + \", b = \" + b;})(a,b);" ], "solutions": [ "var a;\nvar b = 2;\na = 7;\nb = a;" ], "tests": [ "assert(/var a;/.test(code) && /var b = 2;/.test(code), 'message: Do not change code above the line');", "assert(typeof a === 'number' && a === 7, 'message: a should have a value of 7');", "assert(typeof b === 'number' && b === 7, 'message: b should have a value of 7');", "assert(/b\\s*=\\s*a\\s*;/g.test(code), 'message: a should be assigned to b with =');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Almacenar valores con el operador igual", "description": [ "En JavaScript, puedes almacenar un valor en una variable con la asignación o con el operador igual (=).", "miVariable = 5;", "Asigna el valor númerico de 5 a miVariable.", "La asignación siempre va de derecha a izquierda. Todo a la derecha del operador = es resuelto antes que el valor es asignado a la variable a la izquierda del operador.", "
miVar = 5;
miNum = miVar;
", "Asigna 5 a miVar y entonces resuelve miVar a 5 otra vez y asigna esta a miNum.", "

Instrucciones

", "Asigna el valor 7 a la variable a.", "Asigna el contenido de a a la variable b." ] } } }, { "id": "56533eb9ac21ba0edf2244a9", "title": "Initializing Variables with the Assignment Operator", "description": [ "It is common to initialize a variable to an initial value in the same line as it is declared.", "var myVar = 0;", "Creates a new variable called myVar and assigns it an initial value of 0.", "
", "Define a variable a with var and initialize it to a value of 9." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Example", "var ourVar = 19;", "", "// Only change code below this line", "" ], "tail": [ "if(typeof a !== 'undefined') {(function(a){return \"a = \" + a;})(a);} else { (function() {return 'a is undefined';})(); }" ], "solutions": [ "var a = 9;" ], "tests": [ "assert(/var\\s+a\\s*=\\s*9\\s*/.test(code), 'message: Initialize a to a value of 9');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Inicializar variables con el operador igual", "description": [ "Es común inicializar una variable a un valor inicial en la misma línea que es declarada.", "var miVar = 0;", "Crea una nueva variable llamada miVar y le asigna un valor inicial de 0.", "

Instrucciones

", "Define una variable a con var e inicializala a un valor de 9." ] } } }, { "id": "56533eb9ac21ba0edf2244aa", "title": "Understanding Uninitialized Variables", "description": [ "When JavaScript variables are declared, they have an initial 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 concatenate a string with an undefined variable, you will get a literal string of \"undefined\".", "
", "Initialize the three variables a, b, and c with 5, 10, and \"I am a\" respectively so that they will not be undefined." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Initialize these three variables", "var a;", "var b;", "var c;", "", "// Do not change code below this line", "", "a = a + 1;", "b = b + 5;", "c = c + \" String!\";", "" ], "tail": [ "(function(a,b,c){ return \"a = \" + a + \", b = \" + b + \", c = '\" + c + \"'\"; })(a,b,c);" ], "solutions": [ "var a = 5;\nvar b = 10;\nvar c = \"I am a\";\na = a + 1;\nb = b + 5;\nc = c + \" String!\";" ], "tests": [ "assert(typeof a === 'number' && a === 6, 'message: 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(code) && /b = b \\+ 5;/.test(code) && /c = c \\+ \" String!\";/.test(code), 'message: Do not change code below the line');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Entendiendo variables sin inicializar", "description": [ "Cuando las variables de JavaScript son declaradas, ellas tienen un valor inicial de undefined. Si tu haces una operación matematica sobre una variable undefined tu resultado sera NaN el cual significa \"Not a Number\" es decir \"No es un número\". Si tu concatenas una cadena con una variable undefined, vas a obtener una cadena literal de \"undefined\".", "

Instrucciones

", "Inicializa las tres variables a, b, y c con 5, 10, y \"I am a\" respectivamente de manera que no sean undefined." ] } } }, { "id": "56533eb9ac21ba0edf2244ab", "title": "Understanding Case Sensitivity in Variables", "description": [ "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 multiple distinct variables with the same name but different casing. It is strongly recommended that for the sake of clarity, you do not use this language feature.", "

Best Practice

", "Write variable names in Javascript in camelCase. In camelCase, multi-word variable names have the first word in lowercase and the first letter of each subsequent word is capitalized.", "Examples:", "
var someVariable;
var anotherVariableName;
var thisVariableNameIsTooLong;
", "
", "Modify the existing declarations and assignments so their names use camelCase.
Do not create any new variables." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Declarations", "var StUdLyCapVaR;", "var properCamelCase;", "var TitleCaseOver;", "", "// Assignments", "STUDLYCAPVAR = 10;", "PRoperCAmelCAse = \"A String\";", "tITLEcASEoVER = 9000;" ], "solutions": [ "var studlyCapVar;\nvar properCamelCase;\nvar titleCaseOver;\n\nstudlyCapVar = 10;\nproperCamelCase = \"A String\";\ntitleCaseOver = 9000;" ], "tests": [ "assert(typeof studlyCapVar !== 'undefined' && studlyCapVar === 10, 'message: studlyCapVar is defined and has a value of 10');", "assert(typeof properCamelCase !== 'undefined' && properCamelCase === \"A String\", 'message: properCamelCase is defined and has a value of \"A String\"');", "assert(typeof titleCaseOver !== 'undefined' && titleCaseOver === 9000, 'message: titleCaseOver is defined and has a value of 9000');", "assert(code.match(/studlyCapVar/g).length === 2, 'message: studlyCapVar should use camelCase in both declaration and assignment sections.');", "assert(code.match(/properCamelCase/g).length === 2, 'message: properCamelCase should use camelCase in both declaration and assignment sections.');", "assert(code.match(/titleCaseOver/g).length === 2, 'message: titleCaseOver should use camelCase in both declaration and assignment sections.');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Entendiendo la distinción en variables", "description": [ "En JavaScript todas las variables y nombres de funciones distinguen entre mayúsculas y minúsculas. Esto significa que la capitalización importa.", "MIVAR no es lo mismo que MiVar o mivar. Esto hace posible tener múltiples variables distintas con el mismo nombre pero de diferente manera. Es fuertemente recomendado por el bien de la claridad, que tu no uses esta característica del lenguaje.", "

Mejor Práctica

", "Escribe nombres de variables en Javascript en capitalizaciónCamello (camelCase). En capitalizaciónCamello, los nombres de variables con múltiples palabras tienen la primera palabra en minúsculas y la primera letra de cada palabra subsecuente es capitalizada.", "Ejemplos:", "
var algunaVariable;
var otraVariable;
var esteNombreDeVariableEsMuyLargo;
", "

Instrucciones

", "Repara las declaraciones y asignaciones de variables de manera que sus nombres usen capitalizaciónCamello." ] } } }, { "id": "cf1111c1c11feddfaeb3bdef", "title": "Add Two Numbers with JavaScript", "description": [ "Number is a data type in JavaScript which represents numeric data.", "Now let's try to add two numbers using JavaScript.", "JavaScript uses the + symbol as addition operation when placed between two numbers.", "Example", "
myVar = 5 + 10; // assigned 15
", "
", "Change the 0 so that sum will equal 20." ], "challengeSeed": [ "var sum = 10 + 0;", "" ], "tail": [ "(function(z){return 'sum = '+z;})(sum);" ], "solutions": [ "var sum = 10 + 10;" ], "tests": [ "assert(sum === 20, 'message: sum should equal 20');", "assert(/\\+/.test(code), 'message: Use the + operator');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Suma dos números con JavaScript", "description": [ "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." ] } } }, { "id": "cf1111c1c11feddfaeb4bdef", "title": "Subtract One Number from Another with JavaScript", "description": [ "We can also subtract one number from another.", "JavaScript uses the - symbol for subtraction.", "", "Example", "
myVar = 12 - 6; // assigned 6
", "", "
", "Change the 0 so the difference is 12." ], "challengeSeed": [ "var difference = 45 - 0;", "", "" ], "tail": [ "(function(z){return 'difference = '+z;})(difference);" ], "solutions": [ "var difference = 45 - 33;" ], "tests": [ "assert(difference === 12, 'message: Make the variable difference equal 12.');", "assert((code).match(/difference/g).length === 1,'message: Only change the first line');", "assert(/\\d+\\s*-\\s*\\d+/.test(code),'message: Use the - operator');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Resta un número de otro con JavaScript", "description": [ "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." ] } } }, { "id": "cf1231c1c11feddfaeb5bdef", "title": "Multiply Two Numbers with JavaScript", "description": [ "We can also multiply one number by another.", "JavaScript uses the * symbol for multiplication of two numbers.", "", "Example", "
myVar = 13 * 13; // assigned 169
", "", "
", "Change the 0 so that product will equal 80." ], "challengeSeed": [ "var product = 8 * 0;", "", "" ], "tail": [ "(function(z){return 'product = '+z;})(product);" ], "solutions": [ "var product = 8 * 10;" ], "tests": [ "assert(product === 80,'message: Make the variable product equal 80');", "assert(/\\*/.test(code), 'message: Use the * operator');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Multiplica dos números con JavaScript", "description": [ "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." ] } } }, { "id": "cf1111c1c11feddfaeb6bdef", "title": "Divide One Number by Another with JavaScript", "description": [ "We can also divide one number by another.", "JavaScript uses the / symbol for division.", "", "Example", "
myVar = 16 / 2; // assigned 8
", "", "
", "Change the 0 so that the quotient is equal to 2." ], "challengeSeed": [ "var quotient = 66 / 0;", "", "" ], "tail": [ "(function(z){return 'quotient = '+z;})(quotient);" ], "solutions": [ "var quotient = 66 / 33;" ], "tests": [ "assert(quotient === 2, 'message: Make the variable quotient equal to 2.');", "assert(/\\d+\\s*\\/\\s*\\d+/.test(code), 'message: Use the / operator');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Divide un número por otro con JavaScript", "description": [ "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." ] } } }, { "id": "56533eb9ac21ba0edf2244ac", "title": "Increment a Number with JavaScript", "description": [ "You can easily increment or add one to a variable with the ++ operator.", "i++;", "is the equivalent of", "i = i + 1;", "Note
The entire line becomes i++;, eliminating the need for the equal sign.", "
", "Change the code to use the ++ operator on myVar.", "Hint
Learn more about Arithmetic operators - Increment (++)." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "var myVar = 87;", "", "// Only change code below this line", "myVar = myVar + 1;", "" ], "tail": [ "(function(z){return 'myVar = ' + z;})(myVar);" ], "solutions": [ "var myVar = 87;\nmyVar++;" ], "tests": [ "assert(myVar === 88, 'message: myVar should equal 88');", "assert(/myVar\\s*\\=.*myVar/.test(code) === false, 'message: myVar = myVar + 1; should be changed');", "assert(/[+]{2}\\s*myVar|myVar\\s*[+]{2}/.test(code), 'message: Use the ++ operator');", "assert(/var myVar = 87;/.test(code), 'message: Do not change code above the line');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Incrementa un número con JavaScript", "description": [ "Tu puedes fácilmente incrementar o agregar uno a una variable con el operador ++.", "i++", "es el equivalente de", "i = i + 1;", "Nota
Toda la línea equivale a i++, sin necesidad del signo igual.", "

Instrucciones

", "Cambia el código para usar el operador ++ sobre myVar." ] } } }, { "id": "56533eb9ac21ba0edf2244ad", "title": "Decrement a Number with JavaScript", "description": [ "You can easily decrement or decrease a variable by one with the -- operator.", "i--;", "is the equivalent of", "i = i - 1;", "Note
The entire line becomes i--;, eliminating the need for the equal sign.", "
", "Change the code to use the -- operator on myVar." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "var myVar = 11;", "", "// Only change code below this line", "myVar = myVar - 1;", "" ], "tail": [ "(function(z){return 'myVar = ' + z;})(myVar);" ], "solutions": [ "var myVar = 11;\nmyVar--;" ], "tests": [ "assert(myVar === 10, 'message: myVar should equal 10');", "assert(/[-]{2}\\s*myVar|myVar\\s*[-]{2}/.test(code), 'message: Use the -- operator on myVar');", "assert(/var myVar = 11;/.test(code), 'message: Do not change code above the line');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Decrementar un número con JavaScript", "description": [ "Fácilmente puedes decrementar o disminuir una variable por uno con el operador --.", "i--;", "es el equivalente a", "i = i - 1;", "Nota
Toda la línea equivale a i--;, sin necesidad del signo igual.", "

Instrucciones

", "Cambia el código para usar el operador -- en myVar." ] } } }, { "id": "cf1391c1c11feddfaeb4bdef", "title": "Create Decimal Numbers with JavaScript", "description": [ "We can store decimal numbers in variables too. Decimal numbers are sometimes referred to as floating point numbers or floats.", "Note
Not all real numbers can accurately be represented in floating point. This can lead to rounding errors. Details Here.", "
", "Create a variable myDecimal and give it a decimal value with a fractional part (e.g. 5.7)." ], "challengeSeed": [ "var ourDecimal = 5.7;", "", "// Only change code below this line", "", "" ], "tail": [ "(function(){if(typeof myDecimal !== \"undefined\"){return myDecimal;}})();" ], "solutions": [ "var myDecimal = 9.9;" ], "tests": [ "assert(typeof myDecimal === \"number\", 'message: myDecimal should be a number.');", "assert(myDecimal % 1 != 0, 'message: myDecimal should have a decimal point'); " ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Crea números decimales con JavaScript", "description": [ "Podemos almacenar números decimales en variables también. Los números decimales a veces son referidos como números de punto flotante o flotantes.", "Nota
No todos los números reales pueden ser exactamente representados en punto flotante. Esto puede conducir a errores de redondeo. Detalles aquí.", "

Instrucciones

", "Crea una variable myDecimal y dale un valor decimal con una parte fraccional (p.e. 5.7)." ] } } }, { "id": "bd7993c9c69feddfaeb7bdef", "title": "Multiply Two Decimals with JavaScript", "description": [ "In JavaScript, you can also perform calculations with decimal numbers, just like whole numbers.", "Let's multiply two decimals together to get their product.", "
", "Change the 0.0 so that product will equal 5.0." ], "challengeSeed": [ "var product = 2.0 * 0.0;", "", "" ], "tail": [ "(function(y){return 'product = '+y;})(product);" ], "solutions": [ "var product = 2.0 * 2.5;" ], "tests": [ "assert(product === 5.0, 'message: The variable product should equal 5.0.');", "assert(/\\*/.test(code), 'message: You should use the * operator');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Multiplicar dos decimales con JavaScript", "description": [ "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.", "

Instrucciones

", "Cambia el 0.0 para que el producto sea igual a 5.0." ] } } }, { "id": "bd7993c9ca9feddfaeb7bdef", "title": "Divide one Decimal by Another with JavaScript", "description": [ "Now let's divide one decimal by another.", "
", "Change the 0.0 so that quotient will equal to 2.2." ], "challengeSeed": [ "var quotient = 0.0 / 2.0; // Fix this line", "", "" ], "tail": [ "(function(y){return 'quotient = '+y;})(quotient);" ], "solutions": [], "tests": [ "assert(quotient === 2.2, 'message: The variable quotient should equal 2.2');", "assert(/4\\.40*\\s*\\/\\s*2\\.*0*/.test(code), 'message: You should use the / operator to divide 4.4 by 2');", "assert(code.match(/quotient/g).length === 3, 'message: The quotient variable should only be assigned once');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Divide un número decimal por otro con JavaScript", "description": [ "Ahora vamos a dividir un decimal por otro.", "

Instrucciones

", "Cambia el 0.0 para que tu cociente sea igual a 2.2." ] } } }, { "id": "56533eb9ac21ba0edf2244ae", "title": "Finding a Remainder in JavaScript", "description": [ "The remainder operator % gives the remainder of the division of two numbers.", "Example", "
5 % 2 = 1 because
Math.floor(5 / 2) = 2 (Quotient)
2 * 2 = 4
5 - 4 = 1 (Remainder)
", "Usage
In mathematics, a number can be checked to be even or odd by checking the remainder of the division of the number by 2.", "
17 % 2 = 1 (17 is Odd)
48 % 2 = 0 (48 is Even)
", "Note
The remainder operator is sometimes incorrectly referred to as the \"modulus\" operator. It is very similar to modulus, but does not work properly with negative numbers.", "
", "Set remainder equal to the remainder of 11 divided by 3 using the remainder (%) operator." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Only change code below this line", "", "var remainder;", "" ], "tail": [ "(function(y){return 'remainder = '+y;})(remainder);" ], "solutions": [ "var remainder = 11 % 3;" ], "tests": [ "assert(/var\\s+?remainder/.test(code), 'message: The variable remainder should be initialized');", "assert(remainder === 2, 'message: The value of remainder should be 2');", "assert(/\\s+?remainder\\s*?=\\s*?.*%.*;/.test(code), 'message: You should use the % operator');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Encontrar un cociente en JavaScript", "description": [ "El operador residuo % da el residuo de la división de dos números.", "Ejemplo", "
5 % 2 = 1 por que
Math.floor(5 / 2) = 2 (Cociente)
2 * 2 = 4
5 - 4 = 1 (Residuo)
", "Uso
En matemáticas, se puede comprobar si un número es par o impar revisando en residuo de la división del número por 2.", "
17 % 2 = 1 (17 es Impar)
48 % 2 = 0 (48 es Par)
", "Nota
El operador residuo es a veces incorrectamente referenciado como el operador \"módulo\". Este es muy parecido a módulo, pero no trabaja apropiadamente con números negativos.", "

Instrucciones

", "Asigna remainder igual al residuo de 11 dividido por 3 usando el operador residuo (%)." ] } } }, { "id": "56533eb9ac21ba0edf2244af", "title": "Compound Assignment With Augmented Addition", "description": [ "In programming, it is common to use assignments to modify the contents of a variable. Remember that everything to the right of the equals sign is evaluated first, so we can say:", "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 assignment in one step.", "One such operator is the += operator.", "
var myVar = 1;
myVar += 5;
console.log(myVar); // Returns 6
", "
", "Convert the assignments for a, b, and c to use the += operator." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "var a = 3;", "var b = 17;", "var c = 12;", "", "// Only modify code below this line", "", "a = a + 12;", "b = 9 + b;", "c = c + 7;", "" ], "tail": [ "(function(a,b,c){ return \"a = \" + a + \", b = \" + b + \", c = \" + c; })(a,b,c);" ], "solutions": [ "var a = 3;\nvar b = 17;\nvar c = 12;\n\na += 12;\nb += 9;\nc += 7;" ], "tests": [ "assert(a === 15, 'message: a should equal 15');", "assert(b === 26, 'message: b should equal 26');", "assert(c === 19, 'message: c should equal 19');", "assert(code.match(/\\+=/g).length === 3, 'message: You should use the += operator for each variable');", "assert(/var a = 3;/.test(code) && /var b = 17;/.test(code) && /var c = 12;/.test(code), 'message: Do not modify the code above the line');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Asignación con más", "description": [ "En programación, es común usar asignaciones para modificar el contenido de una variable. Recuerda que todo lo de la derecha del signo igual es evaluado primero, así podemos decir que:", "miVar = miVar + 5;", "para agregar 5 a miVar. Dado que este es un patrón común, hay operadores que realizan tanto una operación matemática como una asignación en un paso.", "Uno de tales operadores es el operador +=.", "miVar += 5; añadirá 5 a miVar.", "

Instrucciones

", "Convierte las asignaciones para a, b y c usando el operador +=." ] } } }, { "id": "56533eb9ac21ba0edf2244b0", "title": "Compound Assignment With Augmented Subtraction", "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;", "
", "Convert the assignments for a, b, and c to use the -= operator." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "var a = 11;", "var b = 9;", "var c = 3;", "", "// Only modify code below this line", "", "a = a - 6;", "b = b - 15;", "c = c - 1;", "", "" ], "tail": [ "(function(a,b,c){ return \"a = \" + a + \", b = \" + b + \", c = \" + c; })(a,b,c);" ], "solutions": [ "var a = 11;\nvar b = 9;\nvar c = 3;\n\na -= 6;\nb -= 15;\nc -= 1;\n\n" ], "tests": [ "assert(a === 5, 'message: a should equal 5');", "assert(b === -6, 'message: b should equal -6');", "assert(c === 2, 'message: c should equal 2');", "assert(code.match(/-=/g).length === 3, 'message: You should use the -= operator for each variable');", "assert(/var a = 11;/.test(code) && /var b = 9;/.test(code) && /var c = 3;/.test(code), 'message: Do not modify the code above the line');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Asignación con menos", "description": [ "Al igual que el operador +=, -= substrae un número de una variable.", "miVar = miVar - 5;", "substraerá 5 de miVar. Esto puede ser reescrito como: ", "miVar -= 5;", "

Instrucciones

", "Convierte las asignaciones para a, b, y c para usar el operador -=." ] } } }, { "id": "56533eb9ac21ba0edf2244b1", "title": "Compound Assignment With Augmented Multiplication", "description": [ "The *= operator multiplies a variable by a number.", "myVar = myVar * 5;", "will multiply myVar by 5. This can be rewritten as: ", "myVar *= 5;", "
", "Convert the assignments for a, b, and c to use the *= operator." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "var a = 5;", "var b = 12;", "var c = 4.6;", "", "// Only modify code below this line", "", "a = a * 5;", "b = 3 * b;", "c = c * 10;", "", "" ], "tail": [ "(function(a,b,c){ return \"a = \" + a + \", b = \" + b + \", c = \" + c; })(a,b,c);" ], "solutions": [ "var a = 5;\nvar b = 12;\nvar c = 4.6;\n\na *= 5;\nb *= 3;\nc *= 10;" ], "tests": [ "assert(a === 25, 'message: a should equal 25');", "assert(b === 36, 'message: b should equal 36');", "assert(c === 46, 'message: c should equal 46');", "assert(code.match(/\\*=/g).length === 3, 'message: You should use the *= operator for each variable');", "assert(/var a = 5;/.test(code) && /var b = 12;/.test(code) && /var c = 4\\.6;/.test(code), 'message: Do not modify the code above the line');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Asignación con veces igual", "description": [ "El operador *= multiplica una variable por un número.", "miVar = miVar * 5;", "multiplicará miVar por 5. Esto puede ser reescrito como: ", "miVar *= 5;", "

Instrucciones

", "Convierte las asignaciones para a, b y c usando el operador *=." ] } } }, { "id": "56533eb9ac21ba0edf2244b2", "title": "Compound Assignment With Augmented Division", "description": [ "The /= operator divides a variable by another number.", "myVar = myVar / 5;", "Will divide myVar by 5. This can be rewritten as: ", "myVar /= 5;", "
", "Convert the assignments for a, b, and c to use the /= operator." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "var a = 48;", "var b = 108;", "var c = 33;", "", "// Only modify code below this line", "", "a = a / 12;", "b = b / 4;", "c = c / 11;", "" ], "tail": [ "(function(a,b,c){ return \"a = \" + a + \", b = \" + b + \", c = \" + c; })(a,b,c);" ], "solutions": [ "var a = 48;\nvar b = 108;\nvar c = 33;\n\na /= 12;\nb /= 4;\nc /= 11;" ], "tests": [ "assert(a === 4, 'message: a should equal 4');", "assert(b === 27, 'message: b should equal 27');", "assert(c === 3, 'message: c should equal 3');", "assert(code.match(/\\/=/g).length === 3, 'message: You should use the /= operator for each variable');", "assert(/var a = 48;/.test(code) && /var b = 108;/.test(code) && /var c = 33;/.test(code), 'message: Do not modify the code above the line');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Asignación con división", "description": [ "El operador /= divide una variable por otro número.", "miVar = miVar / 5;", "Dividirá miVar por 5. Esto puede ser reescrito como: ", "miVar /= 5;", "

Instrucciones

", "Convierte las asignaciones para a, b y c para usar el operador /=." ] } } }, { "id": "bd7123c9c444eddfaeb5bdef", "title": "Declare String Variables", "description": [ "Previously we have used the code", "var myName = \"your name\";", "\"your name\" is called a string literal. It is a string because it is a series of zero or more characters enclosed in single or double quotes.", "
", "Create two new string variables: myFirstName and myLastName and assign them the values of your first and last name, respectively." ], "challengeSeed": [ "// Example", "var firstName = \"Alan\";", "var lastName = \"Turing\";", "", "// Only change code below this line", "", "" ], "tail": [ "if(typeof myFirstName !== \"undefined\" && typeof myLastName !== \"undefined\"){(function(){return myFirstName + ', ' + myLastName;})();}" ], "solutions": [ "var myFirstName = \"Alan\";\nvar myLastName = \"Turing\";" ], "tests": [ "assert((function(){if(typeof myFirstName !== \"undefined\" && typeof myFirstName === \"string\" && myFirstName.length > 0){return true;}else{return false;}})(), 'message: 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.');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Declara variables tipo cadena", "description": [ "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." ] } } }, { "id": "56533eb9ac21ba0edf2244b5", "title": "Escaping Literal Quotes in Strings", "description": [ "When you are defining a string you must start and end with a single or double quote. What happens when you need a literal quote: \" or ' inside of your string?", "In JavaScript, you can escape a quote from considering it as an end of string quote by placing a backslash (\\) in front of the quote.", "var sampleStr = \"Alan said, \\\"Peter is learning JavaScript\\\".\";", "This signals to JavaScript that the following quote is not the end of the string, but should instead appear inside the string. So if you were to print this to the console, you would get:", "Alan said, \"Peter is learning JavaScript\".", "
", "Use backslashes to assign a string to the myStr variable so that if you were to print it to the console, you would see:", "I am a \"double quoted\" string inside \"double quotes\"." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "var myStr = \"\"; // Change this line", "", "" ], "tail": [ "(function(){", " if(typeof myStr === 'string') {", " console.log(\"myStr = \\\"\" + myStr + \"\\\"\");", " } else {", " console.log(\"myStr is undefined\");", " }", "})();" ], "solutions": [], "tests": [ "assert(code.match(/\\\\\"/g).length === 6 && code.match(/[^\\\\]\"/g).length === 10, 'message: You should use two double quotes (") and four escaped double quotes (\").');", "assert(myStr === \"I am a \\\"double quoted\\\" string inside \\\"double quotes\\\".\", 'message: Variable myStr should contain the string: I am a \"double quoted\" string inside \"double quotes\".');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Escapar comillas en cadenas de texto", "description": [ "Cuando estás definiendo una cadena debes iniciar y terminar con apóstrofes o comillas. ¿Qué pasa cuando necesitas una comilla: \" o ' dentro de tu cadena?", "En JavaScript, tu puedes escapar unas comillas para diferenciarlas de las comillas del final de la cadena colocando una barra invertida (\\) antes de la cita.", "var cadenaEjem = \"Alan dijo, \\\"Pedro está aprendiendo JavaScript\\\".\";", "Esto le indica a JavaScript que la comilla siguiente no es el fin de la cadena, sino que debe aparecer dentro de la cadena. Así que si fueras a imprimir esto en la consola, tu obtendrías:", "Alan dijo, \"Pedro está aprendiendo JavaScript\".", "

Instructiones

", "Usa barras invertidaspara asigar una cadena a la variable myStr de modo que si tu fueras a imprimirla en la consola, tu verías:", "I am a \"double quoted\" string inside \"double quotes\"." ] } } }, { "id": "56533eb9ac21ba0edf2244b4", "title": "Quoting Strings with Single Quotes", "description": [ "String values in JavaScript may be written with single or double quotes, so long as you start and end with the same type of quote. Unlike some languages, single and double quotes are functionally identical in JavaScript.", "
\"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. Unless they are escaped, you cannot have more than one pair of whichever quote type begins a string.", "If you have a string with many double quotes, this can be difficult to read and write. Instead, use single quotes:", "
'This string has \"double quotes\" in it. And \"probably\" lots of them.'
", "
", "Change the provided string from double to single quotes and remove the escaping. Do not change anything else." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "var myStr = \"Link\";", "", "" ], "tail": [ "(function() { return \"myStr = \" + myStr; })();" ], "solutions": [ "/* head */ 'use strict'; /* solution */ var myStr = 'Link'; /* tail */ (function() { return \"myStr = \" + myStr; })();" ], "tests": [ "assert(!/\\\\/g.test(code) && myStr.match('\\\\s*\\\\s*Link\\\\s*\\\\s*'), 'message: Remove all the backslashes (\\)');", "assert(code.match(/\"/g).length === 6 && code.match(/'/g).length === 4, 'message: You should have two single quotes ' and four double quotes "');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Citando cadenas con comillas simples", "description": [ "Los valores de Cadenas en JavaScript pueden ser escritos con comillas o apóstrofes, siempre y cuando inicien y terminen con el mismo tipo de cita. A diferencia de algunos lenguajes, apóstrofes y comillas son funcionalmente identicas en JavaScript.", "\"Esta cadena tiene \\\"comillas\\\" en esta\"", "La ventaja de usar una o la otra tiene que ver con la necesidad de escapar comillas. Si tu tienes una cadena con algunas comillas, esta puede ser difícil de leer y escribir. En su lugar, usa apóstrofes:", "'Esta cadena tiene \"comillas\" en esta. Y \"probablemente\" muchas de ellas.'", "

Instrucciones

", "Cambia la cadena dada de comillas a apóstrofes y quita el escape." ] } } }, { "id": "56533eb9ac21ba0edf2244b6", "title": "Escape Sequences in Strings", "description": [ "Quotes are not the only characters that can be escaped inside a string. There are two reasons to use escaping characters: First is to allow you to use characters you might not otherwise be able to type out, such as a backspace. Second is to allow you to represent multiple quotes in a string without JavaScript misinterpreting what you mean. We learned this in the previous challenge.", "
CodeOutput
\\'single quote
\\\"double quote
\\\\backslash
\\nnewline
\\rcarriage return
\\ttab
\\bbackspace
\\fform feed
", "Note that the backslash itself must be escaped in order to display as a backslash.", "
", "Assign the following three lines of text into the single variable myStr using escape sequences.", "
FirstLine
    \\SecondLine
ThirdLine
", "You will need to use escape sequences to insert special characters correctly. You will also need to follow the spacing as it looks above, with no spaces between escape sequences or words.", "Here is the text with the escape sequences written out.", "FirstLinenewlinetabbackslashSecondLinenewlineThirdLine" ], "releasedOn": "January 1, 2016", "challengeSeed": [ "var myStr; // Change this line", "", "" ], "tail": [ "(function(){", "if (myStr !== undefined){", "console.log('myStr:\\n' + myStr);}})();" ], "solutions": [ "var myStr = \"FirstLine\\n\\t\\\\SecondLine\\nThirdLine\";" ], "tests": [ "assert(!/ /.test(myStr), 'message: myStr should not contain any spaces');", "assert(/FirstLine/.test(myStr) && /SecondLine/.test(myStr) && /ThirdLine/.test(myStr), 'message: myStr should contain the strings FirstLine, SecondLine and ThirdLine (remember case sensitivity)');", "assert(/FirstLine\\n/.test(myStr), 'message: FirstLine should be followed by the newline character \\n');", "assert(/\\n\\t/.test(myStr), 'message: myStr should contain a tab character \\t which follows a newline character');", "assert(/\\SecondLine/.test(myStr), 'message: SecondLine should be preceded by the backslash character \\\\');", "assert(/SecondLine\\nThirdLine/.test(myStr), 'message: There should be a newline character between SecondLine and ThirdLine');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Secuencias de escape en cadenas", "description": [ "Las comillas no son el único caracter que puede ser escapado dentro de una cadena. Aquí ahí una tabla de secuencias de escape comunes:", "
CódigoSalida
\\'apostrofe
\\\"comilla
\\\\barra invertida
\\nnueva línea
\\rretorno de carro
\\ttabulación
\\bretroceso
\\fsalto de página
", "Nota que la barra invertida por si misma tiene que ser escapada con el fin de mostrarse como una barra invertida.", "

Instrucciones

", "Codifica la siguiente secuencia, separada por espacios:
FirstLinenueva líneatabulaciónbarra invertidaSecondLinenueva líneaThirdLine" ] } } }, { "id": "56533eb9ac21ba0edf2244b7", "title": "Concatenating Strings with Plus Operator", "description": [ "In JavaScript, when the + operator is used with a String value, it is called the concatenation operator. You can build a new string out of other strings by concatenating them together.", "Example", "
'My name is Alan,' + ' I concatenate.'
", "Note
Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.", "
", "Build myStr from the strings \"This is the start. \" and \"This is the end.\" using the + operator." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Example", "var ourStr = \"I come first. \" + \"I come second.\";", "", "// Only change code below this line", "", "var myStr;", "", "" ], "tail": [ "(function(){", " if(typeof myStr === 'string') {", " return 'myStr = \"' + myStr + '\"';", " } else {", " return 'myStr is not a string';", " }", "})();" ], "solutions": [ "var ourStr = \"I come first. \" + \"I come second.\";\nvar myStr = \"This is the start. \" + \"This is the end.\";" ], "tests": [ "assert(myStr === \"This is the start. This is the end.\", 'message: myStr should have a value of This is the start. This is the end.');", "assert(code.match(/([\"']).*([\"'])\\s*\\+\\s*([\"']).*([\"'])/g).length > 1, 'message: Use the + operator to build myStr');", "assert(/var\\s+myStr/.test(code), 'message: myStr should be created using the var keyword.');", "assert(/myStr\\s*=/.test(code), 'message: Make sure to assign the result to the myStr variable.');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Concatenar cadenas con el operador más", "description": [ "En JavaScript, cuando el operador + es usado con un valor de Cadena, este es llamado el operador concatenación. Tu puedes construir una nueva cadena de otras cadenas concatenandolas juntas.", "Ejemplo", "
'Mi nombre es Alan,' + ' Yo concateno.'
", "Nota
Cuidado con los espacios. La concatenación no agrega espacios entre cadenas concatenadas, así que necesitarás agregarlos tu mismo.", "

Instrucciones

", "Construye myStr con las cadenas \"This is the start. \" y \"This is the end.\" usando el operador+." ] } } }, { "id": "56533eb9ac21ba0edf2244b8", "title": "Concatenating Strings with the Plus Equals Operator", "description": [ "We can also use the += operator to concatenate a string onto the end of an existing string variable. This can be very helpful to break a long string over several lines.", "Note
Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.", "
", "Build myStr over several lines by concatenating these two strings:
\"This is the first sentence. \" and \"This is the second sentence.\" using the += operator." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Example", "var ourStr = \"I come first. \";", "ourStr += \"I come second.\";", "", "// Only change code below this line", "", "var myStr;", "", "" ], "tail": [ "(function(){", " if(typeof myStr === 'string') {", " return 'myStr = \"' + myStr + '\"';", " } else {", " return 'myStr is not a string';", " }", "})();" ], "solutions": [ "var ourStr = \"I come first. \";\nourStr += \"I come second.\";\n\nvar myStr = \"This is the first sentence. \";\nmyStr += \"This is the second sentence.\";" ], "tests": [ "assert(myStr === \"This is the first sentence. This is the second sentence.\", 'message: myStr should have a value of This is the first sentence. This is the second sentence.');", "assert(code.match(/\\w\\s*\\+=\\s*[\"']/g).length > 1 && code.match(/\\w\\s*\\=\\s*[\"']/g).length > 1, 'message: Use the += operator to build myStr');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Concatenar cadenas con el operador mas igual", "description": [ "Nosotros también podemos usar el operador += para concatenar una cadena al final de una variable de cadena existente. Esto puede ser muy útil para romper una cadena larga sobre varias líneas.", "Nota
Cuidado con los espacios. La concatenación no agrega espacios entre cadenas concatenadas, así que necesitarás añadirlos tu mismo.", "

Instrucciones

", "Construye myStr sobre varias líneas concatenando estas dos cadenas:
\"This is the first sentence. \" y \"This is the second sentence.\" usando el operador +=." ] } } }, { "id": "56533eb9ac21ba0edf2244b9", "title": "Constructing Strings with Variables", "description": [ "Sometimes you will need to build a string, Mad Libs style. By using the concatenation operator (+), you can insert one or more variables into a string you're building.", "
", "Set myName to a string equal to your name and build myStr with myName between the strings \"My name is \" and \" and I am well!\"" ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Example", "var ourName = \"freeCodeCamp\";", "var ourStr = \"Hello, our name is \" + ourName + \", how are you?\";", "", "// Only change code below this line", "var myName;", "var myStr;", "", "" ], "tail": [ "(function(){", " var output = [];", " if(typeof myName === 'string') {", " output.push('myName = \"' + myName + '\"');", " } else {", " output.push('myName is not a string');", " }", " if(typeof myStr === 'string') {", " output.push('myStr = \"' + myStr + '\"');", " } else {", " output.push('myStr is not a string');", " }", " return output.join('\\n');", "})();" ], "solutions": [ "var myName = \"Bob\";\nvar myStr = \"My name is \" + myName + \" and I am well!\";" ], "tests": [ "assert(typeof myName !== 'undefined' && myName.length > 2, 'message: myName should be set to a string at least 3 characters long');", "assert(code.match(/[\"']\\s*\\+\\s*myName\\s*\\+\\s*[\"']/g).length > 0, 'message: Use two + operators to build myStr with myName inside it');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Construir cadenas con variables", "description": [ "A veces necesitarás construir una cadena, al estilo Mad Libs. Mediante el uso del operador concatenación (+), puedes insertar una o más variables dentro de una cadena que estés construyendo.", "

Instrucciones

", "Asigna myName a una cadena igual a tu nombre y construye myStr con myName entre las cadenas \"My name is \" and \" and I am well!\"" ] } } }, { "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.", "
", "Set someAdjective and append it to myStr using the += operator." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Example", "var anAdjective = \"awesome!\";", "var ourStr = \"freeCodeCamp is \";", "ourStr += anAdjective;", "", "// Only change code below this line", "", "var someAdjective;", "var myStr = \"Learning to code is \";", "" ], "tail": [ "(function(){", " var output = [];", " if(typeof someAdjective === 'string') {", " output.push('someAdjective = \"' + someAdjective + '\"');", " } else {", " output.push('someAdjective is not a string');", " }", " if(typeof myStr === 'string') {", " output.push('myStr = \"' + myStr + '\"');", " } else {", " output.push('myStr is not a string');", " }", " return output.join('\\n');", "})();" ], "solutions": [ "var anAdjective = \"awesome!\";\nvar ourStr = \"freeCodeCamp is \";\nourStr += anAdjective;\n\nvar someAdjective = \"neat\";\nvar myStr = \"Learning to code is \";\nmyStr += someAdjective;" ], "tests": [ "assert(typeof someAdjective !== 'undefined' && someAdjective.length > 2, 'message: someAdjective should be set to a string at least 3 characters long');", "assert(code.match(/myStr\\s*\\+=\\s*someAdjective\\s*/).length > 0, 'message: Append someAdjective to myStr using the += operator');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Anexando variables a cadenas", "description": [ "Al igual que podemos construir una cadena en múltiples líneas a partir de cadenas literales, nosotros podemos ademas anexar variables a una cadena usando el operador más igual (+=).", "

Instructiones

", "Asigna someAdjective y anexalo a myStr usando el operador +=." ] } } }, { "id": "bd7123c9c448eddfaeb5bdef", "title": "Find the Length of a String", "description": [ "You can find the length of a String value by writing .length after the string variable or string literal.", "\"Alan Peter\".length; // 10", "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 and assign it to lastNameLength." ], "challengeSeed": [ "// Example", "var firstNameLength = 0;", "var firstName = \"Ada\";", "", "firstNameLength = firstName.length;", "", "// Setup", "var lastNameLength = 0;", "var lastName = \"Lovelace\";", "", "// Only change code below this line.", "", "lastNameLength = lastName;", "", "" ], "tail": [ "if(typeof lastNameLength !== \"undefined\"){(function(){return lastNameLength;})();}" ], "solutions": [ "var firstNameLength = 0;\nvar firstName = \"Ada\";\nfirstNameLength = firstName.length;\n\nvar lastNameLength = 0;\nvar lastName = \"Lovelace\";\nlastNameLength = lastName.length;" ], "tests": [ "assert((function(){if(typeof lastNameLength !== \"undefined\" && typeof lastNameLength === \"number\" && lastNameLength === 8){return true;}else{return false;}})(), 'message: lastNameLength should be equal to eight.');", "assert((function(){if(code.match(/\\.length/gi) && code.match(/\\.length/gi).length >= 2 && code.match(/var lastNameLength \\= 0;/gi) && code.match(/var lastNameLength \\= 0;/gi).length >= 1){return true;}else{return false;}})(), 'message: You should be getting the length of lastName by using .length like this: lastName.length.');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Comprueba la propiedad longitud (length) de una variable tipo cadena", "description": [ "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." ] } } }, { "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.", "Most modern programming languages, like JavaScript, don't start counting at 1 like humans do. They start at 0. This is referred 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].", "
", "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." ], "challengeSeed": [ "// Example", "var firstLetterOfFirstName = \"\";", "var firstName = \"Ada\";", "", "firstLetterOfFirstName = firstName[0];", "", "// Setup", "var firstLetterOfLastName = \"\";", "var lastName = \"Lovelace\";", "", "// Only change code below this line", "firstLetterOfLastName = lastName;", "", "" ], "tail": [ "(function(v){return v;})(firstLetterOfLastName);" ], "solutions": [ "var firstLetterOfLastName = \"\";\nvar lastName = \"Lovelace\";\n\n// Only change code below this line\nfirstLetterOfLastName = lastName[0];" ], "tests": [ "assert(firstLetterOfLastName === 'L', 'message: The firstLetterOfLastName variable should have the value of L.');", "assert(code.match(/firstLetterOfLastName\\s*?=\\s*?lastName\\[.*?\\]/), 'message: You should use bracket notation.');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Usa la notación de corchetes para encontrar el primer carácter de una cadena", "description": [ "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." ] } } }, { "id": "56533eb9ac21ba0edf2244ba", "title": "Understand String Immutability", "description": [ "In JavaScript, String values are immutable, which means that they cannot be altered once created.", "For example, the following code:", "
var myStr = \"Bob\";
myStr[0] = \"J\";
", "cannot change the value of myStr to \"Job\", because the contents of myStr cannot be altered. Note that this does not mean that myStr cannot be changed, just that the individual characters of a string literal cannot be changed. The only way to change myStr would be to assign it with a new string, like this:", "
var myStr = \"Bob\";
myStr = \"Job\";
", "
", "Correct the assignment to myStr so it contains the string value of Hello World using the approach shown in the example above." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Setup", "var myStr = \"Jello World\";", "", "// Only change code below this line", "", "myStr[0] = \"H\"; // Fix Me", "", "" ], "tail": [ "(function(v){return \"myStr = \" + v;})(myStr);" ], "solutions": [ "var myStr = \"Jello World\";\nmyStr = \"Hello World\";" ], "tests": [ "assert(myStr === \"Hello World\", 'message: myStr should have a value of Hello World');", "assert(/myStr = \"Jello World\"/.test(code), 'message: Do not change the code above the line');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Comprender la inmutabilidad de cadenas", "description": [ "En JavaScript, los valores de las Cadenas son inmutables, lo cual significa que ellos no pueden ser alterados una vez creados.", "Por ejemplo, el siguiente código:", "
var miCad = \"Bob\";
myCad[0] = \"J\";
", "no puede cambiar el valor de miCad a \"Job\" porque el contenido de miCad no puede ser alterado. Nota que esto no significa que miCad no puede ser cambiado, solo que los valores individuales de una cadena literal no pueden ser cambiados. La única manera de cambiar miCad sería asignandola a una nueva cadena, como esta:", "
var miCad = \"Bob\";
miCad = \"Job\";
", "

Instrucciones

", "Corrige la asignación de myStr para lograr el efecto deseado." ] } } }, { "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.", "
", "Let's try to set thirdLetterOfLastName to equal the third letter of the lastName variable using bracket notation.", "Hint
Try looking at the secondLetterOfFirstName variable declaration if you get stuck." ], "challengeSeed": [ "// Example", "var firstName = \"Ada\";", "var secondLetterOfFirstName = firstName[1];", "", "// Setup", "var lastName = \"Lovelace\";", "", "// Only change code below this line.", "var thirdLetterOfLastName = lastName;", "", "" ], "tail": [ "(function(v){return v;})(thirdLetterOfLastName);" ], "solutions": [ "var lastName = \"Lovelace\";\nvar thirdLetterOfLastName = lastName[2];" ], "tests": [ "assert(thirdLetterOfLastName === 'v', 'message: The thirdLetterOfLastName variable should have the value of v.');", "assert(code.match(/thirdLetterOfLastName\\s*?=\\s*?lastName\\[.*?\\]/), 'message: You should use bracket notation.');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Usar la notación de corchetes para encontrar el n-ésimo caracter en una cadena", "description": [ "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.", "

Instrucciones

", "Vamos a tratar de asignar a thirdLetterOfLastName la tercera letra de la variable lastName.", "Pista
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.", "Hint
Try looking at the lastLetterOfFirstName variable declaration if you get stuck." ], "challengeSeed": [ "// Example", "var firstName = \"Ada\";", "var lastLetterOfFirstName = firstName[firstName.length - 1];", "", "// Setup", "var lastName = \"Lovelace\";", "", "// Only change code below this line.", "var lastLetterOfLastName = lastName;", "", "" ], "tail": [ "(function(v){return v;})(lastLetterOfLastName);" ], "solutions": [ "var firstName = \"Ada\";\nvar lastLetterOfFirstName = firstName[firstName.length - 1];\n\nvar lastName = \"Lovelace\";\nvar lastLetterOfLastName = lastName[lastName.length - 1];" ], "tests": [ "assert(lastLetterOfLastName === \"e\", 'message: lastLetterOfLastName should be \"e\".');", "assert(code.match(/\\.length/g).length === 2, 'message: You have to use .length to get the last letter.');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Usa notación de corchetes para encontrar el último caracter de una cadena", "description": [ "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]. ", "

Instrucciones

", "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.", "Hint
Try looking at the thirdToLastLetterOfFirstName variable declaration if you get stuck." ], "challengeSeed": [ "// Example", "var firstName = \"Ada\";", "var thirdToLastLetterOfFirstName = firstName[firstName.length - 3];", "", "// Setup", "var lastName = \"Lovelace\";", "", "// Only change code below this line", "var secondToLastLetterOfLastName = lastName;", "", "" ], "tail": [ "(function(v){return v;})(secondToLastLetterOfLastName);" ], "solutions": [ "var firstName = \"Ada\";\nvar thirdToLastLetterOfFirstName = firstName[firstName.length - 3];\n\nvar lastName = \"Lovelace\";\nvar secondToLastLetterOfLastName = lastName[lastName.length - 2];" ], "tests": [ "assert(secondToLastLetterOfLastName === 'c', 'message: secondToLastLetterOfLastName should be \"c\".');", "assert(code.match(/\\.length/g).length === 2, 'message: You have to use .length to get the second last letter.');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Usa notación de corchetes para encontrar el n-ésimo último caracter de una cadena", "description": [ "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] ", "

Instrucciones

", "Usa notación de corchete para encontrar el segundo último caracter de la cadena en lastName.", "Pista
Si te atascas intenta mirando la declaración de la variable thirdToLastLetterOfFirstName." ] } } }, { "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\". You will create an (optionally humorous) \"Fill in the Blanks\" style sentence. Here's an example of an incomplete sentence.", "\"The ______ ______ looked around ______ then ______ into the house\"", "These four blanks would be filled in this order: (adjective) (noun) (adverb) (verb)", "You will need to use string concatenation to build a new string, result, using the variables myNoun, myAdjective, myVerb, and myAdverb. These variables are passed to the function as parameters. Don't change these parameter names in the function.", "Include additional strings and spaces (which will not change) in between the provided variables to make a complete sentence." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) {", " var result = \"\";", " // Your code below this line", " ", "", " // Your code above this line", " return result;", "}", "", "// Change the words here to test your function", "wordBlanks(\"dog\", \"big\", \"ran\", \"quickly\");" ], "tail": [ "var test1 = wordBlanks(\"dog\", \"big\", \"ran\", \"quickly\");", "var test2 = wordBlanks(\"cat\", \"little\", \"hit\", \"slowly\");" ], "solutions": [ "function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) {\n var result = \"\";\n\n result = \"Once there was a \" + myNoun + \" which was very \" + myAdjective + \". \";\n result += \"It \" + myVerb + \" \" + myAdverb + \" around the yard.\";\n\n return result;\n}" ], "tests": [ "assert(typeof wordBlanks(\"\",\"\",\"\",\"\") === 'string', 'message: wordBlanks(\"\",\"\",\"\",\"\") should return a string.');", "assert(/\\bdog\\b/.test(test1) && /\\bbig\\b/.test(test1) && /\\bran\\b/.test(test1) && /\\bquickly\\b/.test(test1),'message: wordBlanks(\"dog\", \"big\", \"ran\", \"quickly\") should contain all of the passed in words separated by non-word characters (and any additional words in your madlib).');", "assert(/\\bcat\\b/.test(test2) && /\\blittle\\b/.test(test2) && /\\bhit\\b/.test(test2) && /\\bslowly\\b/.test(test2),'message: wordBlanks(\"cat\", \"little\", \"hit\", \"slowly\") should contain all of the passed in words separated by non-word characters (and any additional words in your madlib).');" ], "type": "checkpoint", "challengeType": 1, "translations": { "es": { "title": "Espacios en blanco de palabras", "description": [ "Ahora usaremos nuestro conocimiento de cadenas para construir un juego de palabras estilo \"Mad Libs\" que llamaremos \"Espacios en Blanco de Palabras\". Vas a crear unas oraciones estilo (opcionalmente graciosa) \"Llena los espacios en blanco\".", "Necesitarás usar operadores de cadenas para construir una nueva cadena result, usando las variables previstas: myNoun, myAdjective, myVerb y myAdverb.", "Además, necesitarás proporcionar cadenas adicionales, las cuales no cambiarán entre las palabras proporcionadas.", "Nosotros hemos proporcionado un marco de referencia para probar tus resultados con diferentes palabras. La prueba correrá tu función con varias palabras diferentes para asegurarse que todas las palabras proporcionadas aparezcan en la salida, así como en tus cadenas adicionales." ] } } }, { "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\"].", "
", "Modify the new array myArray so that it contains both a string and a number (in that order).", "Hint
Refer to the example code in the text editor if you get stuck." ], "challengeSeed": [ "// Example", "var ourArray = [\"John\", 23];", "", "// Only change code below this line.", "var myArray = [];", "" ], "tail": [ "(function(z){return z;})(myArray);" ], "solutions": [ "var myArray = [\"The Answer\", 42];" ], "tests": [ "assert(typeof myArray == 'object', 'message: 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.');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Almacena múltiples valores en una variable utilizando vectores en JavaScript", "description": [ "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\"]. ", "

Instrucciones

", "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." ] } } }, { "id": "cf1111c1c11feddfaeb7bdef", "title": "Nest one Array within Another Array", "description": [ "You can also nest arrays within other arrays, like this: [[\"Bulls\", 23], [\"White Sox\", 45]]. This is also called a Multi-dimensional Array.", "
", "Create a nested array called myArray." ], "challengeSeed": [ "// Example", "var ourArray = [[\"the universe\", 42], [\"everything\", 101010]];", "", "// Only change code below this line.", "var myArray = [];", "" ], "tail": [ "if(typeof myArray !== \"undefined\"){(function(){return myArray;})();}" ], "solutions": [ "var myArray = [[1,2,3]];" ], "tests": [ "assert(Array.isArray(myArray) && myArray.some(Array.isArray), 'message: myArray should have at least one array nested within another array.');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Anida un vector dentro de otro vector", "description": [ "También puedes anidar vectores dentro de otros vectores, como este: [[\"Bulls\", 23], [\"White Sox\", 45]].", "

Instrucciones

", "Ahora vamos a crear un vector anidado llamado myArray." ] } } }, { "id": "56bbb991ad1ed5201cd392ca", "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. Like strings, arrays use zero-based indexing, so the first element in an array is element 0.", "Example", "
var array = [1,2,3];
array[0]; // equals 1
var data = array[1]; // equals 2
", "Note
There shouldn't be any spaces between the array name and the square brackets, like array [0]. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.", "
", "Create a variable called myData and set it to equal the first value of myArray using bracket notation." ], "challengeSeed": [ "// Example", "var ourArray = [1,2,3];", "var ourData = ourArray[0]; // equals 1", "", "// Setup", "var myArray = [1,2,3];", "", "// Only change code below this line.", "" ], "tail": [ "if(typeof myArray !== \"undefined\" && typeof myData !== \"undefined\"){(function(y,z){return 'myArray = ' + JSON.stringify(y) + ', myData = ' + JSON.stringify(z);})(myArray, myData);}" ], "solutions": [ "var myArray = [1,2,3];\nvar myData = myArray[0];" ], "tests": [ "assert((function(){if(typeof myArray !== 'undefined' && typeof myData !== 'undefined' && myArray[0] === myData){return true;}else{return false;}})(), 'message: The variable myData should equal the first value of myArray.');", "assert((function(){if(code.match(/\\s*=\\s*myArray\\[0\\]/g)){return true;}else{return false;}})(), 'message: The data in variable myArray should be accessed using bracket notation.');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Accede a los datos de un vector mediante índices", "description": [ "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];", "

Instrucciones

", "Crea una variable llamada myData y asignale el primer valor del vector myArray." ] } } }, { "id": "cf1111c1c11feddfaeb8bdef", "title": "Modify Array Data With Indexes", "description": [ "Unlike strings, the entries of arrays are mutable and can be changed freely.", "Example", "
var ourArray = [3,2,1];
ourArray[0] = 1; // equals [1,2,1]
", "Note
There shouldn't be any spaces between the array name and the square brackets, like array [0]. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.", "
", "Modify the data stored at index 0 of myArray to a value of 3." ], "challengeSeed": [ "// Example", "var ourArray = [1,2,3];", "ourArray[1] = 3; // ourArray now equals [1,3,3].", "", "// Setup", "var myArray = [1,2,3];", "", "// Only change code below this line.", "", "" ], "tail": [ "if(typeof myArray !== \"undefined\"){(function(){return myArray;})();}" ], "solutions": [ "var myArray = [1,2,3];\nmyArray[0] = 3;" ], "tests": [ "assert((function(){if(typeof myArray != 'undefined' && myArray[0] == 3 && myArray[1] == 2 && myArray[2] == 3){return true;}else{return false;}})(), 'message: myArray should now be [3,2,3].');", "assert((function(){if(code.match(/myArray\\[0\\]\\s*=\\s*/g)){return true;}else{return false;}})(), 'message: You should be using correct index to modify the value in myArray.');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Modifica datos de un vector usando índices", "description": [ "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]", "

Instrucciones

", "Ahora establece el dato almacenado en el índice 0 de myArray para que sea el valor 3." ] } } }, { "id": "56592a60ddddeae28f7aa8e1", "title": "Access Multi-Dimensional Arrays With Indexes", "description": [ "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 brackets refers to the entries in the outer-most (the first level) array, and each additional pair of brackets refers to the next level of entries inside.", "Example", "
var arr = [
[1,2,3],
[4,5,6],
[7,8,9],
[[10,11,12], 13, 14]
];
arr[3]; // equals [[10,11,12], 13, 14]
arr[3][0]; // equals [10,11,12]
arr[3][0][1]; // equals 11
", "Note
There shouldn't be any spaces between the array name and the square brackets, like array [0][0] and even this array [0] [0] is not allowed. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.", "
", "Using bracket notation select an element from myArray such that myData is equal to 8." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Setup", "var myArray = [[1,2,3], [4,5,6], [7,8,9], [[10,11,12], 13, 14]];", "", "// Only change code below this line.", "var myData = myArray[0][0];", "" ], "tail": [ "if(typeof myArray !== \"undefined\"){(function(){return \"myData: \" + myData + \" myArray: \" + JSON.stringify(myArray);})();}" ], "solutions": [ "var myArray = [[1,2,3],[4,5,6], [7,8,9], [[10,11,12], 13, 14]];\nvar myData = myArray[2][1];" ], "tests": [ "assert(myData === 8, 'message: myData should be equal to 8.');", "assert(/myArray\\[2\\]\\[1\\]/g.test(code) && !/myData\\s*=\\s*(?:.*[-+*/%]|\\d)/g.test(code), 'message: You should be using bracket notation to read the correct value from myArray.');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Acceder a vectores multi-dimensionales con índices", "description": [ "Una manera de pensar un vector multi-dimensional, es como un vector de vectores. Cuando usas corchetes para acceder a tu vector, el primer conjunto de brackets se refiere a las entradas en el vector más externo y cada nivel subsecuente de brackets se refiere al siguiente nivel de vectores internos.", "Ejemplo", "
var vec = [
[1,2,3],
[4,5,6],
[7,8,9],
[[10,11,12], 13, 14]
];
vec[0]; // es igual [1,2,3]
vec[1][2]; // es igual 6
vec[3][0][1]; // es igual 11
", "

Instrucciones

", "Lee de myArray usando la notación corchete de modo que myData sea igual a 8" ] } } }, { "id": "56bbb991ad1ed5201cd392cb", "title": "Manipulate Arrays With push()", "description": [ "An easy way to append data to the end of an array is via the push() function.", ".push() takes one or more parameters and \"pushes\" them onto the end of the array.", "
var arr = [1,2,3];
arr.push(4);
// arr is now [1,2,3,4]
", "
", "Push [\"dog\", 3] onto the end of the myArray variable." ], "challengeSeed": [ "// Example", "var ourArray = [\"Stimpson\", \"J\", \"cat\"];", "ourArray.push([\"happy\", \"joy\"]); ", "// ourArray now equals [\"Stimpson\", \"J\", \"cat\", [\"happy\", \"joy\"]]", "", "// Setup", "var myArray = [[\"John\", 23], [\"cat\", 2]];", "", "// Only change code below this line.", "", "" ], "tail": [ "(function(z){return 'myArray = ' + JSON.stringify(z);})(myArray);" ], "solutions": [ "var myArray = [[\"John\", 23], [\"cat\", 2]];\nmyArray.push([\"dog\",3]);" ], "tests": [ "assert((function(d){if(d[2] != undefined && d[0][0] == 'John' && d[0][1] === 23 && d[2][0] == 'dog' && d[2][1] === 3 && d[2].length == 2){return true;}else{return false;}})(myArray), 'message: myArray should now equal [[\"John\", 23], [\"cat\", 2], [\"dog\", 3]].');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Manipula vectores con push()", "description": [ "No sólo se pueden sacar datos del final de un vector con pop(), también puedes empujar (push()) datos al final del vector.", "

Instrucciones

", "Empuja [\"dog\", 3] al final de la variable myArray." ] } } }, { "id": "56bbb991ad1ed5201cd392cc", "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\" value by assigning it to a variable. In other words, .pop() removes the last element from an array and returns that element.", "Any type of entry can be \"popped\" off of an array - numbers, strings, even nested arrays.", "
var threeArr = [1, 4, 6];
var oneDown = threeArr.pop();
console.log(oneDown); // Returns 6
console.log(threeArr); // Returns [1, 4]
", "
", "Use the .pop() function to remove the last item from myArray, assigning the \"popped off\" value to removedFromMyArray." ], "challengeSeed": [ "// Example", "var ourArray = [1,2,3];", "var removedFromOurArray = ourArray.pop(); ", "// removedFromOurArray now equals 3, and ourArray now equals [1,2]", "", "// Setup", "var myArray = [[\"John\", 23], [\"cat\", 2]];", "", "// Only change code below this line.", "var removedFromMyArray;", "", "" ], "tail": [ "(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);" ], "solutions": [ "var myArray = [[\"John\", 23], [\"cat\", 2]];\nvar removedFromMyArray = myArray.pop();" ], "tests": [ "assert((function(d){if(d[0][0] == 'John' && d[0][1] === 23 && d[1] == undefined){return true;}else{return false;}})(myArray), 'message: myArray should only contain [[\"John\", 23]].');", "assert(/removedFromMyArray\\s*=\\s*myArray\\s*.\\s*pop\\s*(\\s*)/.test(code), 'message: Use pop() on myArray');", "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].');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Manipula vectores con pop()", "description": [ "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.", "

Instrucciones

", "Usa la función .pop() para sacar el último elemento de myArray y asigna ese valor \"sacado\" a removedFromMyArray ." ] } } }, { "id": "56bbb991ad1ed5201cd392cd", "title": "Manipulate Arrays With shift()", "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." ], "challengeSeed": [ "// Example", "var ourArray = [\"Stimpson\", \"J\", [\"cat\"]];", "removedFromOurArray = ourArray.shift();", "// removedFromOurArray now equals \"Stimpson\" and ourArray now equals [\"J\", [\"cat\"]].", "", "// Setup", "var myArray = [[\"John\", 23], [\"dog\", 3]];", "", "// Only change code below this line.", "var removedFromMyArray;", "", "" ], "tail": [ "(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);" ], "solutions": [ "var myArray = [[\"John\", 23], [\"dog\", 3]];\n\n// Only change code below this line.\nvar removedFromMyArray = myArray.shift();" ], "tests": [ "assert((function(d){if(d[0][0] == 'dog' && d[0][1] === 3 && d[1] == undefined){return true;}else{return false;}})(myArray), 'message: 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].');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Manipula vectores con shift()", "description": [ "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. ", "

Instrucciones

", "Usa la función .shift() para eliminar el primer elemento de myArray, y el elemento que saques asignalo a removedFromMyArra" ] } } }, { "id": "56bbb991ad1ed5201cd392ce", "title": "Manipulate Arrays With unshift()", "description": [ "Not only can you shift elements off of the beginning of an array, you can also unshift elements to the beginning of an array i.e. add elements in front of the 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\",35] to the beginning of the myArray variable using unshift()." ], "challengeSeed": [ "// Example", "var ourArray = [\"Stimpson\", \"J\", \"cat\"];", "ourArray.shift(); // ourArray now equals [\"J\", \"cat\"]", "ourArray.unshift(\"Happy\"); ", "// ourArray now equals [\"Happy\", \"J\", \"cat\"]", "", "// Setup", "var myArray = [[\"John\", 23], [\"dog\", 3]];", "myArray.shift();", "", "// Only change code below this line.", "", "" ], "tail": [ "(function(y, z){return 'myArray = ' + JSON.stringify(y);})(myArray);" ], "solutions": [ "var myArray = [[\"John\", 23], [\"dog\", 3]];\nmyArray.shift();\nmyArray.unshift([\"Paul\", 35]);" ], "tests": [ "assert((function(d){if(typeof d[0] === \"object\" && d[0][0] == '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]].');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Manipula vectores con unshift()", "description": [ "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. ", "

Instrucciones

", "Añade \"Paul\" al comienzo de la variable myArray usando unshift()." ] } } }, { "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 i.e.", "[\"Chocolate Bar\", 15]", "There should be at least 5 sub-arrays in the list." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "var myList = [];", "", "" ], "tail": [ "var count = 0;", "var isArray = false;", "var hasString = false;", "var hasNumber = false;", "(function(list){", " if(Array.isArray(myList)) {", " isArray = true;", " if(myList.length > 0) {", " hasString = true;", " hasNumber = true;", " myList.forEach(function(elem) {", " if(typeof elem[0] !== 'string') {", " hasString = false;", " }", " if(typeof elem[1] !== 'number') {", " hasNumber = false;", " }", " });", " }", " count = myList.length;", " return JSON.stringify(myList);", " } else {", " return \"myList is not an array\";", " }", "", "})(myList);" ], "solutions": [ "var myList = [\n [\"Candy\", 10],\n [\"Potatoes\", 12],\n [\"Eggs\", 12],\n [\"Catfood\", 1],\n [\"Toads\", 9]\n];" ], "tests": [ "assert(isArray, 'message: 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');" ], "type": "checkpoint", "challengeType": 1, "translations": { "es": { "title": "Lista de compras", "description": [ "Crea una lista de compras en la variable myList. La lista tiene que ser un vector multidimensional conteniendo varios sub-vectores.", "El primer elemento en cada sub-vector debe contener una cadena con el nombre del elemento. El segundo elemento debe ser un número representando la cantidad i. e.", "[\"Barra de Chocolate\", 15]", "Tiene que haber por lo menos 5 sub-vectores en la lista." ] } } }, { "id": "56bbb991ad1ed5201cd392cf", "title": "Write Reusable JavaScript with Functions", "description": [ "In JavaScript, we can divide up our code into reusable parts called functions.", "Here's an example of a function:", "
function functionName() {
console.log(\"Hello World\");
}
", "You can call or invoke this function by using its name followed by parentheses, 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.", "
", "
  1. Create a function called reusableFunction which prints \"Hi World\" to the dev console.
  2. Call the function.
" ], "head": [ "var logOutput = \"\";", "var originalConsole = console", "function capture() {", " var nativeLog = console.log;", " console.log = function (message) {", " if(message && message.trim) logOutput = message.trim();", " if(nativeLog.apply) {", " nativeLog.apply(originalConsole, arguments);", " } else {", " var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');", " nativeLog(nativeMsg);", " }", " };", "}", "", "function uncapture() {", " console.log = originalConsole.log;", "}", "", "capture();" ], "challengeSeed": [ "// Example", "function ourReusableFunction() {", " console.log(\"Heyya, World\");", "}", "", "ourReusableFunction();", "", "// Only change code below this line", "" ], "tail": [ "uncapture();", "", "if (typeof reusableFunction !== \"function\") { ", " (function() { return \"reusableFunction is not defined\"; })();", "} else {", " (function() { return logOutput || \"console.log never called\"; })();", "}" ], "solutions": [ "function reusableFunction() {\n console.log(\"Hi World\");\n}\nreusableFunction();" ], "tests": [ "assert(typeof reusableFunction === 'function', 'message: reusableFunction should be a function');", "assert(\"Hi World\" === logOutput, 'message: reusableFunction should output \"Hi World\" to the dev console');", "assert(/^\\s*reusableFunction\\(\\)\\s*;/m.test(code), 'message: Call reusableFunction after you define it');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Escribe código JavaScript reutilizable con funciones", "description": [ "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). ", "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." ] } } }, { "id": "56533eb9ac21ba0edf2244bd", "title": "Passing Values to Functions with Arguments", "description": [ "Parameters are variables that act as placeholders for the values that are to be input to a function when it is called. When a function is defined, it is typically defined along with one or more parameters. The actual values that are input (or \"passed\") into a function when it is called are known as arguments.", "Here is a function with two parameters, param1 and param2:", "
function testFun(param1, param2) {
console.log(param1, param2);
}
", "Then we can call testFun:", "testFun(\"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 testFun again with different arguments and the parameters would take on the value of the new arguments.", "
", "
  1. Create a function called functionWithArgs that accepts two arguments and outputs their sum to the dev console.
  2. Call the function with two numbers as arguments.
" ], "releasedOn": "January 1, 2016", "head": [ "var logOutput = \"\";", "var originalConsole = console", "function capture() {", " var nativeLog = console.log;", " console.log = function (message) {", " if(message) logOutput = JSON.stringify(message).trim();", " if(nativeLog.apply) {", " nativeLog.apply(originalConsole, arguments);", " } else {", " var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');", " nativeLog(nativeMsg);", " }", " };", "}", "", "function uncapture() {", " console.log = originalConsole.log;", "}", "", "capture();" ], "challengeSeed": [ "// Example", "function ourFunctionWithArgs(a, b) {", " console.log(a - b);", "}", "ourFunctionWithArgs(10, 5); // Outputs 5", "", "// Only change code below this line.", "", "" ], "tail": [ "uncapture();", "", "if (typeof functionWithArgs !== \"function\") { ", " (function() { return \"functionWithArgs is not defined\"; })();", "} else {", " (function() { return logOutput || \"console.log never called\"; })();", "}" ], "solutions": [ "function functionWithArgs(a, b) {\n console.log(a + b);\n}\nfunctionWithArgs(10, 5);" ], "tests": [ "assert(typeof functionWithArgs === 'function', 'message: functionWithArgs should be a function');", "if(typeof functionWithArgs === \"function\") { capture(); functionWithArgs(1,2); uncapture(); } assert(logOutput == 3, 'message: functionWithArgs(1,2) should output 3');", "if(typeof functionWithArgs === \"function\") { capture(); functionWithArgs(7,9); uncapture(); } assert(logOutput == 16, 'message: functionWithArgs(7,9) should output 16');", "assert(/^\\s*functionWithArgs\\s*\\(\\s*\\d+\\s*,\\s*\\d+\\s*\\)\\s*;/m.test(code), 'message: Call functionWithArgs with two numbers after you define it.');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Pasando valores a funciones con argumentos", "description": [ "Los parámetros son variables que actúan como marcadores de lugar para los valores que han de ser entrada para una función cuando esta es llamada. Cuando una función es definida, es típicamente definida con uno o más parámetros. Los valores actuales que son entrada (or \"pasados\") dentro de una función cuando esta es llamada son concidos como argumentos.", "Aquí hay una función con dos parámetros, param1 y param2:", "
function testFun(param1, param2) {
console.log(param1, param2);
}
", "Entonces nosotros podemos llamar testFun:", "testFun(\"Hello\", \"World\");", "Nosotros hemos pasado dos argumentos, \"Hello\" y \"World\". Dentro de la función, param1 será igual a \"Hello\" y param2 será igual a \"World\". Nota que puedes llamar testFun otra vez con argumentos diferentes y los parámetros asumirían el valor de los nuevos argumentos.", "

Instrucciones

", "
  1. Crea una función llamada functionWithArgs que acepte dos argumentos y da salida a su suma en la consola.
  2. Llama la función.
" ] } } }, { "id": "56533eb9ac21ba0edf2244be", "title": "Global Scope and Functions", "description": [ "In JavaScript, scope refers to the visibility of variables. Variables which are defined outside of a function block have Global scope. This means, they can be seen everywhere in your JavaScript code.", "Variables which are used without the var keyword are automatically created in the global scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with var.", "
", "Using var, declare a global variable myGlobal outside of any function. Initialize it with a value of 10.", "Inside function fun1, assign 5 to oopsGlobal without using the var keyword." ], "releasedOn": "January 1, 2016", "head": [ "var logOutput = \"\";", "var originalConsole = console", "function capture() {", " var nativeLog = console.log;", " console.log = function (message) {", " logOutput = message;", " if(nativeLog.apply) {", " nativeLog.apply(originalConsole, arguments);", " } else {", " var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');", " nativeLog(nativeMsg);", " }", " };", "}", "", "function uncapture() {", " console.log = originalConsole.log;", "}", "var oopsGlobal;", "capture();" ], "challengeSeed": [ "// Declare your variable here", "", "", "function fun1() {", " // Assign 5 to oopsGlobal Here", " ", "}", "", "// Only change code above this line", "function fun2() {", " var output = \"\";", " if (typeof myGlobal != \"undefined\") {", " output += \"myGlobal: \" + myGlobal;", " }", " if (typeof oopsGlobal != \"undefined\") {", " output += \" oopsGlobal: \" + oopsGlobal;", " }", " console.log(output);", "}" ], "tail": [ "fun1();", "fun2();", "uncapture();", "(function() { return logOutput || \"console.log never called\"; })();" ], "solutions": [ "// Declare your variable here\nvar myGlobal = 10;\n\nfunction fun1() {\n // Assign 5 to oopsGlobal Here\n oopsGlobal = 5;\n}\n\n// Only change code above this line\nfunction fun2() {\n var output = \"\";\n if(typeof myGlobal != \"undefined\") {\n output += \"myGlobal: \" + myGlobal;\n }\n if(typeof oopsGlobal != \"undefined\") {\n output += \" oopsGlobal: \" + oopsGlobal;\n }\n console.log(output);\n}" ], "tests": [ "assert(typeof myGlobal != \"undefined\", 'message: myGlobal should be defined');", "assert(myGlobal === 10, 'message: myGlobal should have a value of 10');", "assert(/var\\s+myGlobal/.test(code), 'message: myGlobal should be declared using the var keyword');", "assert(typeof oopsGlobal != \"undefined\" && oopsGlobal === 5, 'message: oopsGlobal should be a global variable and have a value of 5');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Alcance global y funciones", "description": [ "En JavaScript, alcance se referiere a la visibilidad de variables. Las variables que definas fuera de un bloque de una función tienen alcance Global. Esto significa que ellas pueden ser vistas en todas partes en tu código JavaScript.", "Las variables que pueden ser usadas sin la palabra clave var son automáticamente creadas en el alcance global. Esto puede tener consecuencias no deseadas en otras partes de tu código o cuando se ejecuta una función de nuevo. Tu siempre deberías declarar tus variables con var.", "

Instrucciones

", "Declara a variable global myGlobal fuera de cualquier función. Inicializala para tener un valor de 10 ", "Dentro de la función fun1, asigna 5 a oopsGlobal sin usar la palabra clave var." ] } } }, { "id": "56533eb9ac21ba0edf2244bf", "title": "Local Scope and Functions", "description": [ "Variables which are declared within a function, as well as the function parameters have local scope. That means, they are only visible within that function.", "Here is a function myTest with a local variable called loc.", "
function myTest() {
var loc = \"foo\";
console.log(loc);
}
myTest(); // logs \"foo\"
console.log(loc); // loc is not defined
", "loc is not defined outside of the function.", "
", "Declare a local variable myVar inside myLocalScope. Run the tests and then follow the instructions commented out in the editor.", "Hint
Refreshing the page may help if you get stuck." ], "releasedOn": "January 1, 2016", "head": [ "var logOutput = \"\";", "var originalConsole = console", "function capture() {", " var nativeLog = console.log;", " console.log = function (message) {", " logOutput = message;", " if(nativeLog.apply) {", " nativeLog.apply(originalConsole, arguments);", " } else {", " var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');", " nativeLog(nativeMsg);", " }", " };", "}", "", "function uncapture() {", " console.log = originalConsole.log;", "}", "" ], "challengeSeed": [ "function myLocalScope() {", " 'use strict'; // you shouldn't need to edit this line", " ", " console.log(myVar);", "}", "myLocalScope();", "", "// Run and check the console", "// myVar is not defined outside of myLocalScope", "console.log(myVar);", "", "// Now remove the console log line to pass the test", "" ], "tail": [ "typeof myLocalScope === 'function' && (capture(), myLocalScope(), uncapture());", "(function() { return logOutput || \"console.log never called\"; })();" ], "solutions": [ "function myLocalScope() {\n 'use strict';\n \n var myVar;\n console.log(myVar);\n}\nmyLocalScope();" ], "tests": [ "assert(typeof myVar === 'undefined', 'message: No global myVar variable');", "assert(/var\\s+myVar/.test(code), 'message: Add a local myVar variable');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Alcance local y funciones", "description": [ "Las variables que son declaradas dentro de una función, así como los parámetros de la función tienen alcance local. Eso significa que solo son visibles dentro de esa función.", "Aquí está una función myTest con una variable local llamada loc.", "
function myTest() {
var loc = \"foo\";
console.log(loc);
}
myTest(); // \"foo\"
console.log(loc); // \"undefined\"
", "loc no está definida fuera de la función.", "

Instrucciones

", "Declara una variable local myVar dentro de myLocalScope" ] } } }, { "id": "56533eb9ac21ba0edf2244c0", "title": "Global vs. Local Scope in Functions", "description": [ "It is possible to have both local and global variables with the same name. When you do this, the local variable takes precedence over the global variable.", "In this example:", "
var someVar = \"Hat\";
function myFun() {
var someVar = \"Head\";
return someVar;
}
", "The function myFun will return \"Head\" because the local version of the variable is present.", "
", "Add a local variable to myOutfit to override the value of outerWear with \"sweater\"." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Setup", "var outerWear = \"T-Shirt\";", "", "function myOutfit() {", " // Only change code below this line", " ", " ", " ", " // Only change code above this line", " return outerWear;", "}", "", "myOutfit();" ], "solutions": [ "var outerWear = \"T-Shirt\";\nfunction myOutfit() {\n var outerWear = \"sweater\";\n return outerWear;\n}" ], "tests": [ "assert(outerWear === \"T-Shirt\", 'message: Do not change the value of the global outerWear');", "assert(myOutfit() === \"sweater\", 'message: myOutfit should return \"sweater\"');", "assert(/return outerWear/.test(code), 'message: Do not change the return statement');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Alcance global vs. local en funciones", "description": [ "Es posible tener variables locales y globales con el mismo nombre. Cuando tu haces esto, la variable local toma precedencia sobre la variable global.", "En este ejemplo:", "
var algunaVar = \"Sombrero\";
function miFun() {
var algunaVar = \"Cabeza\";
return algunaVar;
}
", "La función miFun regresará \"Cabeza\" porque la versión local de la variable tiene precedencia.", "

Instrucciones

", "Agrega una variable local a myOutfit para sobreescribir el valor de outerWear con \"sweater\"." ] } } }, { "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.", "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.", "
", "Create a function timesFive that accepts one argument, multiplies it by 5, and returns the new value. See the last line in the editor for an example of how you can test your timesFive function." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Example", "function minusSeven(num) {", " return num - 7;", "}", "", "// Only change code below this line", "", "", "", "console.log(minusSeven(10));" ], "tail": [], "solutions": [ "function timesFive(num) {\n return num * 5;\n}" ], "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');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Retorna un valor desde una función con return", "description": [ "Podemos pasar valores a una función mediante los argumentos. Puedes usar una sentencia return para enviar un valor de vuelta de una función.", "Ejemplo", "
function masTres(num) {
return num + 3;
}
var respuesta = masTres(5); // 8
", "masTres toma un argumento que es num y retorna un valor igual a num + 3.", "

Instrucciones

", "Crea una función timesFive que acepte un argumento, lo multiplique por 5 y retorne el nuevo valor." ] } } }, { "id": "56533eb9ac21ba0edf2244c3", "title": "Assignment with a Returned Value", "description": [ "If you'll recall from our discussion of Storing Values with the Assignment 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: ", "ourSum = sum(5, 12);", "will call sum function, which returns a value of 17 and assigns it to ourSum variable.", "
", "Call the processArg function with an argument of 7 and assign its return value to the variable processed." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Example", "var changed = 0;", "", "function change(num) {", " return (num + 5) / 3;", "}", "", "changed = change(10);", "", "// Setup", "var processed = 0;", "", "function processArg(num) {", " return (num + 3) / 5;", "}", "", "// Only change code below this line", "", "" ], "tail": [ "(function(){return \"processed = \" + processed})();" ], "solutions": [ "var processed = 0;\n\nfunction processArg(num) {\n return (num + 3) / 5;\n}\n\nprocessed = processArg(7);" ], "tests": [ "assert(processed === 2, 'message: processed should have a value of 2');", "assert(/processed\\s*=\\s*processArg\\(\\s*7\\s*\\)\\s*;/.test(code), 'message: You should assign processArg to processed');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Asignación con un valor retornado", "description": [ "Si recuerdas de nuestra discusión de Almacenar Valores con el Operador Igual, todo a la derecha del signo igual es resuelto antes que el valor sea asignado. Esto significa que nosotros podemos tomar el valor de retorno de una función y asignarlo a una variable.", "Supongamos que tenemos una función pre-definida suma la cual suma dos números, entonces: ", "nuestraSuma = suma(5, 12);", "llamará la función suma, la cual retornará un valor de 17 y lo asignará a la variable nuestraSuma.", "

Instrucciones

", "Llama la función processArg con un argumento 7 y asigna su valor de retorno a la variable processed." ] } } }, { "id": "56533eb9ac21ba0edf2244c6", "title": "Stand in Line", "description": [ "In Computer Science a queue is an abstract Data Structure where items are kept in order. New items can be added at the back of the queue and old items are taken off from the front of the queue.", "Write a function nextInLine which takes an array (arr) and a number (item) as arguments.", "Add the number to the end of the array, then remove the first element of the array.", "The nextInLine function should then return the element that was removed." ], "releasedOn": "January 1, 2016", "head": [ "var logOutput = [];", "var originalConsole = console", "function capture() {", " var nativeLog = console.log;", " console.log = function (message) {", " logOutput.push(message);", " if(nativeLog.apply) {", " nativeLog.apply(originalConsole, arguments);", " } else {", " var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');", " nativeLog(nativeMsg);", " }", " };", "}", "", "function uncapture() {", " console.log = originalConsole.log;", "}", "", "capture();" ], "challengeSeed": [ "function nextInLine(arr, item) {", " // Your code here", " ", " return item; // Change this line", "}", "", "// Test Setup", "var testArr = [1,2,3,4,5];", "", "// Display Code", "console.log(\"Before: \" + JSON.stringify(testArr));", "console.log(nextInLine(testArr, 6)); // Modify this line to test", "console.log(\"After: \" + JSON.stringify(testArr));" ], "tail": [ "uncapture();", "testArr = [1,2,3,4,5];", "(function() { return logOutput.join(\"\\n\");})();" ], "solutions": [ "var testArr = [ 1,2,3,4,5];\n\nfunction nextInLine(arr, item) {\n arr.push(item);\n return arr.shift();\n}" ], "tests": [ "assert.isNumber(nextInLine([],5), 'message: nextInLine([], 5) should return a number.');", "assert(nextInLine([],1) === 1, 'message: nextInLine([], 1) should return 1');", "assert(nextInLine([2],1) === 2, 'message: nextInLine([2], 1) should return 2');", "assert(nextInLine([5,6,7,8,9],1) === 5, 'message: nextInLine([5,6,7,8,9], 1) should return 5');", "nextInLine(testArr, 10); assert(testArr[4] === 10, 'message: After nextInLine(testArr, 10), testArr[4] should be 10');" ], "type": "checkpoint", "challengeType": 1, "translations": { "es": { "title": "Hacer cola", "description": [ "En Ciencias de la Computación una cola es una Estructura de Datos abstracta donde los elementos son mantenidos en orden. Nuevos elementos pueden ser agregados en la parte trasera de la cola y los elementos viejos son quitados desde el frente de la cola.", "Escribe una función nextInLine la cual toma un vector (arr) y un número (item) como argumentos. Agrega el número al final del vector, entonces retira el primer elemento del vector. La función nextInLine debe entonces devolver el elemento que se ha eliminado." ] } } }, { "id": "bd7123c9c441eddfaeb5bdef", "title": "Understanding Boolean Values", "description": [ "Another data type is the Boolean. Booleans may only be one of two values: true or false. They are basically little on-off switches, where true is \"on\" and false is \"off.\" These two states are mutually exclusive.", "Note
Boolean values are never written with quotes. The strings \"true\" and \"false\" are not Boolean and have no special meaning in JavaScript.", "
", "Modify the welcomeToBooleans function so that it returns true instead of false when the run button is clicked." ], "challengeSeed": [ "function welcomeToBooleans() {", "", "// Only change code below this line.", "", "return false; // Change this line", "", "// Only change code above this line.", "}" ], "tail": [ "welcomeToBooleans();" ], "solutions": [ "function welcomeToBooleans() {\n return true; // Change this line\n}" ], "tests": [ "assert(typeof welcomeToBooleans() === 'boolean', 'message: The welcomeToBooleans() function should return a boolean (true/false) value.');", "assert(welcomeToBooleans() === true, 'message: welcomeToBooleans() should return true.');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Entiende los valores booleanos", "description": [ "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. ", "

Instrucciones

", "Vamos a modificar nuestra función welcomeToBooleans para que devuelva true en lugar de false cuando se pulse el botón de ejecución." ] } } }, { "id": "cf1111c1c12feddfaeb3bdef", "title": "Use Conditional Logic with If Statements", "description": [ "If statements are used to make decisions in code. The keyword if tells JavaScript to execute the code in the curly braces under certain conditions, defined in the parentheses. These conditions are known as Boolean conditions and they may only be true or false.", "When the condition evaluates to true, the program executes the statement inside the curly braces. When the Boolean condition evaluates to false, the statement inside the curly braces will not execute.", "Pseudocode", "
if (condition is true) {
statement is executed
}
", "Example", "
function test (myCondition) {
if (myCondition) {
return \"It was true\";
}
return \"It was false\";
}
test(true); // returns \"It was true\"
test(false); // returns \"It was false\"
", "When test is called with a value of true, the if statement evaluates myCondition to see if it is true or not. Since it is true, the function returns \"It was true\". When we call test with a value of false, myCondition is not true and the statement in the curly braces is not executed and the function returns \"It was false\".", "
", "Create an if statement inside the function to return \"Yes, that was true\" if the parameter wasThatTrue is true and return \"No, that was false\" otherwise." ], "challengeSeed": [ "// Example", "function ourTrueOrFalse(isItTrue) {", " if (isItTrue) { ", " return \"Yes, it's true\";", " }", " return \"No, it's false\";", "}", "", "// Setup", "function trueOrFalse(wasThatTrue) {", "", " // Only change code below this line.", " ", " ", " ", " // Only change code above this line.", "", "}", "", "// Change this value to test", "trueOrFalse(true);" ], "solutions": [ "function trueOrFalse(wasThatTrue) {\n if (wasThatTrue) {\n return \"Yes, that was true\";\n }\n return \"No, that was false\";\n}" ], "tests": [ "assert(typeof trueOrFalse === \"function\", 'message: trueOrFalse should be a function');", "assert(typeof trueOrFalse(true) === \"string\", 'message: trueOrFalse(true) should return a string');", "assert(typeof trueOrFalse(false) === \"string\", 'message: trueOrFalse(false) should return a string');", "assert(trueOrFalse(true) === \"Yes, that was true\", 'message: trueOrFalse(true) should return \"Yes, that was true\"');", "assert(trueOrFalse(false) === \"No, that was false\", 'message: trueOrFalse(false) should return \"No, that was false\"');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Usa lógica condicional con instrucciones if y else", "description": [ "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.", "

Instrucciones

", "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. " ] } } }, { "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 operator is the equality operator ==. The equality operator compares two values and returns true if they're equivalent or false if they are not. Note that equality is different from assignment (=), which assigns the value at the right of the operator to a variable in the left.", "
function equalityTest(myVal) {
if (myVal == 10) {
return \"Equal\";
}
return \"Not Equal\";
}
", "If myVal is equal to 10, the equality operator returns true, so the code in the curly braces will execute, and the function will return \"Equal\". Otherwise, the function will return \"Not Equal\".", "In order for JavaScript to compare two different data types (for example, numbers and strings), it must convert one type to another. Once it does, however, it can compare terms as follows:", "
1 == 1 // true
1 == 2 // false
1 == '1' // true
\"3\" == 3 // true
", "
", "Add the equality operator to the indicated line so that the function will return \"Equal\" when val is equivalent to 12" ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Setup", "function testEqual(val) {", " if (val) { // Change this line", " return \"Equal\";", " }", " return \"Not Equal\";", "}", "", "// Change this value to test", "testEqual(10);" ], "solutions": [ "function testEqual(val) {\n if (val == 12) {\n return \"Equal\";\n }\n return \"Not Equal\";\n}" ], "tests": [ "assert(testEqual(10) === \"Not Equal\", 'message: testEqual(10) should return \"Not Equal\"');", "assert(testEqual(12) === \"Equal\", 'message: testEqual(12) should return \"Equal\"');", "assert(testEqual(\"12\") === \"Equal\", 'message: testEqual(\"12\") should return \"Equal\"');", "assert(code.match(/==/g) && !code.match(/===/g), 'message: You should use the == operator');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "La comparación con el operador de igualdad", "description": [ "Hay muchos Operadores de Comparación en JavaScript. Todos estos operadores retornan un valor booleano true(verdadero) o false(falso).", "El operador más básico es el operador de igualdad ==. El operador de igualdad compara dos valores y retorna true si son equivalentes o false si no lo son. Nota que la igualdad es diferente de la asignación (=), la cual asigna el valor a la derecha del operador a la variable en la izquierda.", "
function pruebaIgualdad(miVal) {
if (miVal == 10) {
return \"Igual\";
}
return \"No Es Igual\";
}
", "Si miVal es igual a 10, el operador de igualdad retornará true(verdadero), así el código entre llaves será ejecutado y la función retornará \"Equal\". De otra manera, la función retornará \"Not Equal\".", "Para que JavaScript pueda comparar dos tipos de datos diferentes (por ejemplo, números y cadenas de texto), debe convertir un tipo a otro. Una vez que lo hace, sin embargo, puede comparar términos de la siguiente manera:", "
1 == 1 // true
1 == 2 // false
1 == '1' // true
\"3\" == 3 // true
", "

Instrucciones

", "Agrega el operador de igualdad a la línea indicada de manera que la función retornará \"Equal\" cuando val sea equivalente a 12" ] } } }, { "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 data type and value of the compared elements.", "Examples", "
3 === 3 // true
3 === '3' // false
", "In the second example, 3 is a Number type and '3' is a String type.", "
", "Use the strict equality operator in the if statement so the function will return \"Equal\" when val is strictly equal to 7" ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Setup", "function testStrict(val) {", " if (val) { // Change this line", " return \"Equal\";", " }", " return \"Not Equal\";", "}", "", "// Change this value to test", "testStrict(10);" ], "solutions": [ "function testStrict(val) {\n if (val === 7) {\n return \"Equal\";\n }\n return \"Not Equal\";\n}" ], "tests": [ "assert(testStrict(10) === \"Not Equal\", 'message: testStrict(10) should return \"Not Equal\"');", "assert(testStrict(7) === \"Equal\", 'message: testStrict(7) should return \"Equal\"');", "assert(testStrict(\"7\") === \"Not Equal\", 'message: testStrict(\"7\") should return \"Not Equal\"');", "assert(code.match(/(val\\s*===\\s*\\d+)|(\\d+\\s*===\\s*val)/g).length > 0, 'message: You should use the === operator');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "La comparación con el operador de estricta igualdad", "description": [ "Igualdad estricta (===) es la contraparte del operador de igualdad (==). Diferente al operador de igualdad, igualdad estricta prueba los tipos de datos y el valor de los elementos comparados.", "Ejemplos", "
3 === 3 // true
3 === '3' // falso
", "En el segundo ejemplo, 3 es de tipo Número y '3' es de tipo Cadena.", "

Instrucciones

", "Usa el operador de igualdad estricta en la sentencia if de manera que la función retorne \"Equal\" cuando val es estrictamente igual a 7" ] } } }, { "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 data types of values while comparing.", "Examples", "
1 != 2 // true
1 != \"1\" // false
1 != '1' // false
1 != true // false
0 != false // false
", "
", "Add the inequality operator != in the if statement so that the function will return \"Not Equal\" when val is not equivalent to 99" ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Setup", "function testNotEqual(val) {", " if (val) { // Change this line", " return \"Not Equal\";", " }", " return \"Equal\";", "}", "", "// Change this value to test", "testNotEqual(10);" ], "solutions": [ "function testNotEqual(val) {\n if (val != 99) {\n return \"Not Equal\";\n }\n return \"Equal\";\n}" ], "tests": [ "assert(testNotEqual(99) === \"Equal\", 'message: testNotEqual(99) should return \"Equal\"');", "assert(testNotEqual(\"99\") === \"Equal\", 'message: testNotEqual(\"99\") should return \"Equal\"');", "assert(testNotEqual(12) === \"Not Equal\", 'message: testNotEqual(12) should return \"Not Equal\"');", "assert(testNotEqual(\"12\") === \"Not Equal\", 'message: testNotEqual(\"12\") should return \"Not Equal\"');", "assert(testNotEqual(\"bob\") === \"Not Equal\", 'message: testNotEqual(\"bob\") should return \"Not Equal\"');", "assert(code.match(/(?!!==)!=/), 'message: You should use the != operator');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "La comparación con el operador de desigualdad", "description": [ "El operador de desigualdad (!=) es el opuesto al operador de igualdad. Esto significa \"No Igual a\" y retorna false cuando igualdad retornaría true y viceversa. Como el operador de igualdad, el operador de desigualdad convertirá tipos de datos mientras compara.", "Ejemplos", "
1 != 2 // true
1 != \"1\" // false
1 != '1' // false
1 != true // false
0 != false // false
", "

Instrucciones

", "Agrega el operador de desigualdad != en la sentencia if de manera que la función retorne \"Not Equal\" (No igual a) cuando val no es equivalente a 99" ] } } }, { "id": "56533eb9ac21ba0edf2244d3", "title": "Comparison with the Strict Inequality Operator", "description": [ "The strict inequality operator (!==) is the logical 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 data types.", "Examples", "
3 !== 3 // false
3 !== '3' // true
4 !== 3 // true
", "
", "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": "January 1, 2016", "challengeSeed": [ "// Setup", "function testStrictNotEqual(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", "testStrictNotEqual(10);" ], "solutions": [ "function testStrictNotEqual(val) {\n if (val !== 17) {\n return \"Not Equal\";\n }\n return \"Equal\";\n}" ], "MDNlinks": [ "Strict Inequality Operator" ], "tests": [ "assert(testStrictNotEqual(17) === \"Equal\", 'message: testStrictNotEqual(17) should return \"Equal\"');", "assert(testStrictNotEqual(\"17\") === \"Not Equal\", 'message: testStrictNotEqual(\"17\") should return \"Not Equal\"');", "assert(testStrictNotEqual(12) === \"Not Equal\", 'message: testStrictNotEqual(12) should return \"Not Equal\"');", "assert(testStrictNotEqual(\"bob\") === \"Not Equal\", 'message: testStrictNotEqual(\"bob\") should return \"Not Equal\"');", "assert(code.match(/(val\\s*!==\\s*\\d+)|(\\d+\\s*!==\\s*val)/g).length > 0, 'message: You should use the !== operator');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "La comparación con el operador de estricta desigualdad", "description": [ "El operador de estricta desigualdad (!==) es el opuesto al operador de estricta igualdad. Esto significa \"Estrictamente no Igual\" y retorna false(falso) donde igualdad estricta retornaría true(verdadero) y viceversa. Estricta desigualdad no convertirá tipos de datos.", "Ejemplos", "
3 !== 3 // false
3 !== '3' // true
4 !== 3 // true
", "

Instrucciones

", "Agrega el operador de estricta desigualdad a la sentencia if de manera que la función retorne \"Not Equal\" cuando val no es estrictamente igual a 17" ] } } }, { "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. Otherwise, it returns false.", "Like the equality operator, greater than operator will convert data types of values while comparing.", "Examples", "
5 > 3 // true
7 > '3' // true
2 > 3 // false
'1' > 9 // false
", "
", "Add the greater than operator to the indicated lines so that the return statements make sense." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "function testGreaterThan(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", "testGreaterThan(10);" ], "solutions": [ "function testGreaterThan(val) {\n if (val > 100) { // Change this line\n return \"Over 100\";\n }\n if (val > 10) { // Change this line\n return \"Over 10\";\n }\n return \"10 or Under\";\n}" ], "tests": [ "assert(testGreaterThan(0) === \"10 or Under\", 'message: testGreaterThan(0) should return \"10 or Under\"');", "assert(testGreaterThan(10) === \"10 or Under\", 'message: testGreaterThan(10) should return \"10 or Under\"');", "assert(testGreaterThan(11) === \"Over 10\", 'message: testGreaterThan(11) should return \"Over 10\"');", "assert(testGreaterThan(99) === \"Over 10\", 'message: testGreaterThan(99) should return \"Over 10\"');", "assert(testGreaterThan(100) === \"Over 10\", 'message: testGreaterThan(100) should return \"Over 10\"');", "assert(testGreaterThan(101) === \"Over 100\", 'message: testGreaterThan(101) should return \"Over 100\"');", "assert(testGreaterThan(150) === \"Over 100\", 'message: testGreaterThan(150) should return \"Over 100\"');", "assert(code.match(/val\\s*>\\s*('|\")*\\d+('|\")*/g).length > 1, 'message: You should use the > operator at least twice');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "La comparación con el operador mayor que", "description": [ "El operador mayor que (>) compara los valores de dos números. Si el número a la izquierda es mayor que el número a la derecha, este returna true(verdadero). De otra manera, este retorna false(falso).", "Al igual que el operador de igualdad, el operador mayor que convertirá tipos de datos de valores mientras los compara.", "Ejemplos", "
5 > 3 // true
7 > '3' // true
2 > 3 // false
'1' > 9 // false
", "

Instrucciones

", "Agrega el operador mayor que para las líneas indicadas de manera que las sentencias retornadas tengan sentido." ] } } }, { "id": "56533eb9ac21ba0edf2244d5", "title": "Comparison with the Greater Than Or Equal To Operator", "description": [ "The greater than or equal to operator (>=) compares the values of two numbers. If the number to the left is greater than or equal to the number to the right, it returns true. Otherwise, it returns false.", "Like the equality operator, greater than or equal to operator will convert data types while comparing.", "Examples", "
6 >= 6 // true
7 >= '3' // true
2 >= 3 // false
'7' >= 9 // false
", "
", "Add the greater than or equal to operator to the indicated lines so that the return statements make sense." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "function testGreaterOrEqual(val) {", " if (val) { // Change this line", " return \"20 or Over\";", " }", " ", " if (val) { // Change this line", " return \"10 or Over\";", " }", "", " return \"Less than 10\";", "}", "", "// Change this value to test", "testGreaterOrEqual(10);" ], "solutions": [ "function testGreaterOrEqual(val) {\n if (val >= 20) { // Change this line\n return \"20 or Over\";\n }\n \n if (val >= 10) { // Change this line\n return \"10 or Over\";\n }\n\n return \"Less than 10\";\n}" ], "tests": [ "assert(testGreaterOrEqual(0) === \"Less than 10\", 'message: testGreaterOrEqual(0) should return \"Less than 10\"');", "assert(testGreaterOrEqual(9) === \"Less than 10\", 'message: testGreaterOrEqual(9) should return \"Less than 10\"');", "assert(testGreaterOrEqual(10) === \"10 or Over\", 'message: testGreaterOrEqual(10) should return \"10 or Over\"');", "assert(testGreaterOrEqual(11) === \"10 or Over\", 'message: testGreaterOrEqual(11) should return \"10 or Over\"');", "assert(testGreaterOrEqual(19) === \"10 or Over\", 'message: testGreaterOrEqual(19) should return \"10 or Over\"');", "assert(testGreaterOrEqual(100) === \"20 or Over\", 'message: testGreaterOrEqual(100) should return \"20 or Over\"');", "assert(testGreaterOrEqual(21) === \"20 or Over\", 'message: testGreaterOrEqual(21) should return \"20 or Over\"');", "assert(code.match(/val\\s*>=\\s*('|\")*\\d+('|\")*/g).length > 1, 'message: You should use the >= operator at least twice');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "La comparación con el operador mayor o ogual", "description": [ "El operador mayor o igual (>=) compara los valores de dos números. Si el número de la izquierda es mayor o igual a el número de la derecha, este retorna true(verdadero). De otra manera, este retorna false(falso).", "Como el operador de igualdad, el operador mayor o igual convertirá tipos de datos mientras está comparando.", "Ejemplos", "
6 >= 6 // true
7 >= '3' // true
2 >= 3 // false
'7' >= 9 // false
", "

Instrucciones

", "Agrega el operador mayor o igual a las líneas indicadas de manera que las sentencias de retorno tengan sentido." ] } } }, { "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. Otherwise, it returns false. Like the equality operator, less than operator converts data types while comparing.", "Examples", "
2 < 5 // true
'3' < 7 // true
5 < 5 // false
3 < 2 // false
'8' < 4 // false
", "
", "Add the less than operator to the indicated lines so that the return statements make sense." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "function testLessThan(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", "testLessThan(10);" ], "solutions": [ "function testLessThan(val) {\n if (val < 25) { // Change this line\n return \"Under 25\";\n }\n \n if (val < 55) { // Change this line\n return \"Under 55\";\n }\n\n return \"55 or Over\";\n}" ], "tests": [ "assert(testLessThan(0) === \"Under 25\", 'message: testLessThan(0) should return \"Under 25\"');", "assert(testLessThan(24) === \"Under 25\", 'message: testLessThan(24) should return \"Under 25\"');", "assert(testLessThan(25) === \"Under 55\", 'message: testLessThan(25) should return \"Under 55\"');", "assert(testLessThan(54) === \"Under 55\", 'message: testLessThan(54) should return \"Under 55\"');", "assert(testLessThan(55) === \"55 or Over\", 'message: testLessThan(55) should return \"55 or Over\"');", "assert(testLessThan(99) === \"55 or Over\", 'message: testLessThan(99) should return \"55 or Over\"');", "assert(code.match(/val\\s*<\\s*('|\")*\\d+('|\")*/g).length > 1, 'message: You should use the < operator at least twice');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "La comparación con el operador menor que", "description": [ "El operador menor que (<) compara los valores de dos números. Si el número a la izquierda es menor que el número de la derecha, este retorna true(verdadero). De otra manera, este retorna false(falso). Como el operador de igualdad, el operador menor que convierte tipos de datos mientra compara.", "Ejemplos", "
2 < 5 // true
'3' < 7 // true
5 < 5 // false
3 < 2 // false
'8' < 4 // false
", "

Instrucciones

", "Agregar el operador menor que a las líneas indicadas de modo que las sentencias de retorno tengan sentido." ] } } }, { "id": "56533eb9ac21ba0edf2244d7", "title": "Comparison with the Less Than Or Equal To Operator", "description": [ "The less than or equal to operator (<=) compares the values of two numbers. If the number to the left is less than or equal 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 or equal to converts data types.", "Examples", "
4 <= 5 // true
'7' <= 7 // true
5 <= 5 // true
3 <= 2 // false
'8' <= 4 // false
", "
", "Add the less than or equal to operator to the indicated lines so that the return statements make sense." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "function testLessOrEqual(val) {", " if (val) { // Change this line", " return \"Smaller Than or Equal to 12\";", " }", " ", " if (val) { // Change this line", " return \"Smaller Than or Equal to 24\";", " }", "", " return \"More Than 24\";", "}", "", "// Change this value to test", "testLessOrEqual(10);", "" ], "solutions": [ "function testLessOrEqual(val) {\n if (val <= 12) { // Change this line\n return \"Smaller Than or Equal to 12\";\n }\n \n if (val <= 24) { // Change this line\n return \"Smaller Than or Equal to 24\";\n }\n\n return \"More Than 24\";\n}" ], "tests": [ "assert(testLessOrEqual(0) === \"Smaller Than or Equal to 12\", 'message: testLessOrEqual(0) should return \"Smaller Than or Equal to 12\"');", "assert(testLessOrEqual(11) === \"Smaller Than or Equal to 12\", 'message: testLessOrEqual(11) should return \"Smaller Than or Equal to 12\"');", "assert(testLessOrEqual(12) === \"Smaller Than or Equal to 12\", 'message: testLessOrEqual(12) should return \"Smaller Than or Equal to 12\"');", "assert(testLessOrEqual(23) === \"Smaller Than or Equal to 24\", 'message: testLessOrEqual(23) should return \"Smaller Than or Equal to 24\"');", "assert(testLessOrEqual(24) === \"Smaller Than or Equal to 24\", 'message: testLessOrEqual(24) should return \"Smaller Than or Equal to 24\"');", "assert(testLessOrEqual(25) === \"More Than 24\", 'message: testLessOrEqual(25) should return \"More Than 24\"');", "assert(testLessOrEqual(55) === \"More Than 24\", 'message: testLessOrEqual(55) should return \"More Than 24\"');", "assert(code.match(/val\\s*<=\\s*('|\")*\\d+('|\")*/g).length > 1, 'message: You should use the <= operator at least twice');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "La comparación con el operador menor o igual", "description": [ "El operador menor o igual (<=) compara los valores de dos números. Si el número a la izquierda es menor o igual que el número de la derecha, este retorna true(verdadero). Si el número a la izquierda es mayor que el número de la derecha, este retorna false(falso). Al igual que el operador de igualdad, menor o igual convierte tipos de datos.", "Ejemplos", "
4 <= 5 // true
'7' <= 7 // true
5 <= 5 // true
3 <= 2 // false
'8' <= 4 // false
", "

Instrucciones

", "Agrega el operador menor o igual a las líneas indicadas de modo que las sentencias de retorno tengan sentido." ] } } }, { "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 > 5) {
if (num < 10) {
return \"Yes\";
}
}
return \"No\";
", "will only return \"Yes\" if num is greater than 5 and less than 10. The same logic can be written as:", "
if (num > 5 && num < 10) {
return \"Yes\";
}
return \"No\";
", "
", "Combine the two if statements into one statement which will return \"Yes\" if val is less than or equal to 50 and greater than or equal to 25. Otherwise, will return \"No\"." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "function testLogicalAnd(val) {", " // Only change code below this line", "", " if (val) {", " if (val) {", " return \"Yes\";", " }", " }", "", " // Only change code above this line", " return \"No\";", "}", "", "// Change this value to test", "testLogicalAnd(10);" ], "solutions": [ "function testLogicalAnd(val) {\n if (val >= 25 && val <= 50) {\n return \"Yes\";\n }\n return \"No\";\n}" ], "tests": [ "assert(code.match(/&&/g).length === 1, 'message: You should use the && operator once');", "assert(code.match(/if/g).length === 1, 'message: You should only have one if statement');", "assert(testLogicalAnd(0) === \"No\", 'message: testLogicalAnd(0) should return \"No\"');", "assert(testLogicalAnd(24) === \"No\", 'message: testLogicalAnd(24) should return \"No\"');", "assert(testLogicalAnd(25) === \"Yes\", 'message: testLogicalAnd(25) should return \"Yes\"');", "assert(testLogicalAnd(30) === \"Yes\", 'message: testLogicalAnd(30) should return \"Yes\"');", "assert(testLogicalAnd(50) === \"Yes\", 'message: testLogicalAnd(50) should return \"Yes\"');", "assert(testLogicalAnd(51) === \"No\", 'message: testLogicalAnd(51) should return \"No\"');", "assert(testLogicalAnd(75) === \"No\", 'message: testLogicalAnd(75) should return \"No\"');", "assert(testLogicalAnd(80) === \"No\", 'message: testLogicalAnd(80) should return \"No\"');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "La comparación con el operador lógico y", "description": [ "A veces necesitarás probar más de una cosa a la vez. El operador lógico y (&&) retorna true(verdadero) si y solo si los operandos a la izquierda y derecha de este son verdaderos.", "El mismo efecto podría lograrse anidando una sentencia if dentro de otro if:", "
if (num > 5) {
if (num < 10) {
return \"Yes\";
}
}
return \"No\";
", "solo retornará \"Yes\" si num está entre 6 y 9 (6 y 9 incluidos). La misma lógica puede ser escrita como:", "
if (num > 5 && num < 10) {
return \"Yes\";
}
return \"No\";
", "

Instrucciones

", "Combina las dos sentencias if dentro de una sentencia la cual retornará \"Yes\" si val es menor o igual a 50 y mayor o igual a 25. De otra manera, retornará \"No\"." ] } } }, { "id": "56533eb9ac21ba0edf2244d9", "title": "Comparisons with the Logical Or Operator", "description": [ "The logical or operator (||) returns true if either of the operands is true. Otherwise, it returns false.", "The pattern below should look familiar from prior waypoints:", "
if (num > 10) {
return \"No\";
}
if (num < 5) {
return \"No\";
}
return \"Yes\";
", "will return \"Yes\" only if num is between 5 and 10 (5 and 10 included). The same logic can be written as:", "
if (num > 10 || num < 5) {
return \"No\";
}
return \"Yes\";
", "
", "Combine the two if statements into one statement which returns \"Outside\" if val is not between 10 and 20, inclusive. Otherwise, return \"Inside\"." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "function testLogicalOr(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", "testLogicalOr(15);" ], "solutions": [ "function testLogicalOr(val) {\n if (val < 10 || val > 20) {\n return \"Outside\";\n }\n return \"Inside\";\n}" ], "tests": [ "assert(code.match(/\\|\\|/g).length === 1, 'message: You should use the || operator once');", "assert(code.match(/if/g).length === 1, 'message: You should only have one if statement');", "assert(testLogicalOr(0) === \"Outside\", 'message: testLogicalOr(0) should return \"Outside\"');", "assert(testLogicalOr(9) === \"Outside\", 'message: testLogicalOr(9) should return \"Outside\"');", "assert(testLogicalOr(10) === \"Inside\", 'message: testLogicalOr(10) should return \"Inside\"');", "assert(testLogicalOr(15) === \"Inside\", 'message: testLogicalOr(15) should return \"Inside\"');", "assert(testLogicalOr(19) === \"Inside\", 'message: testLogicalOr(19) should return \"Inside\"');", "assert(testLogicalOr(20) === \"Inside\", 'message: testLogicalOr(20) should return \"Inside\"');", "assert(testLogicalOr(21) === \"Outside\", 'message: testLogicalOr(21) should return \"Outside\"');", "assert(testLogicalOr(25) === \"Outside\", 'message: testLogicalOr(25) should return \"Outside\"');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "La comparación con el operador lógico o", "description": [ "El operador lógico o (||) retorna true(verdadero) si cualquiera de los operandos es true(verdadero). De otra manera, este retorna false(falso).", "El patrón de abajo debería ser familiar de los puntos de referencia anteriores:", "
if (num > 10) {
return \"No\";
}
if (num < 5) {
return \"No\";
}
return \"Yes\";
", "retornará \"Yes\" solo si num está entre 5 y 10 (5 y 10 incluidos). La misma lógica puede ser escrita como:", "
if (num > 10 || num < 5) {
return \"No\";
}
return \"Yes\";
", "

Instrucciones

", "Combina las dos sentencias if dentro de una sentencia la cual retorne \"Outside\" si val no está entre 10 y 20, inclusive. De otra manera, retorna \"Inside\"." ] } } }, { "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\";
}
", "
", "Combine the if statements into a single if/else statement." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "function testElse(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", "testElse(4);", "" ], "solutions": [ "function testElse(val) {\n var result = \"\";\n if(val > 5) {\n result = \"Bigger than 5\";\n } else {\n result = \"5 or Smaller\";\n }\n return result;\n}" ], "tests": [ "assert(code.match(/if/g).length === 1, 'message: You should only have one if statement in the editor');", "assert(/else/g.test(code), 'message: You should use an else statement');", "assert(testElse(4) === \"5 or Smaller\", 'message: testElse(4) should return \"5 or Smaller\"');", "assert(testElse(5) === \"5 or Smaller\", 'message: testElse(5) should return \"5 or Smaller\"');", "assert(testElse(6) === \"Bigger than 5\", 'message: testElse(6) should return \"Bigger than 5\"');", "assert(testElse(10) === \"Bigger than 5\", 'message: testElse(10) should return \"Bigger than 5\"');", "assert(/var result = \"\";/.test(code) && /return result;/.test(code), 'message: Do not change the code above or below the lines.');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Introducción de las sentencias else", "description": [ "Cuando una condición de una sentencia if es verdadera, el siguiente bloque de código es ejecutado. ¿Y cuando esa condición es falsa? Normalmente nada pasaría. Con una sentencia else(además), un bloque alternativo de código puede ser ejecutado.", "
if (num > 10) {
return \"Más grande que 10\";
} else {
return \"10 o Menos\";
}
", "

Instrucciones

", "Combina las sentencias if dentro de una sola sentencia if/else." ] } } }, { "id": "56533eb9ac21ba0edf2244db", "title": "Introducing Else If Statements", "description": [ "If you have multiple conditions that need to be addressed, you can chain if statements together with else if statements.", "
if (num > 15) {
return \"Bigger than 15\";
} else if (num < 5) {
return \"Smaller than 5\";
} else {
return \"Between 5 and 15\";
}
", "
", "Convert the logic to use else if statements." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "function testElseIf(val) {", " if (val > 10) {", " return \"Greater than 10\";", " }", " ", " if (val < 5) {", " return \"Smaller than 5\";", " }", " ", " return \"Between 5 and 10\";", "}", "", "// Change this value to test", "testElseIf(7);", "" ], "solutions": [ "function testElseIf(val) {\n if(val > 10) {\n return \"Greater than 10\";\n } else if(val < 5) {\n return \"Smaller than 5\";\n } else {\n return \"Between 5 and 10\";\n }\n}" ], "tests": [ "assert(code.match(/else/g).length > 1, 'message: You should have at least two else statements');", "assert(code.match(/if/g).length > 1, 'message: You should have at least two if statements');", "assert(testElseIf(0) === \"Smaller than 5\", 'message: testElseIf(0) should return \"Smaller than 5\"');", "assert(testElseIf(5) === \"Between 5 and 10\", 'message: testElseIf(5) should return \"Between 5 and 10\"');", "assert(testElseIf(7) === \"Between 5 and 10\", 'message: testElseIf(7) should return \"Between 5 and 10\"');", "assert(testElseIf(10) === \"Between 5 and 10\", 'message: testElseIf(10) should return \"Between 5 and 10\"');", "assert(testElseIf(12) === \"Greater than 10\", 'message: testElseIf(12) should return \"Greater than 10\"');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Introducción de las sentencias else if", "description": [ "Si tienes múltiples condiciones que deben abordarse, puedes encadenar sentencias if juntas con sentencias else if.", "
if (num > 15) {
return \"Más grande que 15\";
} else if (num < 5) {
return \"Más pequeño que 5\";
} else {
return \"Entre 5 y 15\";
}
", "

Instrucciones

", "Convierte la lógica para usar sentencias else if." ] } } }, { "id": "5690307fddb111c6084545d7", "title": "Logical Order in If Else Statements", "description": [ "Order is important in if, else if statements.", "The loop is executed from top to bottom so you will want to be careful of what statement comes first.", "Take these two functions as an example.", "Here's the first:", "
function foo(x) {
if (x < 1) {
return \"Less than one\";
} else if (x < 2) {
return \"Less than two\";
} else {
return \"Greater than or equal to two\";
}
}
", "And the second just switches the order of the statements:", "
function bar(x) {
if (x < 2) {
return \"Less than two\";
} else if (x < 1) {
return \"Less than one\";
} else {
return \"Greater than or equal to two\";
}
}
", "While these two functions look nearly identical if we pass a number to both we get different outputs.", "
foo(0) // \"Less than one\"
bar(0) // \"Less than two\"
", "
", "Change the order of logic in the function so that it will return the correct statements in all cases." ], "challengeSeed": [ "function orderMyLogic(val) {", " if (val < 10) {", " return \"Less than 10\";", " } else if (val < 5) {", " return \"Less than 5\";", " } else {", " return \"Greater than or equal to 10\";", " }", "}", "", "// Change this value to test", "orderMyLogic(7);" ], "solutions": [ "function orderMyLogic(val) {\n if(val < 5) {\n return \"Less than 5\"; \n } else if (val < 10) {\n return \"Less than 10\";\n } else {\n return \"Greater than or equal to 10\";\n }\n}" ], "tests": [ "assert(orderMyLogic(4) === \"Less than 5\", 'message: orderMyLogic(4) should return \"Less than 5\"');", "assert(orderMyLogic(6) === \"Less than 10\", 'message: orderMyLogic(6) should return \"Less than 10\"');", "assert(orderMyLogic(11) === \"Greater than or equal to 10\", 'message: orderMyLogic(11) should return \"Greater than or equal to 10\"');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Orden lógico en sentencias else if", "description": [ "El orden es importante en las sentencia if y else if.", "El ciclo es ejecutado de arriba hacia abajo por lo que tendrás que ser cuidadoso de cual sentencia va primero.", "Toma estas dos funciones como ejemplo.", "Aquí está la primera:", "
function foo(x) {
if (x < 1) {
return \"Menor que uno\";
} else if (x < 2) {
return \"Menor que dos\";
} else {
return \"Mayor o igual a dos\";
}
}
", "Y el segundo solo cambia el orden de las sentencias:", "
function bar(x) {
if (x < 2) {
return \"Menor que dos\";
} else if (x < 1) {
return \"Menor que uno\";
} else {
return \"Mayor o igual a dos\";
}
}
", "Mientras esas dos funciones parecen casi idénticas, si nosotros pasamos un número a ambas obtendremos diferentes salidas.", "
foo(0) // \"Menor que uno\"
bar(0) // \"Menor que dos\"
", "

Instrucciones

", "Cambia el orden de la lógica en la función de manera que esta retorne las sentencias correctas en todos los casos." ] } } }, { "id": "56533eb9ac21ba0edf2244dc", "title": "Chaining If Else Statements", "description": [ "if/else statements can be chained together for complex logic. Here is pseudocode of multiple chained if / else if statements:", "
if (condition1) {
statement1
} else if (condition2) {
statement2
} else if (condition3) {
statement3
. . .
} else {
statementN
}
", "
", "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": "January 1, 2016", "challengeSeed": [ "function testSize(num) {", " // Only change code below this line", " ", " ", " return \"Change Me\";", " // Only change code above this line", "}", "", "// Change this value to test", "testSize(7);" ], "solutions": [ "function testSize(num) {\n if (num < 5) {\n return \"Tiny\";\n } else if (num < 10) {\n return \"Small\";\n } else if (num < 15) {\n return \"Medium\";\n } else if (num < 20) {\n return \"Large\";\n } else {\n return \"Huge\";\n }\n}" ], "tests": [ "assert(code.match(/else/g).length > 3, 'message: You should have at least four else statements');", "assert(code.match(/if/g).length > 3, 'message: You should have at least four if statements');", "assert(code.match(/return/g).length >= 1, 'message: You should have at least one return statement');", "assert(testSize(0) === \"Tiny\", 'message: testSize(0) should return \"Tiny\"');", "assert(testSize(4) === \"Tiny\", 'message: testSize(4) should return \"Tiny\"');", "assert(testSize(5) === \"Small\", 'message: testSize(5) should return \"Small\"');", "assert(testSize(8) === \"Small\", 'message: testSize(8) should return \"Small\"');", "assert(testSize(10) === \"Medium\", 'message: testSize(10) should return \"Medium\"');", "assert(testSize(14) === \"Medium\", 'message: testSize(14) should return \"Medium\"');", "assert(testSize(15) === \"Large\", 'message: testSize(15) should return \"Large\"');", "assert(testSize(17) === \"Large\", 'message: testSize(17) should return \"Large\"');", "assert(testSize(20) === \"Huge\", 'message: testSize(20) should return \"Huge\"');", "assert(testSize(25) === \"Huge\", 'message: testSize(25) should return \"Huge\"');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Encadenamiento de sentencias else if", "description": [ "Las sentencias if/else(si/de lo contrario) pueden ser encadenadas juntas por una lógica compleja. Aquí está el pseudocódigo de múltiples sentencias if / else if encadenadas:", "
if (condicion1) {
sentencias1
} else if (condicion2) {
sentencias2
} else if (condicion3) {
sentencias3
. . .
} else {
sentenciasN
}
", "

Instrucciones

", "Escribe sentencias if/else if encadenadas para cumplir las siguientes condiciones:", "num < 5 - retorna \"Tiny\"
num < 10 - retorna \"Small\"
num < 15 - retorna \"Medium\"
num < 20 - retorna \"Large\"
num >= 20 - retorna \"Huge\"" ] } } }, { "id": "5664820f61c48e80c9fa476c", "title": "Golf Code", "description": [ "In the game of golf each hole has a par meaning the average number of strokes a golfer is expected to make in order to sink the ball in a hole to complete the play. Depending on how far above or below par your strokes are, there is a different nickname.", "Your function will be passed par and strokes arguments. Return the correct string according to this table which lists the strokes in order of priority; top (highest) to bottom (lowest):", "
StrokesReturn
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": "January 1, 2016", "challengeSeed": [ "function golfScore(par, strokes) {", " // Only change code below this line", " ", " ", " return \"Change Me\";", " // Only change code above this line", "}", "", "// Change these values to test", "golfScore(5, 4);" ], "solutions": [ "function golfScore(par, strokes) {\n if (strokes === 1) {\n return \"Hole-in-one!\";\n }\n \n if (strokes <= par - 2) {\n return \"Eagle\";\n }\n \n if (strokes === par - 1) {\n return \"Birdie\";\n }\n \n if (strokes === par) {\n return \"Par\";\n }\n \n if (strokes === par + 1) {\n return \"Bogey\";\n }\n \n if(strokes === par + 2) {\n return \"Double Bogey\";\n }\n \n return \"Go Home!\";\n}" ], "tests": [ "assert(golfScore(4, 1) === \"Hole-in-one!\", 'message: 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(5, 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(1, 1) === \"Hole-in-one!\", 'message: golfScore(1, 1) should return \"Hole-in-one!\"');", "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!\"');" ], "type": "checkpoint", "challengeType": 1, "translations": { "es": { "title": "Código de golf", "description": [ "En el juego de golf cada hoyo tiene un par promedio para el número de golpes necesarios para meter la pelota. Dependiendo de que tan lejos por encima o por debajo del par estén tus golpes, habrá un sobrenombre diferente.", "Tu función pasará un par y el número de golpes, y retornará una cadena de acuerdo a esta tabla (basada en el orden de prioridad - arriba (lo más alto) hacia abajo (lo más bajo)):", "
GolpesRetorna
1\"Hole-in-one!\"
<= par - 2\"Eagle\"
par - 1\"Birdie\"
par\"Par\"
par + 1\"Bogey\"
par + 2\"Double Bogey\"
>= par + 3\"Go Home!\"
", "Tanto par como golpes siempre serán numéricos y positivos." ] } } }, { "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 can have many case statements which define various possible values. Statements are executed from the first matched case value until a break is encountered.", "Here is a pseudocode example:", "
switch (num) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
case valueN:
statementN;
break;
}
", "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.", "
", "Write a switch statement which tests val and sets answer for the following conditions:
1 - \"alpha\"
2 - \"beta\"
3 - \"gamma\"
4 - \"delta\"" ], "releasedOn": "January 1, 2016", "challengeSeed": [ "function caseInSwitch(val) {", " var answer = \"\";", " // Only change code below this line", " ", " ", " ", " // Only change code above this line ", " return answer; ", "}", "", "// Change this value to test", "caseInSwitch(1);", "" ], "solutions": [ "function caseInSwitch(val) {\n var answer = \"\";\n\n switch (val) {\n case 1:\n answer = \"alpha\";\n break;\n case 2:\n answer = \"beta\";\n break;\n case 3:\n answer = \"gamma\";\n break;\n case 4:\n answer = \"delta\";\n }\n return answer; \n}" ], "tests": [ "assert(caseInSwitch(1) === \"alpha\", 'message: caseInSwitch(1) should have a value of \"alpha\"');", "assert(caseInSwitch(2) === \"beta\", 'message: caseInSwitch(2) should have a value of \"beta\"');", "assert(caseInSwitch(3) === \"gamma\", 'message: caseInSwitch(3) should have a value of \"gamma\"');", "assert(caseInSwitch(4) === \"delta\", 'message: caseInSwitch(4) should have a value of \"delta\"');", "assert(!/else/g.test(code) || !/if/g.test(code), 'message: You should not use any if or else statements');", "assert(code.match(/break/g).length > 2, 'message: You should have at least 3 break statements');" ], "type": "waypoint", "MDNlinks": [ "Switch Statement" ], "challengeType": 1, "translations": { "es": { "title": "Seleccionar desde diferentes opciones con la sentencia switch", "description": [ "Si tienes varias opciones para elegir, usa una sentencia switch. Una sentencia switch prueba un valor y puede tener varias sentencias case las cuales definen varios posibles valores. Las sentencias son ejecutadas desde el primer valor case igualado hasta que se encuentr un break.", "Aquí hay un pseudocódigo de ejemplo:", "
switch (num) {
case valor1:
sentencia1;
break;
case valor2:
sentencia2;
break;
...
case valorN:
sentenciaN;
break;
}
", "Los valores case son probados con estricta igualdad (===). El break le dice a JavaScript que pare la ejecución del bloque de sentencias en el que está. Si se omite break, se ejecutará la siguiente sentencia.", "

Instrucciones

", "Escribe una sentencia switch que pruebe val y establezca answer para las siguientes condiciones:
1 - \"alpha\"
2 - \"beta\"
3 - \"gamma\"
4 - \"delta\"" ] } } }, { "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 add the default statement which will be executed if no matching case statements are found. Think of it like the final else statement in an if/else chain.", "A default statement should be the last case.", "
switch (num) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
default:
defaultStatement;
}
", "
", "Write a switch statement to set answer for the following conditions:
\"a\" - \"apple\"
\"b\" - \"bird\"
\"c\" - \"cat\"
default - \"stuff\"" ], "releasedOn": "January 1, 2016", "challengeSeed": [ "function switchOfStuff(val) {", " var answer = \"\";", " // Only change code below this line", " ", " ", " ", " // Only change code above this line ", " return answer; ", "}", "", "// Change this value to test", "switchOfStuff(1);", "" ], "solutions": [ "function switchOfStuff(val) {\n var answer = \"\";\n\n switch(val) {\n case \"a\":\n answer = \"apple\";\n break;\n case \"b\":\n answer = \"bird\";\n break;\n case \"c\":\n answer = \"cat\";\n break;\n default:\n answer = \"stuff\";\n }\n return answer; \n}" ], "tests": [ "assert(switchOfStuff(\"a\") === \"apple\", 'message: switchOfStuff(\"a\") should have a value of \"apple\"');", "assert(switchOfStuff(\"b\") === \"bird\", 'message: switchOfStuff(\"b\") should have a value of \"bird\"');", "assert(switchOfStuff(\"c\") === \"cat\", 'message: switchOfStuff(\"c\") should have a value of \"cat\"');", "assert(switchOfStuff(\"d\") === \"stuff\", 'message: switchOfStuff(\"d\") should have a value of \"stuff\"');", "assert(switchOfStuff(4) === \"stuff\", 'message: switchOfStuff(4) should have a value of \"stuff\"');", "assert(!/else/g.test(code) || !/if/g.test(code), 'message: You should not use any if or else statements');", "assert(switchOfStuff(\"string-to-trigger-default-case\") === \"stuff\", 'message: You should use a default statement');", "assert(code.match(/break/g).length > 2, 'message: You should have at least 3 break statements');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Agregar una opción por omisión (default) en una sentencia switch", "description": [ "En una sentencia switch puede que no seas capaz de especificar todos los posibles valores en las sentencias case. En su lugar, puedes agregar la sentencia default la cual será ejecutada si no es encontrada ninguna coincidencia con alguna sentencia case. Piensa en esto como la última sentencia else en una cadena if/else.", "Una sentencia default debería ser el último caso.", "
switch (num) {
case valor1:
sentencia1;
break;
case valor2:
sentencia2;
break;
...
default:
sentenciaDefault;
}
", "

Instrucciones

", "Escribe una sentencia switch para establecer answer para las siguientes condiciones:
\"a\" - \"apple\"
\"b\" - \"bird\"
\"c\" - \"cat\"
default - \"stuff\"" ] } } }, { "id": "56533eb9ac21ba0edf2244df", "title": "Multiple Identical Options in Switch Statements", "description": [ "If the break statement is omitted from a switch statement's case, the following case statement(s) are executed until a break is encountered. If you have multiple inputs with the same output, you can represent them in a switch statement like this:", "
switch(val) {
case 1:
case 2:
case 3:
result = \"1, 2, or 3\";
break;
case 4:
result = \"4 alone\";
}
", "Cases for 1, 2, and 3 will all produce the same result.", "
", "Write a switch statement to set answer for the following ranges:
1-3 - \"Low\"
4-6 - \"Mid\"
7-9 - \"High\"", "Note
You will need to have a case statement for each number in the range." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "function sequentialSizes(val) {", " var answer = \"\";", " // Only change code below this line", " ", " ", " ", " // Only change code above this line ", " return answer; ", "}", "", "// Change this value to test", "sequentialSizes(1);", "" ], "solutions": [ "function sequentialSizes(val) {\n var answer = \"\";\n \n switch (val) {\n case 1:\n case 2:\n case 3:\n answer = \"Low\";\n break;\n case 4:\n case 5:\n case 6:\n answer = \"Mid\";\n break;\n case 7:\n case 8:\n case 9:\n answer = \"High\";\n }\n \n return answer; \n}" ], "tests": [ "assert(sequentialSizes(1) === \"Low\", 'message: sequentialSizes(1) should return \"Low\"');", "assert(sequentialSizes(2) === \"Low\", 'message: sequentialSizes(2) should return \"Low\"');", "assert(sequentialSizes(3) === \"Low\", 'message: sequentialSizes(3) should return \"Low\"');", "assert(sequentialSizes(4) === \"Mid\", 'message: sequentialSizes(4) should return \"Mid\"');", "assert(sequentialSizes(5) === \"Mid\", 'message: sequentialSizes(5) should return \"Mid\"');", "assert(sequentialSizes(6) === \"Mid\", 'message: sequentialSizes(6) should return \"Mid\"');", "assert(sequentialSizes(7) === \"High\", 'message: sequentialSizes(7) should return \"High\"');", "assert(sequentialSizes(8) === \"High\", 'message: sequentialSizes(8) should return \"High\"');", "assert(sequentialSizes(9) === \"High\", 'message: sequentialSizes(9) should return \"High\"');", "assert(!/else/g.test(code) || !/if/g.test(code), 'message: You should not use any if or else statements');", "assert(code.match(/case/g).length === 9, 'message: You should have nine case statements');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Múltiples opciones idénticas en una sentencias switch", "description": [ "Si la sentencia break es omitida de una sentencia case de un switch, las siguientes sentencias case son ejecutadas hasta que sea encontrado un break. Si tienes multiples entradas con la misma salida, puede representarlas en una sentencia switch así:", "
switch(val) {
case 1:
case 2:
case 3:
result = \"1, 2, or 3\";
break;
case 4:
result = \"4 alone\";
}
", "Los casos 1, 2, y 3 producirán el mismo resultado.", "

Instrucciones

", "Escribe una sentencia switch para establecer answer para los siguientes rangos:
1-3 - \"Low\"
4-6 - \"Mid\"
7-9 - \"High\"", "Nota
Necesitarás tener una sentencia case por cada número en el rango." ] } } }, { "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/else if 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\";
}
", "
", "Change the chained if/else if statements into a switch statement." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "function chainToSwitch(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", "chainToSwitch(7);", "" ], "solutions": [ "function chainToSwitch(val) {\n var answer = \"\";\n\n switch (val) {\n case \"bob\":\n answer = \"Marley\";\n break;\n case 42:\n answer = \"The Answer\";\n break;\n case 1:\n answer = \"There is no #1\";\n break;\n case 99:\n answer = \"Missed me by this much!\";\n break;\n case 7:\n answer = \"Ate Nine\";\n }\n return answer; \n}" ], "tests": [ "assert(!/else/g.test(code), 'message: You should not use any else statements anywhere in the editor');", "assert(!/if/g.test(code), 'message: You should not use any if statements anywhere in the editor');", "assert(code.match(/break/g).length >= 4, 'message: You should have at least four break statements');", "assert(chainToSwitch(\"bob\") === \"Marley\", 'message: chainToSwitch(\"bob\") should be \"Marley\"');", "assert(chainToSwitch(42) === \"The Answer\", 'message: chainToSwitch(42) should be \"The Answer\"');", "assert(chainToSwitch(1) === \"There is no #1\", 'message: chainToSwitch(1) should be \"There is no #1\"');", "assert(chainToSwitch(99) === \"Missed me by this much!\", 'message: chainToSwitch(99) should be \"Missed me by this much!\"');", "assert(chainToSwitch(7) === \"Ate Nine\", 'message: chainToSwitch(7) should be \"Ate Nine\"');", "assert(chainToSwitch(\"John\") === \"\", 'message: chainToSwitch(\"John\") should be \"\" (empty string)');", "assert(chainToSwitch(156) === \"\", 'message: chainToSwitch(156) should be \"\" (empty string)');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Reemplazar cadenas if else con switch", "description": [ "Si tienes varias opciones para elegir, una sentencia switch puede ser más fácil de escribir que varias sentencias if/if else anidadas. Lo siguiente:", "
if (val === 1) {
respuesta = \"a\";
} else if (val === 2) {
respuesta = \"b\";
} else {
respuesta = \"c\";
}
", "puede ser reemplazado con:", "
switch (val) {
case 1:
respuesta = \"a\";
break;
case 2:
respuesta = \"b\";
break;
default:
respuesta = \"c\";
}
", "

Instrucciones

", "Cambia las sentencias if/if else anidadas dentro de una sentencia switch." ] } } }, { "id": "5679ceb97cbaa8c51670a16b", "title": "Returning Boolean Values from Functions", "description": [ "You may recall from Comparison with the Equality Operator that all comparison operators return a boolean true or false value.", "Sometimes people use an if/else statement to do a comparison, like this:", "
function isEqual(a,b) {
if (a === b) {
return true;
} else {
return false;
}
}
", "But there's a better way to do this. Since === returns true or false, we can return the result of the comparison:", "
function isEqual(a,b) {
return a === b;
}
", "
", "Fix the function isLess to remove the if/else statements." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "function isLess(a, b) {", " // Fix this code", " if (a < b) {", " return true;", " } else {", " return false;", " }", "}", "", "// Change these values to test", "isLess(10, 15);" ], "tail": [ "" ], "solutions": [ "function isLess(a, b) {\n return a < b;\n}" ], "tests": [ "assert(isLess(10,15) === true, 'message: isLess(10,15) should return true');", "assert(isLess(15, 10) === false, 'message: isLess(15,10) should return false');", "assert(!/if|else/g.test(code), 'message: You should not use any if or else statements');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Retornar valores booleanos desde funciones", "description": [ "Tal vez recuerdes de La comparación con el operador de igualdad que todos los operadores de comparación retornan un valor booleano true (verdadero) o false (falso).", "Un anti-patrón común es usar una sentencia if/else para hacer una comparación y entonces retornar true o false:", "
function sonIguales(a,b) {
if (a === b) {
return true;
} else {
return false;
}
}
", "Ya que === returna true (verdadero) o false (falso), podemos simplemente retornar el resultado de la comparación:", "
function sonIguales(a,b) {
return a === b;
}
", "

Instrucciones

", "Arregla la función isLess para remover las sentencias if/else." ] } } }, { "id": "56533eb9ac21ba0edf2244c4", "title": "Return Early Pattern for Functions", "description": [ "When a return statement is reached, the execution of the current function stops and control returns to the calling location.", "Example", "
function myFun() {
console.log(\"Hello\");
return \"World\";
console.log(\"byebye\")
}
myFun();
", "The above outputs \"Hello\" to the console, returns \"World\", but \"byebye\" is never output, because the function exits at the return statement.", "
", "Modify the function abTest so that if a or b are less than 0 the function will immediately exit with a value of undefined.", "Hint
Remember that undefined is a keyword, not a string." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Setup", "function abTest(a, b) {", " // Only change code below this line", " ", " ", " ", " // Only change code above this line", "", " return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));", "}", "", "// Change values below to test your code", "abTest(2,2);" ], "tail": [ "" ], "solutions": [ "function abTest(a, b) {\n if(a < 0 || b < 0) {\n return undefined;\n } \n return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));\n}" ], "tests": [ "assert(typeof abTest(2,2) === 'number' , 'message: abTest(2,2) should return a number');", "assert(abTest(2,2) === 8 , 'message: abTest(2,2) should return 8');", "assert(abTest(-2,2) === undefined , 'message: abTest(-2,2) should return undefined');", "assert(abTest(2,-2) === undefined , 'message: abTest(2,-2) should return undefined');", "assert(abTest(2,8) === 18 , 'message: abTest(2,8) should return 18');", "assert(abTest(3,3) === 12 , 'message: abTest(3,3) should return 12');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Retornar un patrón temprano para funciones", "description": [ "Cuando se alcanza una sentencia return, la ejecución de la presente función se detiene y el control la retorna a la ubicación de la llamada.", "Ejemplo", "
function miFuncion() {
console.log(\"Hola\");
return \"Mundo\";
console.log(\"chaochao\")
}
miFuncion();
", "Esta presenta en consola \"Hola\", retorna \"Mundo\", pero \"chaochao\" nunca se presenta, porque la función sale con la sentencia return.", "

Instrucciones

", "Modifica la función abTest de manera que si a o b son menores que 0 la función saldrá inmediatamente con un valor undefined.", "Pista
Recuerda que undefined es una palabra clave, no una cadena." ] } } }, { "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.", "
Count ChangeCards
+12, 3, 4, 5, 6
07, 8, 9
-110, 'J', 'Q', 'K', 'A'
", "You will write a card counting function. It will receive a card parameter, which can be a number or a string, and increment or decrement the global count variable according to the card's value (see table). The function will then return a string with the current count and the string Bet if the count is positive, or Hold if the count is zero or negative. The current count and the player's decision (Bet or Hold) should be separated by a single space.", "Example Output
-3 Hold
5 Bet", "Hint
Do NOT reset count to 0 when value is 7, 8, or 9.
Do NOT return an array.
Do NOT include quotes (single or double) in the output." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "var count = 0;", "", "function cc(card) {", " // Only change code below this line", " ", " ", " return \"Change Me\";", " // Only change code above this line", "}", "", "// Add/remove calls to test your function.", "// Note: Only the last will display", "cc(2); cc(3); cc(7); cc('K'); cc('A');" ], "solutions": [ "var count = 0;\nfunction cc(card) {\n switch(card) {\n case 2:\n case 3:\n case 4:\n case 5:\n case 6:\n count++;\n break;\n case 10:\n case 'J':\n case 'Q':\n case 'K':\n case 'A':\n count--;\n }\n if(count > 0) {\n return count + \" Bet\";\n } else {\n return count + \" Hold\";\n }\n}" ], "tests": [ "assert((function(){ count = 0; cc(2);cc(3);cc(4);cc(5);var out = cc(6); if(out === \"5 Bet\") {return true;} return false; })(), 'message: Cards Sequence 2, 3, 4, 5, 6 should return 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(7);cc('Q');cc(8);var out = cc('A'); if(out === \"-1 Hold\") {return true;} return false; })(), 'message: Cards Sequence 3, 7, Q, 8, A should return -1 Hold');", "assert((function(){ count = 0; cc(2);cc('J');cc(9);cc(2);var out = cc(7); if(out === \"1 Bet\") {return true;} return false; })(), 'message: Cards Sequence 2, J, 9, 2, 7 should return 1 Bet');", "assert((function(){ count = 0; cc(2);cc(2);var out = cc(10); if(out === \"1 Bet\") {return true;} return false; })(), 'message: Cards Sequence 2, 2, 10 should return 1 Bet');", "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');" ], "type": "checkpoint", "challengeType": 1, "translations": { "es": { "title": "Contar cartas", "description": [ "En el juego de casino Blackjack, un jugador puede conseguir ventaja sobre la casa manteniendo un registro del número relativo de cartas altas y bajas restantes en la baraja. Esto es llamado Conteo de Cartas.", "Tener más cartas altas restantes en la baraja favorece al jugador. A cada carta se le asigna un valor de acuerdo a la tabla de abajo. Cuando el conteo es positivo, el jugador debe apostar alto. Cuando el conteo es cero o negativo, el jugador debe apostar bajo.", "
ValorCartas
+12, 3, 4, 5, 6
07, 8, 9
-110, 'J', 'Q', 'K','A'
", "Vas a escribir una función de conteo de cartas. Esta recibirá un parametro card (carta) e incrementa o decrementa la variable count (conteo) global de acuerdo al valor de la carta (ver tabla). La función retornará entonces una cadena con el presente conteo y la cadena Bet si el conteo es positivo o Hold si el conteo es cero o negativo. El presente conteo y la desición del jugador (Bet o Hold) deben quedar separada por un único espacio.", "Ejemplo de Salida
-3 Hold
5 Bet
" ] } } }, { "id": "56bbb991ad1ed5201cd392d0", "title": "Build JavaScript Objects", "description": [ "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\"]
};
", "Objects are useful for storing data in a structured way, and can represent real world objects, like a cat.", "
", "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." ], "challengeSeed": [ "// Example", "var ourDog = {", " \"name\": \"Camper\",", " \"legs\": 4,", " \"tails\": 1,", " \"friends\": [\"everything!\"]", "};", "", "// Only change code below this line.", "", "var myDog = {", " ", " ", " ", " ", "};" ], "tail": [ "(function(z){return z;})(myDog);" ], "solutions": [ "var myDog = {\n \"name\": \"Camper\",\n \"legs\": 4,\n \"tails\": 1,\n \"friends\": [\"everything!\"] \n};" ], "tests": [ "assert((function(z){if(z.hasOwnProperty(\"name\") && z.name !== undefined && typeof z.name === \"string\"){return true;}else{return false;}})(myDog), 'message: 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.');", "assert((function(z){return Object.keys(z).length === 4;})(myDog), 'message: myDog should only contain all the given properties.');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Construye objetos en JavaScript", "description": [ "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." ] } } }, { "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 dot operator (.) to read an object property:", "
var myObj = {
prop1: \"val1\",
prop2: \"val2\"
};
var prop1val = myObj.prop1; // val1
var prop2val = myObj.prop2; // val2
", "
", "Read in the property values of testObj using dot notation. Set the variable hatValue equal to the object property hat and set the variable shirtValue equal to the object property shirt." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Setup", "var testObj = {", " \"hat\": \"ballcap\",", " \"shirt\": \"jersey\",", " \"shoes\": \"cleats\"", "};", "", "// Only change code below this line", "", "var hatValue = testObj; // Change this line", "var shirtValue = testObj; // Change this line" ], "tail": [ "(function(a,b) { return \"hatValue = '\" + a + \"', shirtValue = '\" + b + \"'\"; })(hatValue,shirtValue);" ], "solutions": [ "var testObj = {\n \"hat\": \"ballcap\",\n \"shirt\": \"jersey\",\n \"shoes\": \"cleats\"\n};\n\nvar hatValue = testObj.hat; \nvar shirtValue = testObj.shirt;" ], "tests": [ "assert(typeof hatValue === 'string' , 'message: 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\"');", "assert(code.match(/testObj\\.\\w+/g).length > 1, 'message: You should use dot notation twice');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Acceder a propiedades de objetos con el operador punto", "description": [ "Hay dos maneras de acceder a las propiedades de un objeto: con el operador punto (.) y con la notación corchete ([]), similar al caso de un vector.", "El operador punto es el que usas cuando de antemano sabes el nombre de la propiedad que estás intentando acceder.", "Aquí está un ejemplo del uso del operador punto (.) para leer una propiedad de un objeto:", "
var miObj = {
prop1: \"val1\",
prop2: \"val2\"
};
var prop1val = miObj.prop1; // val1
var prop2val = miObj.prop2; // val2
", "

Instrucciones

", "Lee los valores de propiedades de testObj usando notación punto. Asigna la variable hatValue igual a la propiedad objeto hat y asigna la variable shirtValue igual a la propiedad objeto shirt." ] } } }, { "id": "56533eb9ac21ba0edf2244c8", "title": "Accessing Objects Properties with Bracket Notation", "description": [ "The second way to access the properties of an object is bracket notation ([]). If the property of the object you are trying to access has a space in it's name, 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).", "
", "Read the values of the properties \"an entree\" and \"the drink\" of testObj using bracket notation and assign them to entreeValue and drinkValue respectively." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Setup", "var testObj = {", " \"an entree\": \"hamburger\",", " \"my side\": \"veggies\",", " \"the drink\": \"water\"", "};", "", "// Only change code below this line", "", "var entreeValue = testObj; // Change this line", "var drinkValue = testObj; // Change this line" ], "tail": [ "(function(a,b) { return \"entreeValue = '\" + a + \"', drinkValue = '\" + b + \"'\"; })(entreeValue,drinkValue);" ], "solutions": [ "var testObj = {\n \"an entree\": \"hamburger\",\n \"my side\": \"veggies\",\n \"the drink\": \"water\"\n};\nvar entreeValue = testObj[\"an entree\"];\nvar drinkValue = testObj['the drink'];" ], "tests": [ "assert(typeof entreeValue === 'string' , 'message: 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(code.match(/testObj\\s*?\\[('|\")[^'\"]+\\1\\]/g).length > 1, 'message: You should use bracket notation twice');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Acceder a las propiedades de objetos con la notación corchete", "description": [ "La segunda manera de acceder a las propiedades de un objeto es con la notación corchete ([]). Si el nombre de la propiedad del objeto que estás intentando acceder tiene un espacio, necesitarás usar la notación corchete.", "Aquí está un ejemplo del uso de la notación corchete para leer una propiedad de un objeto:", "
var miObj = {
\"Nombre con espacio\": \"Kirk\",
\"Mas espacio\": \"Spock\"
};
miObj[\"Nombre con espacio\"]; // Kirk
miObj['Mas espacio']; // Spock
", "Nota que los nombres de propiedades con espacios tienen que estar entre comillas (apóstrofes o comillas).", "

Instrucciones

", "Lee los valores de las propiedades \"an entree\" y \"the drink\" de testObj usando la notación corchete." ] } } }, { "id": "56533eb9ac21ba0edf2244c9", "title": "Accessing Objects Properties with Variables", "description": [ "Another use of bracket notation on objects is to use a variable to access a property. This can be very useful for iterating through lists of the object properties or for doing the lookup.", "Here is an example of using a variable to access a property:", "
var someProp = \"propName\";
var myObj = {
propName: \"Some Value\"
}
myObj[someProp]; // \"Some Value\"
", "Here is one more:", "
var myDog = \"Hunter\";
var dogs = {
Fido: \"Mutt\",\n Hunter: \"Doberman\",\n Snoopie: \"Beagle\"
}
var breed = dogs[myDog];
console.log(breed);// \"Doberman\"
", "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", "
", "Use the playerNumber variable to lookup player 16 in testObj using bracket notation. Then assign that name to the player variable." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Setup", "var testObj = {", " 12: \"Namath\",", " 16: \"Montana\",", " 19: \"Unitas\"", "};", "", "// Only change code below this line;", "", "var playerNumber; // Change this Line", "var player = testObj; // Change this Line" ], "tail": [ "if(typeof player !== \"undefined\"){(function(v){return v;})(player);}" ], "solutions": [ "var testObj = {\n 12: \"Namath\",\n 16: \"Montana\",\n 19: \"Unitas\"\n};\nvar playerNumber = 16;\nvar player = testObj[playerNumber];" ], "tests": [ "assert(typeof playerNumber === 'number', 'message: 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*?\\[.*?\\]/.test(code),'message: You should use bracket notation to access testObj');", "assert(/testObj\\s*?\\[\\s*playerNumber\\s*\\]/.test(code),'message: You should be using the variable playerNumber in your bracket notation');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Acceder a propiedades de objetos con variables", "description": [ "Otro uso de la notación corchete sobre objetos es usar una variable para acceder a una propiedad. Esto puede ser muy útil en iteraciones sobre la lista de propiedades de un objetos o para hacer operaciones de búsqueda.", "Aquí está un ejemplo del uso de una variable para acceder a una propiedad:", "
var algunaProp = \"propNombre\";
var miObj = {
propNombre: \"Algún valor\"
}
miObj[algunaProp]; // \"Algún valor\"
", "Aquí hay uno más:", "
var miPerro = \"Cazador\";
var perros = {
Fido: \"Mutt\",\n Cazador: \"Doberman\",\n Snoopie: \"Beagle\"
}
var raza = perros[miPerro]; // \"Cazador\"
console.log(raza)// \"Doberman\"
", "Nota que no usamos comillas alrededor del nombre de la variable (miPerro) cuando la usamos para acceder a la propiedad (perros[miPerro] porque estamos usando el valor de la variable y no su nombre", "

Instrucciones

", "Usa la variable playerNumber para buscar y asignar a player el jugador 16 de testObj, usa la notación corchete." ] } } }, { "id": "56bbb991ad1ed5201cd392d1", "title": "Updating Object Properties", "description": [ "After you've created a JavaScript object, you can update its properties at any time just like you would update any other variable. You can use either dot or bracket notation to update.", "For example, let's look at ourDog:", "
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\"; or", "ourDog[\"name\"] = \"Happy Camper\";", "Now when we evaluate ourDog.name, instead of getting \"Camper\", we'll get his new name, \"Happy Camper\".", "
", "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." ], "challengeSeed": [ "// Example", "var ourDog = {", " \"name\": \"Camper\",", " \"legs\": 4,", " \"tails\": 1,", " \"friends\": [\"everything!\"]", "};", "", "ourDog.name = \"Happy Camper\";", "", "// Setup", "var myDog = {", " \"name\": \"Coder\",", " \"legs\": 4,", " \"tails\": 1,", " \"friends\": [\"freeCodeCamp Campers\"]", "};", "", "// Only change code below this line.", "", "" ], "tail": [ "(function(z){return z;})(myDog);" ], "solutions": [ "var myDog = {\n \"name\": \"Coder\",\n \"legs\": 4,\n \"tails\": 1,\n \"friends\": [\"freeCodeCamp Campers\"]\n};\nmyDog.name = \"Happy Coder\";" ], "tests": [ "assert(/happy coder/gi.test(myDog.name), 'message: Update myDog's \"name\" property to equal \"Happy Coder\".');", "assert(/\"name\": \"Coder\"/.test(code), 'message: Do not edit the myDog definition');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Actualiza las propiedades de un objeto en JavaScript", "description": [ "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\".", "

Instrucciones

", "Vamos a actualizar la propiedad del objeto mydog. Cambiemos su nombre de \"Coder\" a \"Happy Coder\"." ] } } }, { "id": "56bbb991ad1ed5201cd392d2", "title": "Add New Properties to a JavaScript Object", "description": [ "You can add new properties to existing JavaScript objects the same way you would modify them.", "Here's how we would add a \"bark\" property to ourDog:", "ourDog.bark = \"bow-wow\"; ", "or", "ourDog[\"bark\"] = \"bow-wow\";", "Now when we evaluate ourDog.bark, we'll get his bark, \"bow-wow\".", "
", "Add a \"bark\" property to myDog and set it to a dog sound, such as \"woof\". You may use either dot or bracket notation." ], "challengeSeed": [ "// Example", "var ourDog = {", " \"name\": \"Camper\",", " \"legs\": 4,", " \"tails\": 1,", " \"friends\": [\"everything!\"]", "};", "", "ourDog.bark = \"bow-wow\";", "", "// Setup", "var myDog = {", " \"name\": \"Happy Coder\",", " \"legs\": 4,", " \"tails\": 1,", " \"friends\": [\"freeCodeCamp Campers\"]", "};", "", "// Only change code below this line.", "" ], "tail": [ "(function(z){return z;})(myDog);" ], "solutions": [ "var myDog = {\n \"name\": \"Happy Coder\",\n \"legs\": 4,\n \"tails\": 1,\n \"friends\": [\"freeCodeCamp Campers\"]\n};\nmyDog.bark = \"Woof Woof\";" ], "tests": [ "assert(myDog.bark !== undefined, 'message: Add the property \"bark\" to myDog.');", "assert(!/bark[^\\n]:/.test(code), 'message: Do not add \"bark\" to the setup section');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Añade nuevas propiedades a un objeto JavaScript", "description": [ "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 \".", "

Instrucciones

", "Vamos a añadir una propiedad ladra a myDog y a ponerle un sonido de perro, tal como \"woof\"." ] } } }, { "id": "56bbb991ad1ed5201cd392d3", "title": "Delete Properties from a JavaScript Object", "description": [ "We can also delete properties from objects like this:", "delete ourDog.bark;", "
", "Delete the \"tails\" property from myDog. You may use either dot or bracket notation." ], "challengeSeed": [ "// Example", "var ourDog = {", " \"name\": \"Camper\",", " \"legs\": 4,", " \"tails\": 1,", " \"friends\": [\"everything!\"],", " \"bark\": \"bow-wow\"", "};", "", "delete ourDog.bark;", "", "// Setup", "var myDog = {", " \"name\": \"Happy Coder\",", " \"legs\": 4,", " \"tails\": 1,", " \"friends\": [\"freeCodeCamp Campers\"],", " \"bark\": \"woof\"", "};", "", "// Only change code below this line.", "", "" ], "tail": [ "(function(z){return z;})(myDog);" ], "solutions": [ "var ourDog = {\n \"name\": \"Camper\",\n \"legs\": 4,\n \"tails\": 1,\n \"friends\": [\"everything!\"],\n \"bark\": \"bow-wow\"\n};\nvar myDog = {\n \"name\": \"Happy Coder\",\n \"legs\": 4,\n \"tails\": 1,\n \"friends\": [\"freeCodeCamp Campers\"],\n \"bark\": \"woof\"\n};\ndelete myDog.tails;" ], "tests": [ "assert(typeof myDog === \"object\" && myDog.tails === undefined, 'message: Delete the property \"tails\" from myDog.');", "assert(code.match(/\"tails\": 1/g).length > 1, 'message: Do not modify the myDog setup');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Elimina propiedades de un objeto JavaScript", "description": [ "También podemos eliminar propiedades de los objetos de esta manera:", "delete ourDog.bark;", "

Instrucciones

", "Borremos la propiedad \"tails\" de myDog." ] } } }, { "id": "56533eb9ac21ba0edf2244ca", "title": "Using Objects for Lookups", "description": [ "Objects can be thought of as a key/value storage, like a dictionary. If you have tabular data, you can use an object to \"lookup\" values rather than a 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\"

var value = 2;
alpha[value]; // \"Y\"
", "
", "Convert the switch statement into a lookup table called lookup. Use it to lookup val and assign the associated string to the result variable." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Setup", "function phoneticLookup(val) {", " var result = \"\";", "", " // Only change code below this line", " switch(val) {", " case \"alpha\": ", " result = \"Adams\";", " break;", " case \"bravo\": ", " result = \"Boston\";", " break;", " case \"charlie\": ", " result = \"Chicago\";", " break;", " case \"delta\": ", " result = \"Denver\";", " break;", " case \"echo\": ", " result = \"Easy\";", " break;", " case \"foxtrot\": ", " result = \"Frank\";", " }", "", " // Only change code above this line", " return result;", "}", "", "// Change this value to test", "phoneticLookup(\"charlie\");" ], "solutions": [ "function phoneticLookup(val) {\n var result = \"\";\n\n var lookup = {\n alpha: \"Adams\",\n bravo: \"Boston\",\n charlie: \"Chicago\",\n delta: \"Denver\",\n echo: \"Easy\",\n foxtrot: \"Frank\"\n };\n\n result = lookup[val];\n\n return result;\n}" ], "tests": [ "assert(phoneticLookup(\"alpha\") === 'Adams', 'message: phoneticLookup(\"alpha\") should equal \"Adams\"');", "assert(phoneticLookup(\"bravo\") === 'Boston', 'message: phoneticLookup(\"bravo\") should equal \"Boston\"');", "assert(phoneticLookup(\"charlie\") === 'Chicago', 'message: phoneticLookup(\"charlie\") should equal \"Chicago\"');", "assert(phoneticLookup(\"delta\") === 'Denver', 'message: phoneticLookup(\"delta\") should equal \"Denver\"');", "assert(phoneticLookup(\"echo\") === 'Easy', 'message: phoneticLookup(\"echo\") should equal \"Easy\"');", "assert(phoneticLookup(\"foxtrot\") === 'Frank', 'message: phoneticLookup(\"foxtrot\") should equal \"Frank\"');", "assert(typeof phoneticLookup(\"\") === 'undefined', 'message: phoneticLookup(\"\") should equal undefined');", "assert(code.match(/return\\sresult;/), 'message: You should not modify the return statement');", "assert(!/case|switch|if/g.test(code), 'message: You should not use case, switch, or if statements'); " ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Usar objetos para búsquedas", "description": [ "Los objetos pueden ser considerados como un almacenamiento llave/valor, como un diccionario. Si tienes datos tabulados, puedes almacenarlos en un objeto para después \"buscar\" valores, en lugar de emplear una sentencia switch o una secuencia de if/else. Esto es más útil cuando sabes que tus datos de entrada son limitados a un cierto rango.", "Aquí está un ejemplo de una simple búsqueda inversa de alfabeto:", "
var alfa = {
1:\"Z\",
2:\"Y\",
3:\"X\",
4:\"W\",
...
24:\"C\",
25:\"B\",
26:\"A\"
};
alfa[2]; // \"Y\"
alfa[24]; // \"C\"

var valor = 2;
alfa[valor]; // \"Y\"
", "

Instrucciones

", "Convierte la sentencia switch en una tabla de búsqueda llamada lookup. Usala para buscar val y asigna la cadena asociada a la variable result." ] } } }, { "id": "567af2437cbaa8c51670a16c", "title": "Testing Objects for Properties", "description": [ "Sometimes it is useful to check if the property of a given object exists or not. We can use the .hasOwnProperty(propname) method of objects to determine if that object has the given property name. .hasOwnProperty() returns true or false if the property is found or not.", "Example", "
var myObj = {
top: \"hat\",
bottom: \"pants\"
};
myObj.hasOwnProperty(\"top\"); // true
myObj.hasOwnProperty(\"middle\"); // false
", "
", "Modify the function checkObj to test myObj for checkProp. If the property is found, return that property's value. If not, return \"Not Found\"." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Setup", "var myObj = {", " gift: \"pony\",", " pet: \"kitten\",", " bed: \"sleigh\"", "};", "", "function checkObj(checkProp) {", " // Your Code Here", " ", " return \"Change Me!\";", "}", "", "// Test your code by modifying these values", "checkObj(\"gift\");" ], "tail": [ "" ], "solutions": [ "var myObj = {\n gift: \"pony\",\n pet: \"kitten\",\n bed: \"sleigh\"\n};\nfunction checkObj(checkProp) {\n if(myObj.hasOwnProperty(checkProp)) {\n return myObj[checkProp];\n } else {\n return \"Not Found\";\n }\n}" ], "tests": [ "assert(checkObj(\"gift\") === \"pony\", 'message: checkObj(\"gift\") should return \"pony\".');", "assert(checkObj(\"pet\") === \"kitten\", 'message: checkObj(\"pet\") should return \"kitten\".');", "assert(checkObj(\"house\") === \"Not Found\", 'message: checkObj(\"house\") should return \"Not Found\".');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Probar si un objeto tiene cierta propiedad", "description": [ "A veces es útil revisar si cierta propiedad existe o no en un objeto dado. Podemos usar el método de objetos .hasOwnProperty(nomprop) para determinar si un objeto tiene la propiedad nomprop. .hasOwnProperty() retorna true o false si la propiedad es encontrada o no.", "Ejemplo", "
var miObj = {
arriba: \"sombrero\",
abajo: \"pantalones\"
};
miObj.hasOwnProperty(\"arriba\"); // true
miObj.hasOwnProperty(\"medio\"); // false
", "

Instrucciones

", "Modifica la función checkObj que prueba si myObj tiene la propiedad checkProp. Si la propiedad es encontrada, retorna el valor de esa propiedad. Si no, retorna \"Not Found\"." ] } } }, { "id": "56533eb9ac21ba0edf2244cb", "title": "Manipulating Complex Objects", "description": [ "Sometimes you may want to store data in a flexible Data Structure. A JavaScript object is one way to handle flexible data. They allow for arbitrary combinations of strings, numbers, booleans, arrays, functions, and objects.", "Here's an example of a complex data structure:", "
var ourMusic = [
{
\"artist\": \"Daft Punk\",
\"title\": \"Homework\",
\"release_year\": 1997,
\"formats\": [
\"CD\",
\"Cassette\",
\"LP\"
],
\"gold\": true
}
];
", "This is an array which contains one object inside. The object has various pieces of metadata about an album. It also has a nested \"formats\" array. If you want to add more album records, you can do this by adding records to the top level array.", "Objects hold data in a property, which has a key-value format. In the example above, \"artist\": \"Daft Punk\" is a property that has a key of \"artist\" and a value of \"Daft Punk\".", "JavaScript Object Notation or JSON is a related data interchange format used to store data.", "
{
\"artist\": \"Daft Punk\",
\"title\": \"Homework\",
\"release_year\": 1997,
\"formats\": [
\"CD\",
\"Cassette\",
\"LP\"
],
\"gold\": true
}
", "Note
You will need to place a comma after every object in the array, unless it is the last object in the array.", "
", "Add a new album to the myMusic array. Add artist and title strings, release_year number, and a formats array of strings." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "var myMusic = [", " {", " \"artist\": \"Billy Joel\",", " \"title\": \"Piano Man\",", " \"release_year\": 1973,", " \"formats\": [ ", " \"CS\",", " \"8T\",", " \"LP\"", " ],", " \"gold\": true", " }", " // Add record here", "];", "" ], "tail": [ "(function(x){ if (Array.isArray(x)) { return JSON.stringify(x); } return \"myMusic is not an array\"})(myMusic);" ], "solutions": [ "var myMusic = [\n {\n \"artist\": \"Billy Joel\",\n \"title\": \"Piano Man\",\n \"release_year\": 1973,\n \"formats\": [ \n \"CS\", \n \"8T\", \n \"LP\" ],\n \"gold\": true\n }, \n {\n \"artist\": \"ABBA\",\n \"title\": \"Ring Ring\",\n \"release_year\": 1973,\n \"formats\": [ \n \"CS\", \n \"8T\", \n \"LP\",\n \"CD\",\n ]\n }\n];" ], "tests": [ "assert(Array.isArray(myMusic), 'message: 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(myMusic[1].formats.every(function(item) { return (typeof item === \"string\")}) && myMusic[1].formats.length > 1, 'message: formats should be an array of strings with at least two elements');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Manipula objetos complicados", "description": [ "Los objetos Javascript son flexibles porque permiten Estructuras de Datos con combinaciones arbitrarias de cadenas, números, booleanos, vectores, funciones, y objetos.", "Aquí está un ejemplo de un objeto complicado:", "
var nuestraMusica = [
{
\"artista\": \"Daft Punk\",
\"titulo\": \"Homework\",
\"año_publicacion\": 1997,
\"formatos\": [
\"CD\",
\"Cassette\",
\"LP\" ],
\"oro\": true
}
];
", "Este es un vector de objetos con diversos metadatos acerca de un álbum musical. Además tiene anidado un vector formatos. En el vector de nivel superior, pueden añadirse otros registros del álbum.", "Nota
En vectores que tengan más de un objeto, necesitarás separar un objeto de otro mediante comas.", "

Instrucciones

", "Agrega un nuevo álbum al objeto myMusic. Agrega las cadenas artist y title, el número release_year y un vector de cadenas formats." ] } } }, { "id": "56533eb9ac21ba0edf2244cc", "title": "Accessing Nested Objects", "description": [ "The sub-properties of objects can be accessed by chaining together the dot or bracket notation.", "Here is a nested object:", "
var ourStorage = {
\"desk\": {
\"drawer\": \"stapler\"
},
\"cabinet\": {
\"top drawer\": {
\"folder1\": \"a file\",
\"folder2\": \"secrets\"
},
\"bottom drawer\": \"soda\"
}
};
ourStorage.cabinet[\"top drawer\"].folder2; // \"secrets\"
ourStorage.desk.drawer; // \"stapler\"
", "
", "Access the myStorage object and assign the contents of the glove box property to the gloveBoxContents variable. Use bracket notation for properties with a space in their name." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Setup", "var myStorage = {", " \"car\": {", " \"inside\": {", " \"glove box\": \"maps\",", " \"passenger seat\": \"crumbs\"", " },", " \"outside\": {", " \"trunk\": \"jack\"", " }", " }", "};", "", "var gloveBoxContents = undefined; // Change this line", "" ], "tail": [ "(function(x) { ", " if(typeof x != 'undefined') { ", " return \"gloveBoxContents = \" + x;", " }", " return \"gloveBoxContents is undefined\";", "})(gloveBoxContents);" ], "solutions": [ "var myStorage = { \n \"car\":{ \n \"inside\":{ \n \"glove box\":\"maps\",\n \"passenger seat\":\"crumbs\"\n },\n \"outside\":{ \n \"trunk\":\"jack\"\n }\n }\n};\nvar gloveBoxContents = myStorage.car.inside[\"glove box\"];" ], "tests": [ "assert(gloveBoxContents === \"maps\", 'message: gloveBoxContents should equal \"maps\"');", "assert(/=\\s*myStorage\\.car\\.inside\\[\\s*(\"|')glove box\\1\\s*\\]/g.test(code), 'message: Use dot and bracket notation to access myStorage');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Acceder a objetos anidados", "description": [ "Las sub-propiedades de los objetos pueden ser accesadas mediante encadenamiento de la notación punto o corchete.", "Aquí está un objeto anidado:", "
var nuestroAlmacen = {
\"escritorio\": {
\"cajon\": \"grapadora\"
},
\"armario\": {
\"cajón superior\": {
\"legajador1\": \"un archivo\",
\"legajador2\": \"secretos\"
},
\"cajón inferior\": \"gaseosa\"
}
}
nuestroAlmacen.armario[\"cajón superior\"].legajador2; // \"secretos\"
nuestroAlmacen.escritorio.cajon; // \"grapadora\"
", "

Instrucciones

", "Accede al objeto myStorage para recuperar el contenido de glove box. Usa notación corchete para las propiedades con un espacio en su nombre." ] } } }, { "id": "56533eb9ac21ba0edf2244cd", "title": "Accessing Nested Arrays", "description": [ "As we have seen in earlier examples, 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 = [
{
animalType: \"cat\",
names: [
\"Meowzer\",
\"Fluffy\",
\"Kit-Cat\"
]
},
{
animalType: \"dog\",
names: [
\"Spot\",
\"Bowser\",
\"Frankie\"
]
}
];
ourPets[0].names[1]; // \"Fluffy\"
ourPets[1].names[0]; // \"Spot\"
", "
", "Retrieve the second tree from the variable myPlants using object dot and array bracket notation." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Setup", "var myPlants = [", " { ", " type: \"flowers\",", " list: [", " \"rose\",", " \"tulip\",", " \"dandelion\"", " ]", " },", " {", " type: \"trees\",", " list: [", " \"fir\",", " \"pine\",", " \"birch\"", " ]", " } ", "];", "", "// Only change code below this line", "", "var secondTree = \"\"; // Change this line", "" ], "tail": [ "(function(x) { ", " if(typeof x != 'undefined') { ", " return \"secondTree = \" + x;", " }", " return \"secondTree is undefined\";", "})(secondTree);" ], "solutions": [ "var myPlants = [\n { \n type: \"flowers\",\n list: [\n \"rose\",\n \"tulip\",\n \"dandelion\"\n ]\n },\n {\n type: \"trees\",\n list: [\n \"fir\",\n \"pine\",\n \"birch\"\n ]\n } \n];\n\n// Only change code below this line\n\nvar secondTree = myPlants[1].list[1];" ], "tests": [ "assert(secondTree === \"pine\", 'message: secondTree should equal \"pine\"');", "assert(/=\\s*myPlants\\[1\\].list\\[1\\]/.test(code), 'message: Use dot and bracket notation to access myPlants');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Acceder a vectores anidados", "description": [ "Como hemos visto en ejemplos anteriores, los objetos pueden contener objetos anidados y vectores anidados. De forma similar a acceder a objetos anidados, la notación corchete en vectores puede ser encadenada para acceder a vectores anidados.", "Aquí está un ejemplo de como acceder a un vector anidado:", "
var nuestrasMascotas = {
\"gatos\": [
\"Maullador\",
\"Blandito\",
\"Kit-Cat\"
],
\"perros\": [
\"Mancha\",
\"Bowser\",
\"Frankie\"
]
};
nuestrasMascotas.cats[1]; // \"Blandito\"
nuestrasMascotas.dogs[0]; // \"Mancha\"
", "

Instrucciones

", "Recupera el segundo arbol de la variable myPlants usando notación punto para objetos y notación corchete para vectores." ] } } }, { "id": "56533eb9ac21ba0edf2244cf", "title": "Record Collection", "description": [ "You are given a JSON object representing a part of your musical album collection. Each album has several properties and a unique id number as its key. Not all albums have complete information.", "Write a function which takes an album's id (like 2548), a property prop (like \"artist\" or \"tracks\"), and a value (like \"Addicted to Love\") to modify the data in this collection.", "If prop isn't \"tracks\" and value isn't empty (\"\"), update or set the value for that record album's property.", "Your function must always return the entire collection object.", "There are several rules for handling incomplete data:", "If prop is \"tracks\" but the album doesn't have a \"tracks\" property, create an empty array before adding the new value to the album's corresponding property.", "If prop is \"tracks\" and value isn't empty (\"\"), push the value onto the end of the album's existing tracks array.", "If value is empty (\"\"), delete the given prop property from the album.", "Hints
Use bracket notation when accessing object properties with variables.", "Push is an array method you can read about on Mozilla Developer Network.", "You may refer back to Manipulating Complex Objects Introducing JavaScript Object Notation (JSON) for a refresher." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Setup", "var collection = {", " \"2548\": {", " \"album\": \"Slippery When Wet\",", " \"artist\": \"Bon Jovi\",", " \"tracks\": [ ", " \"Let It Rock\", ", " \"You Give Love a Bad Name\" ", " ]", " },", " \"2468\": {", " \"album\": \"1999\",", " \"artist\": \"Prince\",", " \"tracks\": [ ", " \"1999\", ", " \"Little Red Corvette\" ", " ]", " },", " \"1245\": {", " \"artist\": \"Robert Palmer\",", " \"tracks\": [ ]", " },", " \"5439\": {", " \"album\": \"ABBA Gold\"", " }", "};", "// Keep a copy of the collection for tests", "var collectionCopy = JSON.parse(JSON.stringify(collection));", "", "// Only change code below this line", "function updateRecords(id, prop, value) {", " ", " ", " return collection;", "}", "", "// Alter values below to test your code", "updateRecords(5439, \"artist\", \"ABBA\");", "" ], "tail": [ ";(function(x) { return \"collection = \\n\" + JSON.stringify(x, '\\n', 2); })(collection);" ], "solutions": [ "var collection = {\n 2548: {\n album: \"Slippery When Wet\",\n artist: \"Bon Jovi\",\n tracks: [ \n \"Let It Rock\", \n \"You Give Love a Bad Name\" \n ]\n },\n 2468: {\n album: \"1999\",\n artist: \"Prince\",\n tracks: [ \n \"1999\", \n \"Little Red Corvette\" \n ]\n },\n 1245: {\n artist: \"Robert Palmer\",\n tracks: [ ]\n },\n 5439: {\n album: \"ABBA Gold\"\n }\n};\n// Keep a copy of the collection for tests\nvar collectionCopy = JSON.parse(JSON.stringify(collection));\n\n// Only change code below this line\nfunction updateRecords(id, prop, value) {\n if(value === \"\") delete collection[id][prop];\n else if(prop === \"tracks\") {\n collection[id][prop] = collection[id][prop] || [];\n collection[id][prop].push(value);\n } else {\n collection[id][prop] = value;\n }\n \n return collection;\n}" ], "tests": [ "collection = collectionCopy; assert(updateRecords(5439, \"artist\", \"ABBA\")[5439][\"artist\"] === \"ABBA\", 'message: After updateRecords(5439, \"artist\", \"ABBA\"), artist should be \"ABBA\"');", "assert(updateRecords(5439, \"tracks\", \"Take a Chance on Me\")[5439][\"tracks\"].pop() === \"Take a Chance on Me\", 'message: After updateRecords(5439, \"tracks\", \"Take a Chance on Me\"), tracks should have \"Take a Chance on Me\" as the last element.');", "updateRecords(2548, \"artist\", \"\"); assert(!collection[2548].hasOwnProperty(\"artist\"), 'message: After updateRecords(2548, \"artist\", \"\"), artist should not be set');", "assert(updateRecords(1245, \"tracks\", \"Addicted to Love\")[1245][\"tracks\"].pop() === \"Addicted to Love\", 'message: After updateRecords(1245, \"tracks\", \"Addicted to Love\"), tracks should have \"Addicted to Love\" as the last element.');", "assert(updateRecords(2468, \"tracks\", \"Free\")[2468][\"tracks\"][0] === \"1999\", 'message: After updateRecords(2468, \"tracks\", \"Free\"), tracks should have \"1999\" as the first element.');", "updateRecords(2548, \"tracks\", \"\"); assert(!collection[2548].hasOwnProperty(\"tracks\"), 'message: After updateRecords(2548, \"tracks\", \"\"), tracks should not be set');", "assert(updateRecords(1245, \"album\", \"Riptide\")[1245][\"album\"] === \"Riptide\", 'message: After updateRecords(1245, \"album\", \"Riptide\"), album should be \"Riptide\"');" ], "type": "checkpoint", "challengeType": 1, "translations": { "es": { "title": "Colección de registros", "description": [ "Se te da un objeto que representa (una pequeña parte de) tu colección de grabaciones. Cada álbum es identificado por un número id único y tiene varias propiedades. No todos los álbumes tienen la información completa.", "Escribe una función que reciba un id, una propiedad (prop) y un valor (value).", "Para el id dado, en la colección collection:", "Si el valor value no está en blanco (value !== \"\") y prop no es \"tracks\" entonces actualiza o establece el valor de la propiedad prop.", "Si la propiedad prop es \"tracks\" y value no está en blanco, empuja (push) el valor value al final del vector tracks.", "Si el valor value está en blanco, elimina esa prop.", "Siempre retorna el objeto collection entero.", "Nota
No olvides usar notación corchete cuando accedes a propiedades de objetos con variables." ] } } }, { "id": "cf1111c1c11feddfaeb1bdef", "title": "Iterate with JavaScript While Loops", "description": [ "You can run the same code multiple times by using a loop.", "Another type of JavaScript loop is called a \"while loop\", because it runs \"while\" a specified condition is true and stops once that condition is no longer true.", "
var ourArray = [];
var i = 0;
while(i < 5) {
ourArray.push(i);
i++;
}
", "Let's try getting a while loop to work by pushing values to an array.", "
", "Push the numbers 0 through 4 to myArray using a while loop." ], "challengeSeed": [ "// Setup", "var myArray = [];", "", "// Only change code below this line.", "", "" ], "tail": [ "if(typeof myArray !== \"undefined\"){(function(){return myArray;})();}" ], "solutions": [ "var myArray = [];\nvar i = 0;\nwhile(i < 5) {\n myArray.push(i);\n i++;\n}" ], "tests": [ "assert(code.match(/while/g), 'message: You should be using a while loop for this.');", "assert.deepEqual(myArray, [0,1,2,3,4], 'message: myArray should equal [0,1,2,3,4].');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Iterar con JavaScript con ciclos while", "description": [ "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.", "

Instrucciones

", "Empuja los números de 0 a 4 para myArray utilizando un ciclo while." ] } } }, { "id": "cf1111c1c11feddfaeb5bdef", "title": "Iterate with JavaScript For Loops", "description": [ "You can run the same code multiple times by using a loop.", "The most common type of JavaScript loop is called a \"for loop\" because it runs \"for\" a specific number of times.", "For loops are declared with three optional expressions separated by semicolons:", "for ([initialization]; [condition]; [final-expression])", "The initialization statement is executed one time only before the loop starts. It is typically used to define and setup your loop variable.", "The condition statement is evaluated at the beginning of every loop iteration and will continue as long as it evaluates 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);
}
", "ourArray will now contain [0,1,2,3,4].", "
", "Use a for loop to work to push the values 1 through 5 onto myArray." ], "challengeSeed": [ "// Example", "var ourArray = [];", "", "for (var i = 0; i < 5; i++) {", " ourArray.push(i);", "}", "", "// Setup", "var myArray = [];", "", "// Only change code below this line.", "", "" ], "tail": [ "if (typeof myArray !== \"undefined\"){(function(){return myArray;})();}" ], "solutions": [ "var ourArray = [];\nfor (var i = 0; i < 5; i++) {\n ourArray.push(i);\n}\nvar myArray = [];\nfor (var i = 1; i < 6; i++) {\n myArray.push(i);\n}" ], "tests": [ "assert(code.match(/for\\s*\\(/g).length > 1, 'message: You should be using a for loop for this.');", "assert.deepEqual(myArray, [1,2,3,4,5], 'message: myArray should equal [1,2,3,4,5].');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Iterar en JavaScript con ciclos for", "description": [ "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].", "

Instrucciones

", "Vamos a utilizar un ciclo for para empujar los valores del 1 al 5 en myArray." ] } } }, { "id": "56104e9e514f539506016a5c", "title": "Iterate Odd Numbers With a For Loop", "description": [ "For loops don't have to iterate one at a time. By changing our 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);
}
", "ourArray will now contain [0,2,4,6,8].", "Let's change our initialization so we can count by odd numbers.", "
", "Push the odd numbers from 1 through 9 to myArray using a for loop." ], "challengeSeed": [ "// Example", "var ourArray = [];", "", "for (var i = 0; i < 10; i += 2) {", " ourArray.push(i);", "}", "", "// Setup", "var myArray = [];", "", "// Only change code below this line.", "", "" ], "tail": [ "if(typeof myArray !== \"undefined\"){(function(){return myArray;})();}" ], "solutions": [ "var ourArray = [];\nfor (var i = 0; i < 10; i += 2) {\n ourArray.push(i);\n}\nvar myArray = [];\nfor (var i = 1; i < 10; i += 2) {\n myArray.push(i);\n}" ], "tests": [ "assert(code.match(/for\\s*\\(/g).length > 1, 'message: You should be using a for loop for this.');", "assert.deepEqual(myArray, [1,3,5,7,9], 'message: myArray should equal [1,3,5,7,9].');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Itera por los números pares con un ciclo for", "description": [ "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.", "

Instrucciones

", "Empuja los números impares del 1 al 9 en myArray utilizando un ciclo for." ] } } }, { "id": "56105e7b514f539506016a5e", "title": "Count Backwards With a For Loop", "description": [ "A for loop can also count backwards, so long as we can define the right conditions.", "In order to count backwards by twos, we'll need to change our 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);
}
", "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." ], "challengeSeed": [ "// Example", "var ourArray = [];", "", "for (var i = 10; i > 0; i -= 2) {", " ourArray.push(i);", "}", "", "// Setup", "var myArray = [];", "", "// Only change code below this line.", "", "" ], "tail": [ "if(typeof myArray !== \"undefined\"){(function(){return myArray;})();}" ], "solutions": [ "var ourArray = [];\nfor (var i = 10; i > 0; i -= 2) {\n ourArray.push(i);\n}\nvar myArray = [];\nfor (var i = 9; i > 0; i -= 2) {\n myArray.push(i);\n}" ], "tests": [ "assert(code.match(/for\\s*\\(/g).length > 1, 'message: You should be using a for loop for this.');", "assert(code.match(/myArray.push/), 'message: You should be using the array method push.');", "assert.deepEqual(myArray, [9,7,5,3,1], 'message: myArray should equal [9,7,5,3,1].');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Cuenta hacia atrás con un ciclo for", "description": [ "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.", "

Instrucciones

", "Empuja los números impares del 9 a 1 en myArray utilizando un ciclo for." ] } } }, { "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.", "
", "Declare and initialize a variable total to 0. Use a for loop to add the value of each element of the myArr array to total." ], "releasedOn": "January 1, 2016", "challengeSeed": [ "// Example", "var ourArr = [ 9, 10, 11, 12];", "var ourTotal = 0;", "", "for (var i = 0; i < ourArr.length; i++) {", " ourTotal += ourArr[i];", "}", "", "// Setup", "var myArr = [ 2, 3, 4, 5, 6];", "", "// Only change code below this line", "", "" ], "tail": [ "(function(){if(typeof total !== 'undefined') { return \"total = \" + total; } else { return \"total is undefined\";}})()" ], "solutions": [ "var ourArr = [ 9, 10, 11, 12];\nvar ourTotal = 0;\n\nfor (var i = 0; i < ourArr.length; i++) {\n ourTotal += ourArr[i];\n}\n\nvar myArr = [ 2, 3, 4, 5, 6];\nvar total = 0;\n\nfor (var i = 0; i < myArr.length; i++) {\n total += myArr[i];\n}" ], "tests": [ "assert(code.match(/var.*?total\\s*=\\s*0.*?;/), 'message: total should be declared and initialized to 0');", "assert(total === 20, 'message: total should equal 20');", "assert(code.match(/for\\s*\\(/g).length > 1 && code.match(/myArr\\s*\\[/), 'message: You should use a for loop to iterate through myArr');", "assert(!code.match(/total[\\s\\+\\-]*=\\s*(\\d(?!\\s*[;,])|[1-9])/g), 'message: Do not set total to 20 directly');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Iterar a través de un vector con un ciclo for", "description": [ "Una tarea común en JavaScript es iterar a traves del contenido de un vector. Una manera de hacerlo es con un ciclo for. Este código imprimirá cada elemento del vector arr en la consola:", "
var arr = [10,9,8,7,6];
for (var i=0; i < arr.length; i++) {
console.log(arr[i]);
}
", "Recuerda que los vectores tienen numeración que comienza en cero, la cual significa que el último índice del vector es su longitud - 1. Nuestra condición para este ciclo es i < arr.length, que lo detendrá cuando i sea la longitud - 1.", "

Instrucciones

", "Declara e inicializa una variable total en 0. Usa un ciclo for para añadir el valor de cada elemento del vector myArr a total." ] } } }, { "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; j < 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.", "
", "Modify function multiplyAll so that it multiplies the product variable by each number in the sub-arrays of arr" ], "releasedOn": "January 1, 2016", "challengeSeed": [ "function multiplyAll(arr) {", " var product = 1;", " // Only change code below this line", " ", " // Only change code above this line", " return product;", "}", "", "// Modify values below to test your code", "multiplyAll([[1,2],[3,4],[5,6,7]]);", "" ], "tail": [ "" ], "solutions": [ "function multiplyAll(arr) {\n var product = 1;\n for (var i = 0; i < arr.length; i++) {\n for (var j = 0; j < arr[i].length; j++) {\n product *= arr[i][j];\n }\n }\n return product;\n}\n\nmultiplyAll([[1,2],[3,4],[5,6,7]]);" ], "tests": [ "assert(multiplyAll([[1],[2],[3]]) === 6, 'message: multiplyAll([[1],[2],[3]]) should return 6');", "assert(multiplyAll([[1,2],[3,4],[5,6,7]]) === 5040, 'message: multiplyAll([[1,2],[3,4],[5,6,7]]) should return 5040');", "assert(multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]]) === 54, 'message: multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]]) should return 54');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Anidar ciclos for", "description": [ "Si tienes una matriz multi-dimensional, puedes usar la misma lógica del punto anterior para iterar a través de un vector y cualquier sub-vector. Aquí está un ejemplo:", "
var arr = [
[1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) {
console.log(arr[i][j]);
}
}
", "Esto imprime cada sub-elemento en arr uno a la vez. Nota que en el ciclo interior, estamos comprobando la longitud .length de arr[i], ya que arr[i] es por si mismo un vector.", "

Instrucciones

", "Modifica la función multiplyAll de manera que esta multiplique la variable product por cada número en los sub-vectores de arr" ] } } }, { "id": "5688e62ea601b2482ff8422b", "title": "Profile Lookup", "description": [ "We have an array of objects representing different people in our contacts lists.", "A lookUpProfile function that takes name and a property (prop) as arguments has been pre-written for you.", "The function should check if name is an actual contact's firstName and the given property (prop) is a property of that contact.", "If both are true, then return the \"value\" of that property.", "If name does not correspond to any contacts then return \"No such contact\"", "If prop does not correspond to any valid properties of a contact found to match name then return \"No such property\"" ], "releasedOn": "January 8, 2016", "challengeSeed": [ "//Setup", "var contacts = [", " {", " \"firstName\": \"Akira\",", " \"lastName\": \"Laine\",", " \"number\": \"0543236543\",", " \"likes\": [\"Pizza\", \"Coding\", \"Brownie Points\"]", " },", " {", " \"firstName\": \"Harry\",", " \"lastName\": \"Potter\",", " \"number\": \"0994372684\",", " \"likes\": [\"Hogwarts\", \"Magic\", \"Hagrid\"]", " },", " {", " \"firstName\": \"Sherlock\",", " \"lastName\": \"Holmes\",", " \"number\": \"0487345643\",", " \"likes\": [\"Intriguing Cases\", \"Violin\"]", " },", " {", " \"firstName\": \"Kristian\",", " \"lastName\": \"Vos\",", " \"number\": \"unknown\",", " \"likes\": [\"Javascript\", \"Gaming\", \"Foxes\"]", " }", "];", "", "", "function lookUpProfile(name, prop){", "// Only change code below this line", "", "// Only change code above this line", "}", "", "// Change these values to test your function", "lookUpProfile(\"Akira\", \"likes\");" ], "solutions": [ "var contacts = [\n {\n \"firstName\": \"Akira\",\n \"lastName\": \"Laine\",\n \"number\": \"0543236543\",\n \"likes\": [\"Pizza\", \"Coding\", \"Brownie Points\"]\n },\n {\n \"firstName\": \"Harry\",\n \"lastName\": \"Potter\",\n \"number\": \"0994372684\",\n \"likes\": [\"Hogwarts\", \"Magic\", \"Hagrid\"]\n },\n {\n \"firstName\": \"Sherlock\",\n \"lastName\": \"Holmes\",\n \"number\": \"0487345643\",\n \"likes\": [\"Intriguing Cases\", \"Violin\"]\n },\n {\n \"firstName\": \"Kristian\",\n \"lastName\": \"Vos\",\n \"number\": \"unknown\",\n \"likes\": [\"Javascript\", \"Gaming\", \"Foxes\"]\n },\n];\n\n\n//Write your function in between these comments\nfunction lookUpProfile(name, prop){\n for(var i in contacts){\n if(contacts[i].firstName === name) {\n return contacts[i][prop] || \"No such property\";\n }\n }\n return \"No such contact\";\n}\n//Write your function in between these comments\n\nlookUpProfile(\"Akira\", \"likes\");" ], "tests": [ "assert(lookUpProfile('Kristian','lastName') === \"Vos\", 'message: \"Kristian\", \"lastName\" should return \"Vos\"');", "assert.deepEqual(lookUpProfile(\"Sherlock\", \"likes\"), [\"Intriguing Cases\", \"Violin\"], 'message: \"Sherlock\", \"likes\" should return [\"Intriguing Cases\", \"Violin\"]');", "assert(typeof lookUpProfile(\"Harry\", \"likes\") === \"object\", 'message: \"Harry\",\"likes\" should return an array');", "assert(lookUpProfile(\"Bob\", \"number\") === \"No such contact\", 'message: \"Bob\", \"number\" should return \"No such contact\"');", "assert(lookUpProfile(\"Bob\", \"potato\") === \"No such contact\", 'message: \"Bob\", \"potato\" should return \"No such contact\"');", "assert(lookUpProfile(\"Akira\", \"address\") === \"No such property\", 'message: \"Akira\", \"address\" should return \"No such property\"');" ], "type": "checkpoint", "challengeType": 1, "translations": { "es": { "title": "Búsqueda de perfiles", "description": [ "Tenemos un vector de objetos que representan diferentes personas en nuestra lista de contactos.", "Una función lookUp que recibe el nombre (firstName) y una propiedad (prop) como argumentos ya ha sido escrita previamente para ti.", "La función debe comprobar si firstName es un nombre (firstName) de algún contacto y si la propiedad dada (prop) es una propiedad de ese contacto.", "Si ambos son verdaderos, entonces retorna el valor (value) de esa propiedad.", "Si firstName no corresponde a ningun contacto entonces retorna \"No such contact\"", "Si prop no corresponde a ninguna propiedad válida entonces retorna \"No such property\"", "" ] } } }, { "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 (inclusive) and not quite up to 1 (exclusive). Thus Math.random() can return a 0 but never quite return a 1", "Note
Like Storing Values with the Equal Operator, all function calls will be resolved before the return executes, so we can return the value of the Math.random() function.", "
", "Change randomFraction to return a random number instead of returning 0." ], "challengeSeed": [ "function randomFraction() {", "", " // Only change code below this line.", "", " return 0;", "", " // Only change code above this line.", "}" ], "tail": [ "(function(){return randomFraction();})();" ], "solutions": [ "function randomFraction() {\n return Math.random();\n}" ], "tests": [ "assert(typeof randomFraction() === \"number\", 'message: randomFraction should return a random number.');", "assert((randomFraction()+''). match(/\\./g), 'message: The number returned by randomFraction should be a decimal.');", "assert(code.match(/Math\\.random/g).length >= 0, 'message: You should be using Math.random to generate the random decimal number.');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Generar fracciones al azar con JavaScript", "description": [ "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.", "

Instrucciones

", "Cambia randomFraction 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." ] } } }, { "id": "cf1111c1c12feddfaeb1bdef", "title": "Generate Random Whole Numbers with JavaScript", "description": [ "It's great that we can generate random decimal numbers, but it's even more useful if we use it to generate random whole numbers.", "
  1. Use Math.random() to generate a random decimal.
  2. Multiply that random decimal by 20.
  3. Use another function, Math.floor() to round the number down to its nearest whole number.
", "Remember that Math.random() can never quite return a 1 and, because we're rounding down, it's impossible to actually get 20. This technique will give us a whole number between 0 and 19.", "Putting everything together, this is what our code looks like:", "Math.floor(Math.random() * 20);", "We are calling Math.random(), multiplying the result by 20, then passing the value to Math.floor() function to round the value down to the nearest whole number.", "
", "Use this technique to generate and return a random whole number between 0 and 9." ], "challengeSeed": [ "var randomNumberBetween0and19 = Math.floor(Math.random() * 20);", "", "function randomWholeNum() {", "", " // Only change code below this line.", "", " return Math.random();", "}" ], "tail": [ "(function(){return randomWholeNum();})();" ], "solutions": [ "var randomNumberBetween0and19 = Math.floor(Math.random() * 20);\nfunction randomWholeNum() {\n return Math.floor(Math.random() * 10);\n}" ], "tests": [ "assert(typeof randomWholeNum() === \"number\" && (function(){var r = randomWholeNum();return Math.floor(r) === r;})(), 'message: The result of randomWholeNum should be a whole number.');", "assert(code.match(/Math.random/g).length > 1, 'message: You should be using Math.random to generate a random number.');", "assert(code.match(/\\s*?Math.random\\s*?\\(\\s*?\\)\\s*?\\*\\s*?10[\\D]\\s*?/g) || code.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(code.match(/Math.floor/g).length > 1, 'message: You should use Math.floor to remove the decimal part of the number.');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Genera números aleatorios enteros con JavaScript", "description": [ "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.", "

Instrucciones

", "Usa esta técnica para generar y devolver un número entero aleatorio entre 0 y 9." ] } } }, { "id": "cf1111c1c12feddfaeb2bdef", "title": "Generate Random Whole Numbers within a Range", "description": [ "Instead of generating a random number between zero and a given number like we did before, we can generate a random number that falls within a range of two specific numbers.", "To do this, we'll define a minimum number min and a maximum number max.", "Here's the formula we'll use. Take a moment to read it and try to understand what this code is doing:", "Math.floor(Math.random() * (max - min + 1)) + min", "
", "Create a function called randomRange that takes a range myMin and myMax and returns a random number that's greater than or equal to myMin, and is less than or equal to myMax, inclusive." ], "challengeSeed": [ "// Example", "function ourRandomRange(ourMin, ourMax) {", "", " return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin;", "}", "", "ourRandomRange(1, 9);", "", "// Only change code below this line.", "", "function randomRange(myMin, myMax) {", "", " return 0; // Change this line", "", "}", "", "// Change these values to test your function", "var myRandom = randomRange(5, 15);" ], "tail": [ "var calcMin = 100;", "var calcMax = -100;", "for(var i = 0; i < 100; i++) {", " var result = randomRange(5,15);", " calcMin = Math.min(calcMin, result);", " calcMax = Math.max(calcMax, result);", "}", "(function(){", " if(typeof myRandom === 'number') {", " return \"myRandom = \" + myRandom;", " } else {", " return \"myRandom undefined\";", " }", "})();" ], "solutions": [ "function randomRange(myMin, myMax) {\n return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;\n}" ], "tests": [ "assert(calcMin === 5, 'message: The lowest random number that can be generated by randomRange should be equal to your minimum number, myMin.');", "assert(calcMax === 15, 'message: The highest random number that can be generated by randomRange should be equal to your maximum number, myMax.');", "assert(randomRange(0,1) % 1 === 0 , 'message: The random number generated by randomRange should be an integer, not a decimal.');", "assert((function(){if(code.match(/myMax/g).length > 1 && code.match(/myMin/g).length > 2 && code.match(/Math.floor/g) && code.match(/Math.random/g)){return true;}else{return false;}})(), 'message: randomRange should use both myMax and myMin, and return a random number in your range.');" ], "type": "waypoint", "challengeType": 1, "translations": { "es": { "title": "Genera números aleatorios enteros dentro de un rango", "description": [ "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.", "

Instrucciones

", "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": "587d7b7e367417b2b2512b23", "title": "Use the parseInt Function", "description": [ "The parseInt() function parses a string and returns an integer. Here's an example:", "var a = parseInt(\"007\");", "The above function converts the string \"007\" to an integer 7. If the first character in the string can't be converted into a number, then it returns NaN.", "
", "Use parseInt() in the convertToInteger function so it converts the input string str into an integer, and returns it." ], "challengeSeed": [ "function convertToInteger(str) {", " ", "}", "", "convertToInteger(\"56\");" ], "tail": [], "solutions": [], "tests": [ "assert(/parseInt/g.test(code), 'message: convertToInteger should use the parseInt() function');", "assert(typeof(convertToInteger(\"56\")) === \"number\", 'message: convertToInteger(\"56\") should return a number');", "assert(convertToInteger(\"56\") === 56, 'message: convertToInteger(\"56\") should return 56');", "assert(convertToInteger(\"77\") === 77, 'message: convertToInteger(\"77\") should return 77');", "assert.isNaN(convertToInteger(\"JamesBond\"), 'message: convertToInteger(\"JamesBond\") should return NaN');" ], "type": "waypoint", "challengeType": 1, "translations": {}, "releasedOn": "February 17, 2017" }, { "id": "587d7b7e367417b2b2512b22", "title": "Use the parseInt Function with a Radix", "description": [ "The parseInt() function parses a string and returns an integer. It takes a second argument for the radix, which specifies the base of the number in the string. The radix can be an integer between 2 and 36.", "The function call looks like:", "parseInt(string, radix);", "And here's an example:", "var a = parseInt(\"11\", 2);", "The radix variable says that \"11\" is in the binary system, or base 2. This example converts the string \"11\" to an integer 3.", "
", "Use parseInt() in the convertToInteger function so it converts a binary number to an integer and returns it." ], "challengeSeed": [ "function convertToInteger(str) {", " ", "}", "", "convertToInteger(\"10011\");" ], "tail": [], "solutions": [], "tests": [ "assert(/parseInt/g.test(code), 'message: convertToInteger should use the parseInt() function');", "assert(typeof(convertToInteger(\"10011\")) === \"number\", 'message: convertToInteger(\"10011\") should return a number');", "assert(convertToInteger(\"10011\") === 19, 'message: convertToInteger(\"10011\") should return 19');", "assert(convertToInteger(\"111001\") === 57, 'message: convertToInteger(\"111001\") should return 57');", "assert.isNaN(convertToInteger(\"JamesBond\"), 'message: convertToInteger(\"JamesBond\") should return NaN');" ], "type": "waypoint", "challengeType": 1, "releasedOn": "February 17, 2017", "translations": {} }, { "id": "587d7b7e367417b2b2512b24", "title": "Use the Conditional (Ternary) Operator", "description": [ "The conditional operator, also called the ternary operator, can be used as a one line if-else expression.", "The syntax is:", "condition ? statement-if-true : statement-if-false;", "The following function uses an if-else statement to check a condition:", "
function findGreater(a, b) {
if(a > b) {
return \"a is greater\";
}
else {
return \"b is greater\";
}
}
", "This can be re-written using the conditional operator:", "
function findGreater(a, b) {
return a > b ? \"a is greater\" : \"b is greater\";
}
", "
", "Use the conditional operator in the checkEqual function to check if two numbers are equal or not. The function should return either true or false." ], "challengeSeed": [ "function checkEqual(a, b) {", " ", "}", "", "checkEqual(1, 2);" ], "tail": [], "solutions": [], "tests": [ "assert(/.+?\\s*?\\?\\s*?.+?\\s*?:\\s*?.+?/gi.test(code), 'message: checkEqual should use the conditional operator');", "assert(checkEqual(1, 2) === false, 'message: checkEqual(1, 2) should return false');", "assert(checkEqual(1, 1) === true, 'message: checkEqual(1, 1) should return true');", "assert(checkEqual(1, -1) === false, 'message: checkEqual(1, -1) should return false');" ], "type": "waypoint", "challengeType": 1, "releasedOn": "February 17, 2017", "translations": {} }, { "id": "587d7b7e367417b2b2512b21", "title": "Use Multiple Conditional (Ternary) Operators", "description": [ "In the previous challenge, you used a single conditional operator. You can also chain them together to check for multiple conditions.", "The following function uses if, else if, and else statements to check multiple conditions:", "
function findGreaterOrEqual(a, b) {
if(a === b) {
return \"a and b are equal\";
}
else if(a > b) {
return \"a is greater\";
}
else {
return \"b is greater\";
}
}
", "The above function can be re-written using multiple conditional operators:", "
function findGreaterOrEqual(a, b) {
return (a === b) ? \"a and b are equal\" : (a > b) ? \"a is greater\" : \"b is greater\";
}
", "
", "Use multiple conditional operators in the checkSign function to check if a number is positive, negative or zero." ], "challengeSeed": [ "function checkSign(num) {", " ", "}", "", "checkSign(10);" ], "tail": [], "solutions": [], "tests": [ "assert(/.+?\\s*?\\?\\s*?.+?\\s*?:\\s*?.+?\\s*?\\?\\s*?.+?\\s*?:\\s*?.+?/gi.test(code), 'message: checkSign should use multiple conditional operators');", "assert(checkSign(10) === 'positive', 'message: checkSign(10) should return \"positive\". Note that capitalization matters');", "assert(checkSign(-12) === 'negative', 'message: checkSign(-12) should return \"negative\". Note that capitalization matters');", "assert(checkSign(0) === 'zero', 'message: checkSign(0) should return \"zero\". Note that capitalization matters');" ], "type": "waypoint", "challengeType": 1, "releasedOn": "February 17, 2017", "translations": {} } ] }