"Comments are lines of code that JavaScript will intentionally ignore. Comments are a great way to leave notes to yourself and to other people who will later need to figure out what that code does.",
"There are two ways to write comments in JavaScript:",
"Using <code>//</code> will tell JavaScript to ignore the remainder of the text on the current line:",
"<blockquote>// This is an in-line comment.</blockquote>",
"You can make a multi-line comment beginning with <code>/*</code> and ending with <code>*/</code>:",
"<blockquote>/* This is a <br> multi-line comment */</blockquote>",
"<strong>Best Practice</strong><br>As you write code, you should regularly add comments to clarify the function of parts of your code. Good commenting can help communicate the intent of your code—both for others <em>and</em> for your future self.",
"assert(code.match(/(\\/\\*)([^\\*\\/]{5,})(?=\\*\\/)/gm), 'message: Create a <code>/* */</code> style comment that contains at least five letters.');"
"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:",
"<code>// Este es un comentario.</code>",
"El comentario de barra-estrella-estrella-barra, comentará todo lo que haya entre los caracteres <code>/*</code> y <code>*/</code>:",
"<code>/* Este es también un comentario */</code>",
"Trata de crear uno de cada uno."
]
},
"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 <code>//</code> indiquera à JavaScript d'ignorer le reste du texte sur cette même ligne:",
"<code>// Voici un commentaire sur une ligne.</code>",
"Vous pouvez commenter plusieurs lignes en commençant par <code>/*</code> et en finissant par <code>*/</code>:",
"<code>/*Voici un commentaire <br> sur plusieurs lignes */</code>",
"<strong>Conseils</strong>",
"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 <em>et</em> vous-même à mieux comprendre votre code.",
"In computer science, <dfn>data</dfn> is anything that is meaningful to the computer. JavaScript provides seven different <dfn>data types</dfn> which are <code>undefined</code>, <code>null</code>, <code>boolean</code>, <code>string</code>, <code>symbol</code>, <code>number</code>, and <code>object</code>.",
"For example, computers distinguish between numbers, such as the number <code>12</code>, and <code>strings</code>, such as <code>\"12\"</code>, <code>\"dog\"</code>, or <code>\"123 cats\"</code>, which are collections of characters. Computers can perform mathematical operations on a number, but not on a string.",
"<dfn>Variables</dfn> 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.",
"<code>Variables</code> are similar to the x and y variables you use in mathematics, which means they're a simple name to represent the data we want to refer to. Computer <code>variables</code> differ from mathematical variables in that they can store different values at different times.",
"We tell JavaScript to create or <dfn>declare</dfn> a variable by putting the keyword <code>var</code> in front of it, like so:",
"<blockquote>var ourName;</blockquote>",
"creates a <code>variable</code> called <code>ourName</code>. In JavaScript we end statements with semicolons.",
"<code>Variable</code> names can be made up of numbers, letters, and <code>$</code> or <code>_</code>, but may not contain spaces or start with a number.",
"assert(/var\\s+myName\\s*;/.test(code), 'message: You should declare <code>myName</code> with the <code>var</code> keyword, ending with a semicolon');"
"Cuando almacenamos datos en una <code>estructura de datos</code>, la llamamos una <code>variable</code>. Estas variables no son diferentes de las variables x e y que utilizas en matemáticas. ",
"Vamos a crear nuestra primera variable y a llamarla \"myName\".",
"Te darás cuenta que en <code>myName</code>, no usamos un espacio, y que la \" N\"se escribe con mayúscula. Las variables en JavaScript se escriben con <code>capitalización camello (camel case)</code>. Un ejemplo de capitalización camello: capitalizacionCamello.",
"Ahora, utiliza la palabra clave <code>var</code> para crear una variable llamada <code>myName</code>. Establecele como valor tu nombre, entre comillas dobles. ",
"Mira el ejemplo con <code>ourName</code> si te quedas atascado."
]
},
"fr":{
"title":"Déclarer des variables en JavaScript",
"description":[
"En informatique, une <dfn>donnée</dfn> comporte tout ce qui peut avoir du sens pour l'ordinateur. Javascript dispose de sept <code>types de données</code> différents qui sont <code>undefined</code>, <code>null</code>, <code>boolean</code>, <code>string</code>, <code>symbol</code>, <code>number</code> et <code>object</code>.",
"Par exemple, les ordinateurs font la différence entre les nombres tel que <code>12</code> et les <code>strings</code>, tels que <code>\"12\"</code>, <code>\"dog\"</code>, ou <code>\"123 cats\"</code>, 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 <dfn>variables</dfn> permettent aux ordinateurs de stocker et manipuler les données de façon dynamique. Ils font cela en utilisant un <blockquote>label</blockquote> 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 <code>variables</code> 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 <code>variables</code> 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 <code>déclarer</code> une variable en la précédant du mot-clé <code>var</code>, comme ceci:",
"<code>var notreNom</code>;",
"crée une <code>variable</code> appelée <code>notreNom</code>.On termine nos expressions avec un point virgule en JavaScript.",
"Le nom d'une <code>variable</code> peut être composé de nombres, lettres et <code>$</code> ou <code>_</code>, mais ne peut contenir d'espaces ou commencer par un nombre.",
"Assignment always goes from right to left. Everything to the right of the <code>=</code> operator is resolved before the value is assigned to the variable to the left of the operator.",
"This assigns <code>5</code> to <code>myVar</code> and then resolves <code>myVar</code> to <code>5</code> again and assigns it to <code>myNum</code>.",
"title":"Almacenar valores con el operador igual",
"description":[
"En JavaScript, puedes almacenar un valor en una variable con la <dfn>asignación</dfn> o con el operador <code>igual</code> (<code>=</code>).",
"<code>miVariable = 5;</code>",
"Asigna el valor <code>númerico</code> de <code>5</code> a <code>miVariable</code>.",
"La asignación siempre va de derecha a izquierda. Todo a la derecha del operador <code>=</code> es resuelto antes que el valor es asignado a la variable a la izquierda del operador.",
"When JavaScript variables are declared, they have an initial value of <code>undefined</code>. If you do a mathematical operation on an <code>undefined</code> variable your result will be <code>NaN</code> which means <dfn>\"Not a Number\"</dfn>. If you concatenate a string with an <code>undefined</code> variable, you will get a literal <dfn>string</dfn> of <code>\"undefined\"</code>.",
"Initialize the three variables <code>a</code>, <code>b</code>, and <code>c</code> with <code>5</code>, <code>10</code>, and <code>\"I am a\"</code> respectively so that they will not be <code>undefined</code>."
"assert(typeof a === 'number' && a === 6, 'message: <code>a</code> should be defined and have a value of <code>6</code>');",
"assert(typeof b === 'number' && b === 15, 'message: <code>b</code> should be defined and have a value of <code>15</code>');",
"assert(!/undefined/.test(c) && c === \"I am a String!\", 'message: <code>c</code> should not contain <code>undefined</code> and should have a value of \"I am a String!\"');",
"assert(/a = a \\+ 1;/.test(code) && /b = b \\+ 5;/.test(code) && /c = c \\+ \" String!\";/.test(code), 'message: Do not change code below the line');"
"Cuando las variables de JavaScript son declaradas, ellas tienen un valor inicial de <code>undefined</code>. Si tu haces una operación matematica sobre una variable <code>undefined</code> tu resultado sera <code>NaN</code> el cual significa <dfn>\"Not a Number\"</dfn> es decir \"No es un número\". Si tu concatenas una cadena con una variable <code>undefined</code>, vas a obtener una <dfn>cadena</dfn> literal de <code>\"undefined\"</code>.",
"<h4>Instrucciones</h4>",
"Inicializa las tres variables <code>a</code>, <code>b</code>, y <code>c</code> con <code>5</code>, <code>10</code>, y <code>\"I am a\"</code> respectivamente de manera que no sean <code>undefined</code>."
"In JavaScript all variables and function names are case sensitive. This means that capitalization matters.",
"<code>MYVAR</code> is not the same as <code>MyVar</code> nor <code>myvar</code>. It is possible to have multiple distinct variables with the same name but different casing. It is strongly recommended that for the sake of clarity, you <em>do not</em> use this language feature.",
"Write variable names in Javascript in <dfn>camelCase</dfn>. In <dfn>camelCase</dfn>, multi-word variable names have the first word in lowercase and the first letter of each subsequent word is capitalized.",
"assert(typeof studlyCapVar !== 'undefined' && studlyCapVar === 10, 'message: <code>studlyCapVar</code> is defined and has a value of <code>10</code>');",
"assert(typeof properCamelCase !== 'undefined' && properCamelCase === \"A String\", 'message: <code>properCamelCase</code> is defined and has a value of <code>\"A String\"</code>');",
"assert(typeof titleCaseOver !== 'undefined' && titleCaseOver === 9000, 'message: <code>titleCaseOver</code> is defined and has a value of <code>9000</code>');",
"assert(code.match(/studlyCapVar/g).length === 2, 'message: <code>studlyCapVar</code> should use camelCase in both declaration and assignment sections.');",
"assert(code.match(/properCamelCase/g).length === 2, 'message: <code>properCamelCase</code> should use camelCase in both declaration and assignment sections.');",
"assert(code.match(/titleCaseOver/g).length === 2, 'message: <code>titleCaseOver</code> should use camelCase in both declaration and assignment sections.');"
"En JavaScript todas las variables y nombres de funciones distinguen entre mayúsculas y minúsculas. Esto significa que la capitalización importa.",
"<code>MIVAR</code> no es lo mismo que <code>MiVar</code> o <code>mivar</code>. 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 <em>no</em> uses esta característica del lenguaje.",
"<h4>Mejor Práctica</h4>",
"Escribe nombres de variables en Javascript en <dfn>capitalizaciónCamello (camelCase)</dfn>. En <dfn>capitalizaciónCamello</dfn>, 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.",
"Change the code to use the <code>++</code> operator on <code>myVar</code>.",
"<strong>Hint</strong><br>Learn more about <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment_()\" target=\"_blank\">Arithmetic operators - Increment (++)</a>."
"<strong>Note</strong><br>Not all real numbers can accurately be represented in <dfn>floating point</dfn>. This can lead to rounding errors. <a href=\"https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems\" target=\"_blank\">Details Here</a>.",
"Podemos almacenar números decimales en variables también. Los números decimales a veces son referidos como números de <dfn>punto flotante</dfn> o <dfn>flotantes</dfn>.",
"<strong>Nota</strong><br>No todos los números reales pueden ser exactamente representados en <dfn>punto flotante</dfn>. Esto puede conducir a errores de redondeo. <a href=\"https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems\" target=\"_blank\">Detalles aquí</a>.",
"<h4>Instrucciones</h4>",
"Crea una variable <code>myDecimal</code> y dale un valor decimal con una parte fraccional (p.e. <code>5.7</code>)."
"<strong>Usage</strong><br>In mathematics, a number can be checked to be even or odd by checking the remainder of the division of the number by <code>2</code>.",
"<strong>Note</strong><br>The <dfn>remainder</dfn> operator is sometimes incorrectly referred to as the \"modulus\" operator. It is very similar to modulus, but does not work properly with negative numbers.",
"Set <code>remainder</code> equal to the remainder of <code>11</code> divided by <code>3</code> using the <dfn>remainder</dfn> (<code>%</code>) operator."
"<strong>Uso</strong><br>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 <code>2</code>.",
"<blockquote>17 % 2 = 1 (17 es Impar)<br>48 % 2 = 0 (48 es Par)</blockquote>",
"<strong>Nota</strong><br>El operador <dfn>residuo</dfn> 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.",
"<h4>Instrucciones</h4>",
"Asigna <code>remainder</code> igual al residuo de <code>11</code> dividido por <code>3</code> usando el operador <dfn>residuo</dfn> (<code>%</code>)."
"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:",
"to add <code>5</code> to <code>myVar</code>. Since this is such a common pattern, there are operators which do both a mathematical operation and assignment in one step.",
"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:",
"<code>miVar = miVar + 5;</code>",
"para agregar <code>5</code> a <code>miVar</code>. 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 <code>+=</code>.",
"<code>miVar += 5;</code> añadirá <code>5</code> a <code>miVar</code>.",
"<h4>Instrucciones</h4>",
"Convierte las asignaciones para <code>a</code>, <code>b</code> y <code>c</code> usando el operador <code>+=</code>."
"<code>\"your name\"</code> is called a <dfn>string</dfn> <dfn>literal</dfn>. It is a string because it is a series of zero or more characters enclosed in single or double quotes.",
"Create two new <code>string</code> variables: <code>myFirstName</code> and <code>myLastName</code> and assign them the values of your first and last name, respectively."
"assert((function(){if(typeof myFirstName !== \"undefined\" && typeof myFirstName === \"string\" && myFirstName.length > 0){return true;}else{return false;}})(), 'message: <code>myFirstName</code> should be a string with at least one character in it.');",
"assert((function(){if(typeof myLastName !== \"undefined\" && typeof myLastName === \"string\" && myLastName.length > 0){return true;}else{return false;}})(), 'message: <code>myLastName</code> should be a string with at least one character in it.');"
"En el reto anterior, se utilizó el código <code>myName var = \"su nombre\"</code>. Esto es lo que llamamos una variable tipo <code>cadena</code>. No es nada más que una \"cadena\" de caracteres. Las cadenas en JavaScript siempre se encierran entre comillas. ",
"Ahora vamos a crear dos nuevas variables tipo cadena: <code>myFirstName</code> y <code>myLastName</code> y asignarles los valores de tu nombre y tu apellido, respectivamente."
"When you are defining a string you must start and end with a single or double quote. What happens when you need a literal quote: <code>\"</code> or <code>'</code> inside of your string?",
"In JavaScript, you can <dfn>escape</dfn> a quote from considering it as an end of string quote by placing a <dfn>backslash</dfn> (<code>\\</code>) in front of the quote.",
"<code>var sampleStr = \"Alan said, \\\"Peter is learning JavaScript\\\".\";</code>",
"This signals to JavaScript that the following quote is not the end of the string, but should instead appear inside the string. So if you were to print this to the console, you would get:",
"<code>Alan said, \"Peter is learning JavaScript\".</code>",
"assert(code.match(/\\\\\"/g).length === 6 && code.match(/[^\\\\]\"/g).length === 10, 'message: You should use two double quotes (<code>"</code>) and four escaped double quotes (<code>\"</code>).');",
"assert(myStr === \"I am a \\\"double quoted\\\" string inside \\\"double quotes\\\".\", 'message: Variable myStr should contain the string: <code>I am a \"double quoted\" string inside \"double quotes\".</code>');"
"Cuando estás definiendo una cadena debes iniciar y terminar con apóstrofes o comillas. ¿Qué pasa cuando necesitas una comilla: <code>\"</code> o <code>'</code> dentro de tu cadena?",
"En JavaScript, tu puedes <dfn>escapar</dfn> unas comillas para diferenciarlas de las comillas del final de la cadena colocando una <dfn>barra invertida</dfn> (<code>\\</code>) antes de la cita.",
"<code>var cadenaEjem = \"Alan dijo, \\\"Pedro está aprendiendo JavaScript\\\".\";</code>",
"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:",
"<code>Alan dijo, \"Pedro está aprendiendo JavaScript\".<code>",
"<h4>Instructiones</h4>",
"Usa <dfn>barras invertidas</dfn>para asigar una cadena a la variable <code>myStr</code> de modo que <em>si</em> tu fueras a imprimirla en la consola, tu verías:",
"<code>I am a \"double quoted\" string inside \"double quotes\".</code>"
"<dfn>String</dfn> values in JavaScript may be written with single or double quotes, so long as you start and end with the same type of quote. Unlike some languages, single and double quotes are functionally identical in JavaScript.",
"The value in using one or the other has to do with the need to <dfn>escape</dfn> 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:",
"assert(!/\\\\/g.test(code) && myStr.match('\\\\s*<a href\\\\s*=\\\\s*\"http://www.example.com\"\\\\s*target\\\\s*=\\\\s*\"_blank\">\\\\s*Link\\\\s*</a>\\\\s*'), 'message: Remove all the <code>backslashes</code> (<code>\\</code>)');",
"assert(code.match(/\"/g).length === 6 && code.match(/'/g).length === 4, 'message: You should have two single quotes <code>'</code> and four double quotes <code>"</code>');"
"Los valores de <dfn>Cadenas</dfn> 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.",
"<code>\"Esta cadena tiene \\\"comillas\\\" en esta\"</code>",
"La ventaja de usar una o la otra tiene que ver con la necesidad de <code>escapar</code> comillas. Si tu tienes una cadena con algunas comillas, esta puede ser difícil de leer y escribir. En su lugar, usa apóstrofes:",
"<code>'Esta cadena tiene \"comillas\" en esta. Y \"probablemente\" muchas de ellas.'</code>",
"<h4>Instrucciones</h4>",
"Cambia la cadena dada de comillas a apóstrofes y quita el escape."
"Quotes are not the only characters that can be <dfn>escaped</dfn> 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.",
"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.",
"assert(!/ /.test(myStr), 'message: <code>myStr</code> should not contain any spaces');",
"assert(/FirstLine/.test(myStr) && /SecondLine/.test(myStr) && /ThirdLine/.test(myStr), 'message: <code>myStr</code> should contain the strings <code>FirstLine</code>, <code>SecondLine</code> and <code>ThirdLine</code> (remember case sensitivity)');",
"assert(/FirstLine\\n/.test(myStr), 'message: <code>FirstLine</code> should be followed by the newline character <code>\\n</code>');",
"assert(/\\n\\t/.test(myStr), 'message: <code>myStr</code> should contain a tab character <code>\\t</code> which follows a newline character');",
"assert(/\\SecondLine/.test(myStr), 'message: <code>SecondLine</code> should be preceded by the backslash character <code>\\\\</code>');",
"assert(/SecondLine\\nThirdLine/.test(myStr), 'message: There should be a newline character between <code>SecondLine</code> and <code>ThirdLine</code>');"
"Las comillas no son el único caracter que puede ser <dfn>escapado</dfn> dentro de una cadena. Aquí ahí una tabla de secuencias de escape comunes:",
"<table class=\"table table-striped\"><thead><tr><th>Código</th><th>Salida</th></tr></thead><tbody><tr><td>\\'</td><td>apostrofe</td></tr><tr><td>\\\"</td><td>comilla</td></tr><tr><td>\\\\</td><td>barra invertida</td></tr><tr><td>\\n</td><td>nueva línea</td></tr><tr><td>\\r</td><td>retorno de carro</td></tr><tr><td>\\t</td><td>tabulación</td></tr><tr><td>\\b</td><td>retroceso</td></tr><tr><td>\\f</td><td>salto de página</td></tr></tbody></table>",
"<em>Nota que la barra invertida por si misma tiene que ser escapada con el fin de mostrarse como una barra invertida.</em>",
"Codifica la siguiente secuencia, separada por espacios:<br><q>FirstLine<code>nueva línea</code><code>tabulación</code><code>barra invertida</code>SecondLine<code>nueva línea</code>ThirdLine</q>"
"In JavaScript, when the <code>+</code> operator is used with a <code>String</code> value, it is called the <dfn>concatenation</dfn> operator. You can build a new string out of other strings by <dfn>concatenating</dfn> them together.",
"<strong>Example</strong>",
"<blockquote>'My name is Alan,' + ' I concatenate.'</blockquote>",
"Build <code>myStr</code> from the strings <code>\"This is the start. \"</code> and <code>\"This is the end.\"</code> using the <code>+</code> operator."
"assert(myStr === \"This is the start. This is the end.\", 'message: <code>myStr</code> should have a value of <code>This is the start. This is the end.</code>');",
"assert(code.match(/([\"']).*([\"'])\\s*\\+\\s*([\"']).*([\"'])/g).length > 1, 'message: Use the <code>+</code> operator to build <code>myStr</code>');",
"assert(/var\\s+myStr/.test(code), 'message: <code>myStr</code> should be created using the <code>var</code> keyword.');",
"assert(/myStr\\s*=/.test(code), 'message: Make sure to assign the result to the <code>myStr</code> variable.');"
"En JavaScript, cuando el operador <code>+</code> es usado con un valor de <code>Cadena</code>, este es llamado el operador <dfn>concatenación</dfn>. Tu puedes construir una nueva cadena de otras cadenas <dfn>concatenandolas</dfn> juntas.",
"<strong>Ejemplo</strong>",
"<blockquote>'Mi nombre es Alan,' + ' Yo concateno.'<blockquote>",
"<strong>Nota</strong><br>Cuidado con los espacios. La concatenación no agrega espacios entre cadenas concatenadas, así que necesitarás agregarlos tu mismo.",
"<h4>Instrucciones</h4>",
"Construye <code>myStr</code> con las cadenas <code>\"This is the start. \"</code> y <code>\"This is the end.\"</code> usando el operador<code>+</code>."
"We can also use the <code>+=</code> operator to <dfn>concatenate</dfn> a string onto the end of an existing string variable. This can be very helpful to break a long string over several lines.",
"Build <code>myStr</code> over several lines by concatenating these two strings: <code>\"This is the first sentence. \"</code> and <code>\"This is the second sentence.\"</code> using the <code>+=</code> operator. Use the <code>+=</code> operator similar to how it is shown in the editor. Start by assigning the first string to <code>myStr</code>, then add on the second string."
"var ourStr = \"I come first. \";\nourStr += \"I come second.\";\n\nvar myStr = \"This is the first sentence. \";\nmyStr += \"This is the second sentence.\";"
"assert(myStr === \"This is the first sentence. This is the second sentence.\", 'message: <code>myStr</code> should have a value of <code>This is the first sentence. This is the second sentence.</code>');",
"assert(code.match(/\\w\\s*\\+=\\s*[\"']/g).length > 1 && code.match(/\\w\\s*\\=\\s*[\"']/g).length > 1, 'message: Use the <code>+=</code> operator to build <code>myStr</code>');"
"title":"Concatenar cadenas con el operador mas igual",
"description":[
"Nosotros también podemos usar el operador <code>+=</code> para <dfn>concatenar</dfn> una cadena al final de una variable de cadena existente. Esto puede ser muy útil para romper una cadena larga sobre varias líneas.",
"<strong>Nota</strong><br>Cuidado con los espacios. La concatenación no agrega espacios entre cadenas concatenadas, así que necesitarás añadirlos tu mismo.",
"<h4>Instrucciones</h4>",
"Construye <code>myStr</code> sobre varias líneas concatenando estas dos cadenas:<br><code>\"This is the first sentence. \"</code> y <code>\"This is the second sentence.\"</code> usando el operador <code>+=</code>."
"Sometimes you will need to build a string, <a href=\"https://en.wikipedia.org/wiki/Mad_Libs\" target=\"_blank\">Mad Libs</a> style. By using the concatenation operator (<code>+</code>), you can insert one or more variables into a string you're building.",
"Set <code>myName</code> to a string equal to your name and build <code>myStr</code> with <code>myName</code> between the strings <code>\"My name is \"</code> and <code>\" and I am well!\"</code>"
"assert(code.match(/[\"']\\s*\\+\\s*myName\\s*\\+\\s*[\"']/g).length > 0, 'message: Use two <code>+</code> operators to build <code>myStr</code> with <code>myName</code> inside it');"
"A veces necesitarás construir una cadena, al estilo <a href=\"https://en.wikipedia.org/wiki/Mad_Libs\" target=\"_blank\">Mad Libs</a>. Mediante el uso del operador concatenación (<code>+</code>), puedes insertar una o más variables dentro de una cadena que estés construyendo.",
"Asigna <code>myName</code> a una cadena igual a tu nombre y construye <code>myStr</code> con <code>myName</code> entre las cadenas <code>\"My name is \"</code> and <code>\" and I am well!\"</code>"
"Just as we can build a string over multiple lines out of string <dfn>literals</dfn>, we can also append variables to a string using the plus equals (<code>+=</code>) operator.",
"assert(typeof someAdjective !== 'undefined' && someAdjective.length > 2, 'message: <code>someAdjective</code> should be set to a string at least 3 characters long');",
"assert(code.match(/myStr\\s*\\+=\\s*someAdjective\\s*/).length > 0, 'message: Append <code>someAdjective</code> to <code>myStr</code> using the <code>+=</code> operator');"
"Al igual que podemos construir una cadena en múltiples líneas a partir de cadenas <dfn>literales</dfn>, nosotros podemos ademas anexar variables a una cadena usando el operador más igual (<code>+=</code>).",
"<h4>Instructiones</h4>",
"Asigna <code>someAdjective</code> y anexalo a <code>myStr</code> usando el operador <code>+=</code>."
"You can find the length of a <code>String</code> value by writing <code>.length</code> after the string variable or string literal.",
"<code>\"Alan Peter\".length; // 10</code>",
"For example, if we created a variable <code>var firstName = \"Charles\"</code>, we could find out how long the string <code>\"Charles\"</code> is by using the <code>firstName.length</code> property.",
"Use the <code>.length</code> property to count the number of characters in the <code>lastName</code> variable and assign it to <code>lastNameLength</code>."
"assert((function(){if(code.match(/\\.length/gi) && code.match(/\\.length/gi).length >= 2 && code.match(/var lastNameLength \\= 0;/gi) && code.match(/var lastNameLength \\= 0;/gi).length >= 1){return true;}else{return false;}})(), 'message: You should be getting the length of <code>lastName</code> by using <code>.length</code> like this: <code>lastName.length</code>.');"
"title":"Comprueba la propiedad longitud (length) de una variable tipo cadena",
"description":[
"Las <code>estructuras de datos</code> tienen <code>propiedades</code>. Por ejemplo, las <code>cadenas</code> tienen una propiedad llamada <code>.length </code> que te dirá cuántos caracteres hay en la cadena.",
"Por ejemplo, si creamos una variable <code>var firstName=\"Charles\"</code>, podemos averiguar la longitud de la cadena \"Charles\" usando la propiedad <code>firstName.length</code>. ",
"Usa la propiedad <code>.length</code> para contar el número de caracteres en el variable <code>lastName</code>."
"Most modern programming languages, like JavaScript, don't start counting at 1 like humans do. They start at 0. This is referred to as <dfn>Zero-based</dfn> indexing.",
"For example, the character at index 0 in the word \"Charles\" is \"C\". So if <code>var firstName = \"Charles\"</code>, you can get the value of the first letter of the string by using <code>firstName[0]</code>.",
"Use <dfn>bracket notation</dfn> to find the first character in the <code>lastName</code> variable and assign it to <code>firstLetterOfLastName</code>.",
"title":"Usa la notación de corchetes para encontrar el primer carácter de una cadena",
"description":[
"La <code>notación de corchetes</code> es una forma de obtener el caracter en un <code>índice</code> específico de una cadena.",
"Los computadoras no empiezan a contar desde 1 como hacen los humanos. Comienzan en 0 ",
"Por ejemplo, el caracter en el índice 0 en la palabra \"Charles \" es \"C\". Entonces si <code>var firstName = \"Charles\"</code>, puedes obtener la primera letra de la cadena usando <code>firstName[0]</code> .",
"Usa la <code>notación de corchetes</code> para encontrar el primer caracter en la variable <code>lastName</code> y asignarlo a <code>firstLetterOfLastName</code>.",
"Si te atascas intenta mirar la declaración de la variable <code>firstLetterOfFirstName</code>."
"cannot change the value of <code>myStr</code> to \"Job\", because the contents of <code>myStr</code> cannot be altered. Note that this does <em>not</em> mean that <code>myStr</code> cannot be changed, just that the individual characters of a <dfn>string literal</dfn> cannot be changed. The only way to change <code>myStr</code> would be to assign it with a new string, like this:",
"Correct the assignment to <code>myStr</code> so it contains the string value of <code>Hello World</code> using the approach shown in the example above."
"En JavaScript, los valores de las <code>Cadenas</code> son <dfn>inmutables</dfn>, lo cual significa que ellos no pueden ser alterados una vez creados.",
"no puede cambiar el valor de <code>miCad</code> a \"Job\" porque el contenido de <code>miCad</code> no puede ser alterado. Nota que esto <em>no</em> significa que <code>miCad</code> no puede ser cambiado, solo que los valores individuales de una <dfn>cadena literal</dfn> no pueden ser cambiados. La única manera de cambiar <code>miCad</code> sería asignandola a una nueva cadena, como esta:",
"title":"Use Bracket Notation to Find the Last Character in a String",
"description":[
"In order to get the last letter of a string, you can subtract one from the string's length.",
"For example, if <code>var firstName = \"Charles\"</code>, you can get the value of the last letter of the string by using <code>firstName[firstName.length - 1]</code>.",
"title":"Use Bracket Notation to Find the Nth-to-Last Character in a String",
"description":[
"You can use the same principle we just used to retrieve the last character in a string to retrieve the Nth-to-last character.",
"For example, you can get the value of the third-to-last letter of the <code>var firstName = \"Charles\"</code> string by using <code>firstName[firstName.length - 3]</code>",
"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 <code>var firstName = \"Charles\"</code> utilizando <code>firstName[firstName.length - 3]</code> ",
"<h4>Instrucciones</h4>",
"Usa <code>notación de corchete</code> para encontrar el segundo último caracter de la cadena en <code>lastName</code>.",
"<strong>Pista</strong><br>Si te atascas intenta mirando la declaración de la variable <code>thirdToLastLetterOfFirstName</code>."
"We will now use our knowledge of strings to build a \"<a href='https://en.wikipedia.org/wiki/Mad_Libs' target='_blank'>Mad Libs</a>\" style word game we're calling \"Word Blanks\". You will create an (optionally humorous) \"Fill in the Blanks\" style sentence. Here's an example of an incomplete sentence.",
"<code>\"The ______ ______ looked around ______ then ______ into the house\"</code>",
"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, <code>result</code>, using the variables <code>myNoun</code>, <code>myAdjective</code>, <code>myVerb</code>, and <code>myAdverb</code>. 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."
"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}"
"assert(/\\bdog\\b/.test(test1) && /\\bbig\\b/.test(test1) && /\\bran\\b/.test(test1) && /\\bquickly\\b/.test(test1),'message: <code>wordBlanks(\"dog\", \"big\", \"ran\", \"quickly\")</code> should contain all of the passed 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: <code>wordBlanks(\"cat\", \"little\", \"hit\", \"slowly\")</code> should contain all of the passed in words separated by non-word characters (and any additional words in your madlib).');"
"Ahora usaremos nuestro conocimiento de cadenas para construir un juego de palabras estilo \"<a href='https://en.wikipedia.org/wiki/Mad_Libs' target='_blank'>Mad Libs</a>\" 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 <code>result</code>, usando las variables previstas: <code>myNoun</code>, <code>myAdjective</code>, <code>myVerb</code> y <code>myAdverb</code>.",
"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."
"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: ",
"assert(typeof myArray == 'object', 'message: <code>myArray</code> should be an <code>array</code>.');",
"assert(typeof myArray[0] !== 'undefined' && typeof myArray[0] == 'string', 'message: The first item in <code>myArray</code> should be a <code>string</code>.');",
"assert(typeof myArray[1] !== 'undefined' && typeof myArray[1] == 'number', 'message: The second item in <code>myArray</code> should be a <code>number</code>.');"
"title":"Almacena múltiples valores en una variable utilizando vectores en JavaScript",
"description":[
"Con las variables tipo <code>vector</code> (o en inglés <code>array</code>) podemos almacenar diversos datos en un solo lugar.",
"Empiezas la declaración de un vector con un corchete de apertura, y terminas con un corchete de cierre, y pones una coma entre cada entrada, así: <code>var sandwich = [\"mantequilla de maní\", \"jalea\" , \"pan\"]</code>. ",
"<h4>Instrucciones</h4>",
"Ahora vamos a crear un nuevo vector llamado <code>myArray</code> que contenga una <code>cadena</code> y un <code>número</code> (en ese orden).",
"Consulta el código comentado en el editor de texto si te atascas."
"You can also nest arrays within other arrays, like this: <code>[[\"Bulls\", 23], [\"White Sox\", 45]]</code>. This is also called a <dfn>Multi-dimensional Array<dfn>.",
"assert(Array.isArray(myArray) && myArray.some(Array.isArray), 'message: <code>myArray</code> should have at least one array nested within another array.');"
"Array indexes are written in the same bracket notation that strings use, except that instead of specifying a character, they are specifying an entry in the array. Like strings, arrays use <dfn>zero-based</dfn> indexing, so the first element in an array is element <code>0</code>.",
"<strong>Note</strong><br>There shouldn't be any spaces between the array name and the square brackets, like <code>array [0]</code>. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.",
"assert((function(){if(typeof myArray !== 'undefined' && typeof myData !== 'undefined' && myArray[0] === myData){return true;}else{return false;}})(), 'message: The variable <code>myData</code> should equal the first value of <code>myArray</code>.');",
"assert((function(){if(code.match(/\\s*=\\s*myArray\\[0\\]/g)){return true;}else{return false;}})(), 'message: The data in variable <code>myArray</code> should be accessed using bracket notation.');"
"title":"Accede a los datos de un vector mediante índices",
"description":[
"Podemos acceder a los datos dentro de los vectores usando <code>índices</code>.",
"Los índices del vector se escriben en la misma notación con corchetes usado con cadenas, excepto que en lugar de especificar un caracter, especifican un elemento del vector.",
"Por ejemplo:",
"<code>var array = [1,2,3];</code>",
"<code>array[0]; //es igual a 1</code>",
"<code>var data = array[1];</code>",
"<h4>Instrucciones</h4>",
"Crea una variable llamada <code>myData</ code> y asignale el primer valor del vector <code>myArray</code>."
"<strong>Note</strong><br>There shouldn't be any spaces between the array name and the square brackets, like <code>array [0]</code>. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.",
"assert((function(){if(code.match(/myArray\\[0\\]\\s*=\\s*/g)){return true;}else{return false;}})(), 'message: You should be using correct index to modify the value in <code>myArray</code>.');"
"One way to think of a <dfn>multi-dimensional</dfn> array, is as an <em>array of arrays</em>. When you use brackets to access your array, the first set of 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.",
"<strong>Note</strong><br>There shouldn't be any spaces between the array name and the square brackets, like <code>array [0][0]</code> and even this <code>array [0] [0]</code> is not allowed. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.",
"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 <code>myArray</code>.');"
"title":"Acceder a vectores multi-dimensionales con índices",
"description":[
"Una manera de pensar un vector <dfn>multi-dimensional</dfn>, es como un <em>vector de vectores</em>. 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.",
"<strong>Ejemplo</strong>",
"<blockquote>var vec = [<br> [1,2,3],<br> [4,5,6],<br> [7,8,9],<br> [[10,11,12], 13, 14]<br>];<br>vec[0]; // es igual [1,2,3]<br>vec[1][2]; // es igual 6<br>vec[3][0][1]; // es igual 11</blockquote>",
"<h4>Instrucciones</h4>",
"Lee de <code>myArray</code> usando la notación corchete de modo que myData sea igual a <code>8</code>"
"No sólo se pueden sacar datos del final de un vector con <code>pop()</code>, también puedes empujar (<code>push()</code>) datos al final del vector.",
"<h4>Instrucciones</h4>",
"Empuja <code>[\"dog\", 3]</code> al final de la variable <code>myArray</code>."
"<code>.pop()</code> is used to \"pop\" a value off of the end of an array. We can store this \"popped off\" value by assigning it to a variable. In other words, <code>.pop()</code> removes the last element from an array and returns that element.",
"Use the <code>.pop()</code> function to remove the last item from <code>myArray</code>, assigning the \"popped off\" value to <code>removedFromMyArray</code>."
"Otra forma de cambiar los datos en un vector es con la función <code>.pop()</code>.",
"<code>.pop()</code> se utiliza para \"sacar\" el valor final de un vector. Podemos almacenar el valor \"sacado\" asignando <code>pop</code> a una variable por ejemplo durante su declaración.",
"Todo tipo de datos puede ser \"sacado\" de un vector --números, cadenas, incluso los vectores anidadas.",
"<h4>Instrucciones</h4>",
"Usa la función <code>.pop()</code> para sacar el último elemento de <code>myArray</code> y asigna ese valor \"sacado\" a <code>removedFromMyArray </code>."
"Use the <code>.shift()</code> function to remove the first item from <code>myArray</code>, assigning the \"shifted off\" value to <code>removedFromMyArray</code>."
"<code>pop()</code> siempre elimina el último elemento de un vector. ¿Qué pasa si quieres quitar el primero?",
"Ahí es donde entra <code>.shift()</code>. Funciona igual que <code>.pop ()</code>, excepto que elimina el primer elemento en lugar del pasado. ",
"<h4>Instrucciones</h4>",
"Usa la función <code>.shift()</code> para eliminar el primer elemento de <code>myArray</code>, y el elemento que saques asignalo a <code>removedFromMyArra</code>"
"Not only can you <code>shift</code> elements off of the beginning of an array, you can also <code>unshift</code> elements to the beginning of an array i.e. add elements in front of the array.",
"<code>.unshift()</code> works exactly like <code>.push()</code>, but instead of adding the element at the end of the array, <code>unshift()</code> adds the element at the beginning of the array.",
"No sólo se puedes <code>correr</code> (shift) elementos del comienzo de un vector, también puedes <code>descorrerlos</code> (unshift) al comienzo.",
"<code>unshift()</code> funciona exactamente igual que <code>push()</code>, pero en lugar de añadir el elemento al final del vector, <code>unshift()</code> añade el elemento al comienzo del vector. ",
"<h4>Instrucciones</h4>",
"Añade <code>\"Paul\"</code> al comienzo de la variable <code>myArray</code> usando <code>unshift()</code>."
"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.",
"Crea una lista de compras en la variable <code>myList</code>. 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.",
"<code>[\"Barra de Chocolate\", 15]</code>",
"Tiene que haber por lo menos 5 sub-vectores en la lista."
"Each time the function is called it will print out the message <code>\"Hello World\"</code> on the dev console. All of the code between the curly braces will be executed every time the function is called.",
"<ol><li>Create a function called <code>reusableFunction</code> which prints <code>\"Hi World\"</code> to the dev console.</li><li>Call the function.</li></ol>"
"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:",
"<code>function nombreDeFuncion(a, b) {</code>",
"<code>& nbsp; & nbsp; return a + b;</code>",
"<code>}</code>",
"Después de escribir las líneas anteriores en nuestro código, podemos pasar valores a nuestra función y el resultado que sigue a la instrucción <code>return</code> será retornado.",
"Por ejemplo, podemos pasar los números <code>4</code> y <code>2</code> al \"llamar\" la función más adelante en nuestro código, así: <code>nombreDeFuncion(4, 2)</ code >. ",
"En este ejemplo, la función devolverá el número <code>6</code>, ya que es el resultado de <code>4 + 2</code>.",
"Crea y llama una función de nombre <code>myFunction</code> que devuelva la suma de <code>a</code> y <code>b</code>."
"<dfn>Parameters</dfn> are variables that act as placeholders for the values that are to be input to a function when it is called. When a function is defined, it is typically defined along with one or more parameters. The actual values that are input (or <dfn>\"passed\"</dfn>) into a function when it is called are known as <dfn>arguments</dfn>.",
"We have passed two arguments, <code>\"Hello\"</code> and <code>\"World\"</code>. Inside the function, <code>param1</code> will equal \"Hello\" and <code>param2</code> will equal \"World\". Note that you could call <code>testFun</code> again with different arguments and the parameters would take on the value of the new arguments.",
"<ol><li>Create a function called <code>functionWithArgs</code> that accepts two arguments and outputs their sum to the dev console.</li><li>Call the function with two numbers as arguments.</li></ol>"
"assert(/^\\s*functionWithArgs\\s*\\(\\s*\\d+\\s*,\\s*\\d+\\s*\\)\\s*;/m.test(code), 'message: Call <code>functionWithArgs</code> with two numbers after you define it.');"
"title":"Pasando valores a funciones con argumentos",
"description":[
"Los <dfn>parámetros</dfn> 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 <dfn>\"pasados\"</dfn>) dentro de una función cuando esta es llamada son concidos como <dfn>argumentos</dfn>.",
"Aquí hay una función con dos parámetros, <code>param1</code> y <code>param2</code>:",
"Nosotros hemos pasado dos argumentos, <code>\"Hello\"</code> y <code>\"World\"</code>. Dentro de la función, <code>param1</code> será igual a \"Hello\" y <code>param2</code> será igual a \"World\". Nota que puedes llamar <code>testFun</code> otra vez con argumentos diferentes y los parámetros asumirían el valor de los nuevos argumentos.",
"<h4>Instrucciones</h4>",
"<ol><li>Crea una función llamada <code>functionWithArgs</code> que acepte dos argumentos y da salida a su suma en la consola.</li><li>Llama la función.</li></ol>"
"In JavaScript, <dfn>scope</dfn> refers to the visibility of variables. Variables which are defined outside of a function block have <dfn>Global</dfn> scope. This means, they can be seen everywhere in your JavaScript code.",
"Variables which are used without the <code>var</code> keyword are automatically created in the <code>global</code> scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with <code>var</code>.",
"Using <code>var</code>, declare a <code>global</code> variable <code>myGlobal</code> outside of any function. Initialize it with a value of <code>10</code>.",
"Inside function <code>fun1</code>, assign <code>5</code> to <code>oopsGlobal</code> <strong><em>without</em></strong> using the <code>var</code> keyword."
"assert(typeof oopsGlobal != \"undefined\" && oopsGlobal === 5, 'message: <code>oopsGlobal</code> should be a global variable and have a value of <code>5</code>');"
"En JavaScript, <dfn>alcance</dfn> se referiere a la visibilidad de variables. Las variables que definas fuera de un bloque de una función tienen alcance <dfn>Global</dfn>. 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 <code>var</code> son automáticamente creadas en el alcance <code>global</code>. 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 <code>var</code>.",
"<h4>Instrucciones</h4>",
"Declara a variable <code>global</code> <code>myGlobal</code> fuera de cualquier función. Inicializala para tener un valor de <code>10</code> ",
"Dentro de la función <code>fun1</code>, asigna <code>5</code> a <code>oopsGlobal</code> <strong><em>sin</em></strong> usar la palabra clave <code>var</code>."
"Variables which are declared within a function, as well as the function parameters have <dfn>local</dfn> scope. That means, they are only visible within that function.",
"<blockquote>function myTest() {<br> var loc = \"foo\";<br> console.log(loc);<br>}<br>myTest(); // logs \"foo\"<br>console.log(loc); // loc is not defined</blockquote>",
"Declare a local variable <code>myVar</code> inside <code>myLocalScope</code>. Run the tests and then follow the instructions commented out in the editor.",
"Las variables que son declaradas dentro de una función, así como los parámetros de la función tienen alcance <dfn>local</dfn>. Eso significa que solo son visibles dentro de esa función.",
"Aquí está una función <code>myTest</code> con una variable local llamada <code>loc</code>.",
"<blockquote>function myTest() {<br> var loc = \"foo\";<br> console.log(loc);<br>}<br>myTest(); // \"foo\"<br>console.log(loc); // \"undefined\"</blockquote>",
"<code>loc</code> no está definida fuera de la función.",
"<h4>Instrucciones</h4>",
"Declara una variable local <code>myVar</code> dentro de <code>myLocalScope</code>"
"It is possible to have both <dfn>local</dfn> and <dfn>global</dfn> variables with the same name. When you do this, the <code>local</code> variable takes precedence over the <code>global</code> variable.",
"Es posible tener variables <dfn>locales</dfn> y <dfn>globales</dfn> con el mismo nombre. Cuando tu haces esto, la variable <code>local</code> toma precedencia sobre la variable <code>global</code>.",
"Create a function <code>timesFive</code> that accepts one argument, multiplies it by <code>5</code>, and returns the new value. See the last line in the editor for an example of how you can test your <code>timesFive</code> function."
"title":"Retorna un valor desde una función con return",
"description":[
"Podemos pasar valores a una función mediante los <dfn>argumentos</dfn>. Puedes usar una sentencia <code>return</code> para enviar un valor de vuelta de una función.",
"If you'll recall from our discussion of <a href=\"storing-values-with-the-assignment-operator\" target=\"_blank\">Storing Values with the Assignment Operator</a>, everything to the right of the equal sign is resolved before the value is assigned. This means we can take the return value of a function and assign it to a variable.",
"assert(/processed\\s*=\\s*processArg\\(\\s*7\\s*\\)\\s*;/.test(code), 'message: You should assign <code>processArg</code> to <code>processed</code>');"
"Si recuerdas de nuestra discusión de <a href=\"waypoint-storing-values-with-the-equal-operator\" target=\"_blank\">Almacenar Valores con el Operador Igual</a>, 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 <code>suma</code> la cual suma dos números, entonces: ",
"<code>nuestraSuma = suma(5, 12);</code>",
"llamará la función <code>suma</code>, la cual retornará un valor de <code>17</code> y lo asignará a la variable <code>nuestraSuma</code>.",
"<h4>Instrucciones</h4>",
"Llama la función <code>processArg</code> con un argumento <code>7</code> y asigna su valor de retorno a la variable <code>processed</code>."
"In Computer Science a <dfn>queue</dfn> is an abstract <dfn>Data Structure</dfn> where items are kept in order. New items can be added at the back of the <code>queue</code> and old items are taken off from the front of the <code>queue</code>.",
"assert(nextInLine([],1) === 1, 'message: <code>nextInLine([], 1)</code> should return <code>1</code>');",
"assert(nextInLine([2],1) === 2, 'message: <code>nextInLine([2], 1)</code> should return <code>2</code>');",
"assert(nextInLine([5,6,7,8,9],1) === 5, 'message: <code>nextInLine([5,6,7,8,9], 1)</code> should return <code>5</code>');",
"nextInLine(testArr, 10); assert(testArr[4] === 10, 'message: After <code>nextInLine(testArr, 10)</code>, <code>testArr[4]</code> should be <code>10</code>');"
"En Ciencias de la Computación una <dfn>cola</dfn> es una <dfn>Estructura de Datos</dfn> abstracta donde los elementos son mantenidos en orden. Nuevos elementos pueden ser agregados en la parte trasera de la <code>cola</code> y los elementos viejos son quitados desde el frente de la <code>cola</code>.",
"Escribe una función <code>nextInLine</code> la cual toma un vector (<code>arr</code>) y un número (<code>item</code>) 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."
"Another data type is the <dfn>Boolean</dfn>. <code>Booleans</code> may only be one of two values: <code>true</code> or <code>false</code>. They are basically little on-off switches, where <code>true</code> is \"on\" and <code>false</code> is \"off.\" These two states are mutually exclusive.",
"<strong>Note</strong><br><code>Boolean</code> values are never written with quotes. The <code>strings</code> <code>\"true\"</code> and <code>\"false\"</code> are not <code>Boolean</code> and have no special meaning in JavaScript.",
"Modify the <code>welcomeToBooleans</code> function so that it returns <code>true</code> instead of <code>false</code> when the run button is clicked."
],
"challengeSeed":[
"function welcomeToBooleans() {",
"",
"// Only change code below this line.",
"",
"return false; // Change this line",
"",
"// Only change code above this line.",
"}"
],
"tail":[
"welcomeToBooleans();"
],
"solutions":[
"function welcomeToBooleans() {\n return true; // Change this line\n}"
"assert(typeof welcomeToBooleans() === 'boolean', 'message: The <code>welcomeToBooleans()</code> function should return a boolean (true/false) value.');",
"En informática las <code>estructuras de datos</code> son cosas que contienen datos. JavaScript tiene siete de estas. Por ejemplo, la estructura de datos <code>Número</code> contiene números. ",
"Vamos a aprender acerca de la estructura de datos más básica de todas: el <code>Boolean</code>. Los booleanos sólo puede contener el valor verdadero o el valor falso. Son básicamente pequeños interruptores de encendido y apagado. ",
"<h4>Instrucciones</h4>",
"Vamos a modificar nuestra función <code>welcomeToBooleans</code> para que devuelva <code>true</code> en lugar de <code>false</code> cuando se pulse el botón de ejecución."
"<code>If</code> statements are used to make decisions in code. The keyword <code>if</code> tells JavaScript to execute the code in the curly braces under certain conditions, defined in the parentheses. These conditions are known as <code>Boolean</code> conditions and they may only be <code>true</code> or <code>false</code>.",
"When the condition evaluates to <code>true</code>, the program executes the statement inside the curly braces. When the Boolean condition evaluates to <code>false</code>, the statement inside the curly braces will not execute.",
"<blockquote>function test (myCondition) {<br> if (myCondition) {<br> return \"It was true\";<br> }<br> return \"It was false\";<br>}<br>test(true); // returns \"It was true\"<br>test(false); // returns \"It was false\"</blockquote>",
"When <code>test</code> is called with a value of <code>true</code>, the <code>if</code> statement evaluates <code>myCondition</code> to see if it is <code>true</code> or not. Since it is <code>true</code>, the function returns <code>\"It was true\"</code>. When we call <code>test</code> with a value of <code>false</code>, <code>myCondition</code> is <em>not</em> <code>true</code> and the statement in the curly braces is not executed and the function returns <code>\"It was false\"</code>.",
"Create an <code>if</code> statement inside the function to return <code>\"Yes, that was true\"</code> if the parameter <code>wasThatTrue</code> is <code>true</code> and return <code>\"No, that was false\"</code> otherwise."
"title":"Usa lógica condicional con instrucciones if y else",
"description":[
"Podemos usar instrucciones <code>if</code> (\"if\" es \"si\" en español) en JavaScript para ejecutar código sólo cuando cierta condición se cumpla.",
"Las instrucciones <code>if</code> requieren evaluar algún tipo de condición booleana.",
"Por ejemplo:",
"<code>if (1 === 2) {</code>",
"<code> return true;</code>",
"<code>} else {</code>",
"<code> return false;</code>",
"<code>}</code>",
"Vamos a usar la instrucción <code>if</code> con <code>else</code> (\"else\" puede traducirse como \"de lo contrario\") para hacer un juego de cara o sello.",
"<h4>Instrucciones</h4>",
"Crea una instrucción <code>if</code> con <code>else</code> que retorne la cadena <code>\"heads\"</code> si la variable <code>flip</code> es cero, o bien que retorne <code >\"tails\"</code> si la variable <code>flip</code> no es cero. "
"There are many <dfn>Comparison Operators</dfn> in JavaScript. All of these operators return a boolean <code>true</code> or <code>false</code> value.",
"The most basic operator is the equality operator <code>==</code>. The equality operator compares two values and returns <code>true</code> if they're equivalent or <code>false</code> if they are not. Note that equality is different from assignment (<code>=</code>), which assigns the value at the right of the operator to a variable in the left.",
"If <code>myVal</code> is equal to <code>10</code>, the equality operator returns <code>true</code>, so the code in the curly braces will execute, and the function will return <code>\"Equal\"</code>. Otherwise, the function will return <code>\"Not Equal\"</code>.",
"In order for JavaScript to compare two different <code>data types</code> (for example, <code>numbers</code> and <code>strings</code>), it must convert one type to another. Once it does, however, it can compare terms as follows:",
"Add the <code>equality operator</code> to the indicated line so that the function will return \"Equal\" when <code>val</code> is equivalent to <code>12</code>"
"title":"La comparación con el operador de igualdad",
"description":[
"Hay muchos <dfn>Operadores de Comparación</dfn> en JavaScript. Todos estos operadores retornan un valor booleano <code>true</code>(verdadero) o <code>false</code>(falso).",
"El operador más básico es el operador de igualdad <code>==</code>. El operador de igualdad compara dos valores y retorna <code>true</code> si son equivalentes o <code>false</code> si no lo son. Nota que la igualdad es diferente de la asignación (<code>=</code>), la cual asigna el valor a la derecha del operador a la variable en la izquierda.",
"<blockquote>function pruebaIgualdad(miVal) {<br> if (miVal == 10) {<br> return \"Igual\";<br> }<br> return \"No Es Igual\";<br>}</blockquote>",
"Si <code>miVal</code> es igual a <code>10</code>, el operador de igualdad retornará <code>true</code>(verdadero), así el código entre llaves será ejecutado y la función retornará <code>\"Equal\"</code>. De otra manera, la función retornará <code>\"Not Equal\"</code>.",
"Para que JavaScript pueda comparar dos <code>tipos de datos</code> diferentes (por ejemplo, <code>números</code> y <code>cadenas de texto</code>), debe convertir un tipo a otro. Una vez que lo hace, sin embargo, puede comparar términos de la siguiente manera:",
"Agrega el <code>operador de igualdad</code> a la línea indicada de manera que la función retornará \"Equal\" cuando <code>val</code> sea equivalente a <code>12</code>"
"Strict equality (<code>===</code>) is the counterpart to the equality operator (<code>==</code>). Unlike the equality operator, strict equality tests both the <code>data type</code> and value of the compared elements.",
"Use the strict equality operator in the <code>if</code> statement so the function will return \"Equal\" when <code>val</code> is strictly equal to <code>7</code>"
"title":"La comparación con el operador de estricta igualdad",
"description":[
"Igualdad estricta (<code>===</code>) es la contraparte del operador de igualdad (<code>==</code>). Diferente al operador de igualdad, igualdad estricta prueba los <code>tipos de datos</code> y el valor de los elementos comparados.",
"En el segundo ejemplo, <code>3</code> es de tipo <code>Número</code> y <code>'3'</code> es de tipo <code>Cadena</code>.",
"<h4>Instrucciones</h4>",
"Usa el operador de igualdad estricta en la sentencia <code>if</code> de manera que la función retorne \"Equal\" cuando <code>val</code> es estrictamente igual a <code>7</code>"
"The inequality operator (<code>!=</code>) is the opposite of the equality operator. It means \"Not Equal\" and returns <code>false</code> where equality would return <code>true</code> and <em>vice versa</em>. Like the equality operator, the inequality operator will convert data types of values while comparing.",
"Add the inequality operator <code>!=</code> in the <code>if</code> statement so that the function will return \"Not Equal\" when <code>val</code> is not equivalent to <code>99</code>"
"title":"La comparación con el operador de desigualdad",
"description":[
"El operador de desigualdad (<code>!=</code>) es el opuesto al operador de igualdad. Esto significa \"No Igual a\" y retorna <code>false</code> cuando igualdad retornaría <code>true</code> y <em>viceversa</em>. Como el operador de igualdad, el operador de desigualdad convertirá tipos de datos mientras compara.",
"Agrega el operador de desigualdad <code>!=</code> en la sentencia <code>if</code> de manera que la función retorne \"Not Equal\" (No igual a) cuando <code>val</code> no es equivalente a <code>99</code>"
"The strict inequality operator (<code>!==</code>) is the logical opposite of the strict equality operator. It means \"Strictly Not Equal\" and returns <code>false</code> where strict equality would return <code>true</code> and <em>vice versa</em>. Strict inequality will not convert data types.",
"Add the <code>strict inequality operator</code> to the <code>if</code> statement so the function will return \"Not Equal\" when <code>val</code> is not strictly equal to <code>17</code>"
"title":"La comparación con el operador de estricta desigualdad",
"description":[
"El operador de estricta desigualdad (<code>!==</code>) es el opuesto al operador de estricta igualdad. Esto significa \"Estrictamente no Igual\" y retorna <code>false</code>(falso) donde igualdad estricta retornaría <code>true</code>(verdadero) y <em>viceversa</em>. Estricta desigualdad no convertirá tipos de datos.",
"Agrega el <code>operador de estricta desigualdad</code> a la sentencia <code>if</code> de manera que la función retorne \"Not Equal\" cuando <code>val</code> no es estrictamente igual a <code>17</code>"
"The greater than operator (<code>></code>) compares the values of two numbers. If the number to the left is greater than the number to the right, it returns <code>true</code>. Otherwise, it returns <code>false</code>.",
"Like the equality operator, greater than operator will convert data types of values while comparing.",
"title":"La comparación con el operador mayor que",
"description":[
"El operador mayor que (<code>></code>) 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 <code>true</code>(verdadero). De otra manera, este retorna <code>false</code>(falso).",
"Al igual que el operador de igualdad, el operador mayor que convertirá tipos de datos de valores mientras los compara.",
"The <code>greater than or equal to</code> operator (<code>>=</code>) compares the values of two numbers. If the number to the left is greater than or equal to the number to the right, it returns <code>true</code>. Otherwise, it returns <code>false</code>.",
"Like the equality operator, <code>greater than or equal to</code> operator will convert data types while comparing.",
"title":"La comparación con el operador mayor o ogual",
"description":[
"El operador <code>mayor o igual </code> (<code>>=</code>) 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 <code>true</code>(verdadero). De otra manera, este retorna <code>false</code>(falso).",
"Como el operador de igualdad, el operador <code>mayor o igual</code> convertirá tipos de datos mientras está comparando.",
"The <dfn>less than</dfn> operator (<code><</code>) compares the values of two numbers. If the number to the left is less than the number to the right, it returns <code>true</code>. Otherwise, it returns <code>false</code>. Like the equality operator, <dfn>less than</dfn> operator converts data types while comparing.",
"title":"La comparación con el operador menor que",
"description":[
"El operador <dfn>menor que</dfn> (<code><</code>) 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 <code>true</code>(verdadero). De otra manera, este retorna <code>false</code>(falso). Como el operador de igualdad, el operador <dfn>menor que</dfn> convierte tipos de datos mientra compara.",
"The <code>less than or equal to</code> operator (<code><=</code>) compares the values of two numbers. If the number to the left is less than or equal to the number to the right, it returns <code>true</code>. If the number on the left is greater than the number on the right, it returns <code>false</code>. Like the equality operator, <code>less than or equal to</code> converts data types.",
"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}"
"assert(testLessOrEqual(0) === \"Smaller Than or Equal to 12\", 'message: <code>testLessOrEqual(0)</code> should return \"Smaller Than or Equal to 12\"');",
"assert(testLessOrEqual(11) === \"Smaller Than or Equal to 12\", 'message: <code>testLessOrEqual(11)</code> should return \"Smaller Than or Equal to 12\"');",
"assert(testLessOrEqual(12) === \"Smaller Than or Equal to 12\", 'message: <code>testLessOrEqual(12)</code> should return \"Smaller Than or Equal to 12\"');",
"assert(testLessOrEqual(23) === \"Smaller Than or Equal to 24\", 'message: <code>testLessOrEqual(23)</code> should return \"Smaller Than or Equal to 24\"');",
"assert(testLessOrEqual(24) === \"Smaller Than or Equal to 24\", 'message: <code>testLessOrEqual(24)</code> should return \"Smaller Than or Equal to 24\"');",
"title":"La comparación con el operador menor o igual",
"description":[
"El operador <code>menor o igual</code> (<code><=</code>) 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 <code>true</code>(verdadero). Si el número a la izquierda es mayor que el número de la derecha, este retorna <code>false</code>(falso). Al igual que el operador de igualdad, <code>menor o igual</code> convierte tipos de datos.",
"Sometimes you will need to test more than one thing at a time. The <dfn>logical and</dfn> operator (<code>&&</code>) returns <code>true</code> if and only if the <dfn>operands</dfn> to the left and right of it are true.",
"Combine the two if statements into one statement which will return <code>\"Yes\"</code> if <code>val</code> is less than or equal to <code>50</code> and greater than or equal to <code>25</code>. Otherwise, will return <code>\"No\"</code>."
"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 <dfn>lógico y</dfn> (<code>&&</code>) retorna <code>true</code>(verdadero) si y solo si los <dfn>operandos</dfn> a la izquierda y derecha de este son verdaderos.",
"El mismo efecto podría lograrse anidando una sentencia if dentro de otro if:",
"Combina las dos sentencias if dentro de una sentencia la cual retornará <code>\"Yes\"</code> si <code>val</code> es menor o igual a <code>50</code> y mayor o igual a <code>25</code>. De otra manera, retornará <code>\"No\"</code>."
"The <dfn>logical or</dfn> operator (<code>||</code>) returns <code>true</code> if either of the <dfn>operands</dfn> is <code>true</code>. Otherwise, it returns <code>false</code>.",
"The <dfn>logical or</dfn> operator is composed of two pipe symbols (<code>|</code>). This can typically be found between your Backspace and Enter keys.",
"Combine the two <code>if</code> statements into one statement which returns <code>\"Outside\"</code> if <code>val</code> is not between <code>10</code> and <code>20</code>, inclusive. Otherwise, return <code>\"Inside\"</code>."
"title":"La comparación con el operador lógico o",
"description":[
"El operador <dfn>lógico o</dfn> (<code>||</code>) retorna <code>true</code>(verdadero) si cualquiera de los <dfn>operandos</dfn> es <code>true</code>(verdadero). De otra manera, este retorna <code>false</code>(falso).",
"El patrón de abajo debería ser familiar de los puntos de referencia anteriores:",
"Combina las dos sentencias <code>if</code> dentro de una sentencia la cual retorne <code>\"Outside\"</code> si <code>val</code> no está entre <code>10</code> y <code>20</code>, inclusive. De otra manera, retorna <code>\"Inside\"</code>."
"When a condition for an <code>if</code> statement is true, the block of code following it is executed. What about when that condition is false? Normally nothing would happen. With an <code>else</code> statement, an alternate block of code can be executed.",
"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}"
"Cuando una condición de una sentencia <code>if</code> es verdadera, el siguiente bloque de código es ejecutado. ¿Y cuando esa condición es falsa? Normalmente nada pasaría. Con una sentencia <code>else</code>(además), un bloque alternativo de código puede ser ejecutado.",
"<blockquote>if (num > 10) {<br> return \"Más grande que 10\";<br>} else {<br> return \"10 o Menos\";<br>}</blockquote>",
"<h4>Instrucciones</h4>",
"Combina las sentencias <code>if</code> dentro de una sola sentencia <code>if/else</code>."
"<blockquote>function foo(x) {<br> if (x < 1) {<br> return \"Less than one\";<br> } else if (x < 2) {<br> return \"Less than two\";<br> } else {<br> return \"Greater than or equal to two\";<br> }<br>}</blockquote>",
"<blockquote>function bar(x) {<br> if (x < 2) {<br> return \"Less than two\";<br> } else if (x < 1) {<br> return \"Less than one\";<br> } else {<br> return \"Greater than or equal to two\";<br> }<br>}</blockquote>",
"assert(orderMyLogic(4) === \"Less than 5\", 'message: <code>orderMyLogic(4)</code> should return \"Less than 5\"');",
"assert(orderMyLogic(6) === \"Less than 10\", 'message: <code>orderMyLogic(6)</code> should return \"Less than 10\"');",
"assert(orderMyLogic(11) === \"Greater than or equal to 10\", 'message: <code>orderMyLogic(11)</code> should return \"Greater than or equal to 10\"');"
"El orden es importante en las sentencia <code>if</code> y <code>else if</code>.",
"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:",
"<blockquote>function foo(x) {<br> if (x < 1) {<br> return \"Menor que uno\";<br> } else if (x < 2) {<br> return \"Menor que dos\";<br> } else {<br> return \"Mayor o igual a dos\";<br> }<br>}</blockquote>",
"Y el segundo solo cambia el orden de las sentencias:",
"<blockquote>function bar(x) {<br> if (x < 2) {<br> return \"Menor que dos\";<br> } else if (x < 1) {<br> return \"Menor que uno\";<br> } else {<br> return \"Mayor o igual a dos\";<br> }<br>}</blockquote>",
"Mientras esas dos funciones parecen casi idénticas, si nosotros pasamos un número a ambas obtendremos diferentes salidas.",
"<blockquote>foo(0) // \"Menor que uno\"<br>bar(0) // \"Menor que dos\"</blockquote>",
"<h4>Instrucciones</h4>",
"Cambia el orden de la lógica en la función de manera que esta retorne las sentencias correctas en todos los casos."
"<code>if/else</code> statements can be chained together for complex logic. Here is <dfn>pseudocode</dfn> of multiple chained <code>if</code> / <code>else if</code> statements:",
"Las sentencias <code>if/else</code>(si/de lo contrario) pueden ser encadenadas juntas por una lógica compleja. Aquí está el <dfn>pseudocódigo</dfn> de múltiples sentencias <code>if</code> / <code>else if</code> encadenadas:",
"<blockquote>if (<em>condicion1</em>) {<br> <em>sentencias1</em><br>} else if (<em>condicion2</em>) {<br> <em>sentencias2</em><br>} else if (<em>condicion3</em>) {<br> <em>sentencias3</em><br>. . .<br>} else {<br> <em>sentenciasN</em><br>}</blockquote>",
"<h4>Instrucciones</h4>",
"Escribe sentencias <code>if</code>/<code>else if</code> encadenadas para cumplir las siguientes condiciones:",
"In the game of <a href=\"https://en.wikipedia.org/wiki/Golf\" target=\"_blank\">golf</a> each hole has a <code>par</code> meaning the average number of <code>strokes</code> 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 <code>par</code> your <code>strokes</code> are, there is a different nickname.",
"Your function will be passed <code>par</code> and <code>strokes</code> arguments. Return the correct string according to this table which lists the strokes in order of priority; top (highest) to bottom (lowest):",
"En el juego de <a href='https://es.wikipedia.org/wiki/Golf' target='_blank'>golf</a> cada hoyo tiene un <dfn>par</dfn> promedio para el número de <dfn>golpes</dfn> necesarios para meter la pelota. Dependiendo de que tan lejos por encima o por debajo del <code>par</code> estén tus <code>golpes</code>, habrá un sobrenombre diferente.",
"Tu función pasará un <code>par</code> y el número de <code>golpes</code>, 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)):",
"<table class=\"table table-striped\"><thead><tr><th>Golpes</th><th>Retorna</th></tr></thead><tbody><tr><td>1</td><td>\"Hole-in-one!\"</td></tr><tr><td><= par - 2</td><td>\"Eagle\"</td></tr><tr><td>par - 1</td><td>\"Birdie\"</td></tr><tr><td>par</td><td>\"Par\"</td></tr><tr><td>par + 1</td><td>\"Bogey\"</td></tr><tr><td>par + 2</td><td>\"Double Bogey\"</td></tr><tr><td>>= par + 3</td><td>\"Go Home!\"</td></tr></tbody></table>",
"Tanto <code>par</code> como <code>golpes</code> siempre serán numéricos y positivos."
"If you have many options to choose from, use a <code>switch</code> statement. A <code>switch</code> statement tests a value and can have many <code>case</code> statements which define various possible values. Statements are executed from the first matched <code>case</code> value until a <code>break</code> is encountered.",
"<blockquote>switch (num) {<br> case value1:<br> statement1;<br> break;<br> case value2:<br> statement2;<br> break;<br>...<br> case valueN:<br> statementN;<br> break;<br>}</blockquote>",
"<code>case</code> values are tested with strict equality (<code>===</code>). The <code>break</code> tells JavaScript to stop executing statements. If the <code>break</code> is omitted, the next statement will be executed.",
"Write a switch statement which tests <code>val</code> and sets <code>answer</code> for the following conditions:<br><code>1</code> - \"alpha\"<br><code>2</code> - \"beta\"<br><code>3</code> - \"gamma\"<br><code>4</code> - \"delta\""
"title":"Seleccionar desde diferentes opciones con la sentencia switch",
"description":[
"Si tienes varias opciones para elegir, usa una sentencia <code>switch</code>. Una sentencia <code>switch</code> prueba un valor y puede tener varias sentencias <code>case</code> las cuales definen varios posibles valores. Las sentencias son ejecutadas desde el primer valor <code>case</code> igualado hasta que se encuentr un <code>break</code>.",
"Aquí hay un <dfn>pseudocódigo</dfn> de ejemplo:",
"<blockquote>switch (num) {<br> case valor1:<br> sentencia1;<br> break;<br> case valor2:<br> sentencia2;<br> break;<br>...<br> case valorN:<br> sentenciaN;<br> break;<br>}</blockquote>",
"Los valores <code>case</code> son probados con estricta igualdad (<code>===</code>). El <code>break</code> le dice a JavaScript que pare la ejecución del bloque de sentencias en el que está. Si se omite <code>break</code>, se ejecutará la siguiente sentencia.",
"<h4>Instrucciones</h4>",
"Escribe una sentencia <code>switch</code> que pruebe <code>val</code> y establezca <code>answer</code> para las siguientes condiciones:<br><code>1</code> - \"alpha\"<br><code>2</code> - \"beta\"<br><code>3</code> - \"gamma\"<br><code>4</code> - \"delta\""
"In a <code>switch</code> statement you may not be able to specify all possible values as <code>case</code> statements. Instead, you can add the <code>default</code> statement which will be executed if no matching <code>case</code> statements are found. Think of it like the final <code>else</code> statement in an <code>if/else</code> chain.",
"Write a switch statement to set <code>answer</code> for the following conditions:<br><code>\"a\"</code> - \"apple\"<br><code>\"b\"</code> - \"bird\"<br><code>\"c\"</code> - \"cat\"<br><code>default</code> - \"stuff\""
"title":"Agregar una opción por omisión (default) en una sentencia switch",
"description":[
"En una sentencia <code>switch</code> puede que no seas capaz de especificar todos los posibles valores en las sentencias <code>case</code>. En su lugar, puedes agregar la sentencia <code>default</code> la cual será ejecutada si no es encontrada ninguna coincidencia con alguna sentencia <code>case</code>. Piensa en esto como la última sentencia <code>else</code> en una cadena <code>if/else</code>.",
"Una sentencia <code>default</code> debería ser el último caso.",
"<blockquote>switch (num) {<br> case valor1:<br> sentencia1;<br> break;<br> case valor2:<br> sentencia2;<br> break;<br>...<br> default:<br> sentenciaDefault;<br>}</blockquote>",
"<h4>Instrucciones</h4>",
"Escribe una sentencia switch para establecer <code>answer</code> para las siguientes condiciones:<br><code>\"a\"</code> - \"apple\"<br><code>\"b\"</code> - \"bird\"<br><code>\"c\"</code> - \"cat\"<br><code>default</code> - \"stuff\""
"If the <code>break</code> statement is omitted from a <code>switch</code> statement's <code>case</code>, the following <code>case</code> statement(s) are executed until a <code>break</code> is encountered. If you have multiple inputs with the same output, you can represent them in a <code>switch</code> statement like this:",
"<blockquote>switch(val) {<br> case 1:<br> case 2:<br> case 3:<br> result = \"1, 2, or 3\";<br> break;<br> case 4:<br> result = \"4 alone\";<br>}</blockquote>",
"Write a switch statement to set <code>answer</code> for the following ranges:<br><code>1-3</code> - \"Low\"<br><code>4-6</code> - \"Mid\"<br><code>7-9</code> - \"High\"",
"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}"
"title":"Múltiples opciones idénticas en una sentencias switch",
"description":[
"Si la sentencia <code>break</code> es omitida de una sentencia <code>case</code> de un <code>switch</code>, las siguientes sentencias <code>case</code> son ejecutadas hasta que sea encontrado un <code>break</code>. Si tienes multiples entradas con la misma salida, puede representarlas en una sentencia <code>switch</code> así:",
"<blockquote>switch(val) {<br> case 1:<br> case 2:<br> case 3:<br> result = \"1, 2, or 3\";<br> break;<br> case 4:<br> result = \"4 alone\";<br>}</blockquote>",
"Los casos 1, 2, y 3 producirán el mismo resultado.",
"<h4>Instrucciones</h4>",
"Escribe una sentencia <code>switch</code> para establecer <code>answer</code> para los siguientes rangos:<br><code>1-3</code> - \"Low\"<br><code>4-6</code> - \"Mid\"<br><code>7-9</code> - \"High\"",
"<strong>Nota</strong><br>Necesitarás tener una sentencia <code>case</code> por cada número en el rango."
"If you have many options to choose from, a <code>switch</code> statement can be easier to write than many chained <code>if</code>/<code>else if</code> statements. The following:",
"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}"
"Si tienes varias opciones para elegir, una sentencia <code>switch</code> puede ser más fácil de escribir que varias sentencias <code>if</code>/<code>if else</code> anidadas. Lo siguiente:",
"You may recall from <a href=\"waypoint-comparison-with-the-equality-operator\" target=\"_blank\">Comparison with the Equality Operator</a> that all comparison operators return a boolean <code>true</code> or <code>false</code> value.",
"But there's a better way to do this. Since <code>===</code> returns <code>true</code> or <code>false</code>, we can return the result of the comparison:",
"title":"Retornar valores booleanos desde funciones",
"description":[
"Tal vez recuerdes de <a href=\"waypoint-comparison-with-the-equality-operator\" target=\"_blank\">La comparación con el operador de igualdad</a> que todos los operadores de comparación retornan un valor booleano <code>true</code> (verdadero) o <code>false</code> (falso).",
"Un <dfn>anti-patrón</dfn> común es usar una sentencia <code>if/else</code> para hacer una comparación y entonces retornar <code>true</code> o <code>false</code>:",
"<blockquote>function sonIguales(a,b) {<br> if (a === b) {<br> return true;<br> } else {<br> return false;<br> }<br>}</blockquote>",
"Ya que <code>===</code> returna <code>true</code> (verdadero) o <code>false</code> (falso), podemos simplemente retornar el resultado de la comparación:",
"<blockquote>function sonIguales(a,b) {<br> return a === b;<br>}</blockquote>",
"<h4>Instrucciones</h4>",
"Arregla la función <code>isLess</code> para remover las sentencias <code>if/else</code>."
"The above outputs \"Hello\" to the console, returns \"World\", but <code>\"byebye\"</code> is never output, because the function exits at the <code>return</code> statement.",
"Modify the function <code>abTest</code> so that if <code>a</code> or <code>b</code> are less than <code>0</code> the function will immediately exit with a value of <code>undefined</code>.",
"<strong>Hint</strong><br>Remember that <a href='http://www.freeCodeCamp.com/challenges/understanding-uninitialized-variables' target='_blank'><code>undefined</code> is a keyword</a>, not a string."
"title":"Retornar un patrón temprano para funciones",
"description":[
"Cuando se alcanza una sentencia <code>return</code>, la ejecución de la presente función se detiene y el control la retorna a la ubicación de la llamada.",
"Esta presenta en consola \"Hola\", retorna \"Mundo\", pero <code>\"chaochao\"</code> nunca se presenta, porque la función sale con la sentencia <code>return</code>.",
"<h4>Instrucciones</h4>",
"Modifica la función <code>abTest</code> de manera que si <code>a</code> o <code>b</code> son menores que <code>0</code> la función saldrá inmediatamente con un valor <code>undefined</code>.",
"<strong>Pista</strong><br>Recuerda que <a href='http://www.freeCodeCamp.com/challenges/understanding-uninitialized-variables' target='_blank'><code>undefined</code> es una palabra clave</a>, no una cadena."
"In the casino game Blackjack, a player can gain an advantage over the house by keeping track of the relative number of high and low cards remaining in the deck. This is called <a href='https://en.wikipedia.org/wiki/Card_counting' target='_blank'>Card Counting</a>.",
"Having more high cards remaining in the deck favors the player. Each card is assigned a value according to the table below. When the count is positive, the player should bet high. When the count is zero or negative, the player should bet low.",
"You will write a card counting function. It will receive a <code>card</code> parameter, which can be a number or a string, and increment or decrement the global <code>count</code> variable according to the card's value (see table). The function will then return a string with the current count and the string <code>Bet</code> if the count is positive, or <code>Hold</code> if the count is zero or negative. The current count and the player's decision (<code>Bet</code> or <code>Hold</code>) should be separated by a single space.",
"<strong>Hint</strong><br>Do NOT reset <code>count</code> to 0 when value is 7, 8, or 9.<br>Do NOT return an array.<br>Do NOT include quotes (single or double) in the output."
"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}"
"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 <a href='https://en.wikipedia.org/wiki/Card_counting' target='_blank'>Conteo de Cartas</a>.",
"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.",
"Vas a escribir una función de conteo de cartas. Esta recibirá un parametro <code>card</code> (carta) e incrementa o decrementa la variable <code>count</code> (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 <code>Bet</code> si el conteo es positivo o <code>Hold</code> si el conteo es cero o negativo. El presente conteo y la desición del jugador (<code>Bet</code> o <code>Hold</code>) deben quedar separada por un único espacio.",
"<strong>Ejemplo de Salida</strong><br><code>-3 Hold<br>5 Bet</code>"
"You may have heard the term <code>object</code> before.",
"Objects are similar to <code>arrays</code>, except that instead of using indexes to access and modify their data, you access the data in objects through what are called <code>properties</code>.",
"Make an object that represents a dog called <code>myDog</code> which contains the properties <code>\"name\"</code> (a string), <code>\"legs\"</code>, <code>\"tails\"</code> and <code>\"friends\"</code>.",
"You can set these object properties to whatever values you want, as long <code>\"name\"</code> is a string, <code>\"legs\"</code> and <code>\"tails\"</code> are numbers, and <code>\"friends\"</code> is an array."
"assert((function(z){if(z.hasOwnProperty(\"name\") && z.name !== undefined && typeof z.name === \"string\"){return true;}else{return false;}})(myDog), 'message: <code>myDog</code> should contain the property <code>name</code> and it should be a <code>string</code>.');",
"assert((function(z){if(z.hasOwnProperty(\"legs\") && z.legs !== undefined && typeof z.legs === \"number\"){return true;}else{return false;}})(myDog), 'message: <code>myDog</code> should contain the property <code>legs</code> and it should be a <code>number</code>.');",
"assert((function(z){if(z.hasOwnProperty(\"tails\") && z.tails !== undefined && typeof z.tails === \"number\"){return true;}else{return false;}})(myDog), 'message: <code>myDog</code> should contain the property <code>tails</code> and it should be a <code>number</code>.');",
"assert((function(z){if(z.hasOwnProperty(\"friends\") && z.friends !== undefined && Array.isArray(z.friends)){return true;}else{return false;}})(myDog), 'message: <code>myDog</code> should contain the property <code>friends</code> and it should be an <code>array</code>.');",
"assert((function(z){return Object.keys(z).length === 4;})(myDog), 'message: <code>myDog</code> should only contain all the given properties.');"
"Es posible que haya oído el término <code>objeto</code> antes.",
"Los objetos son similares a los <code>vectores</code>, excepto que en lugar de utilizar los índices para acceder y modificar sus datos, pueden accederse mediante lo que se llama <code>propiedades</code>.",
"Los objetos son útiles para almacenar datos de manera estructurada, y pueden representar objetos del mundo real, como un gato.",
"Vamos a tratar de hacer un objeto que representa un perro, lo llamaremos <code>mydog</code> y contendrá las propiedades <code>\"name\"</code> (una cadena con el nombre), <code>\"legs\"</code> (piernas), <code>\"tails\"</code> (colas) y <code>\"friends\" (amigos)</code>. ",
"Podrás establecer estas propiedades del objeto en los valores que desees, siempre y cuando <code>\"name\"</code> sea una cadena, <code>\"legs\"</code> y <code>\"tails\"</code> sean números, y <code>\"friends\"</code> sea un vector."
"There are two ways to access the properties of an object: the dot operator (<code>.</code>) and bracket notation (<code>[]</code>), similar to an array.",
"The dot operator is what you use when you know the name of the property you're trying to access ahead of time.",
"Read in the property values of <code>testObj</code> using dot notation. Set the variable <code>hatValue</code> equal to the object's property <code>hat</code> and set the variable <code>shirtValue</code> equal to the object's property <code>shirt</code>."
"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 (<code>.</code>) y con la notación corchete (<code>[]</code>), 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 (<code>.</code>) para leer una propiedad de un objeto:",
"Lee los valores de propiedades de <code>testObj</code> usando notación punto. Asigna la variable <code>hatValue</code> igual a la propiedad objeto <code>hat</code> y asigna la variable <code>shirtValue</code> igual a la propiedad objeto <code>shirt</code>."
"The second way to access the properties of an object is bracket notation (<code>[]</code>). If the property of the object you are trying to access has a space in its name, you will need to use bracket notation.",
"Here is a sample of using bracket notation to read an object's property:",
"Read the values of the properties <code>\"an entree\"</code> and <code>\"the drink\"</code> of <code>testObj</code> using bracket notation and assign them to <code>entreeValue</code> and <code>drinkValue</code> respectively."
"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 (<code>[]</code>). 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:",
"<blockquote>var miObj = {<br> \"Nombre con espacio\": \"Kirk\",<br> \"Mas espacio\": \"Spock\"<br>};<br>miObj[\"Nombre con espacio\"]; // Kirk<br>miObj['Mas espacio']; // Spock</blockquote>",
"Nota que los nombres de propiedades con espacios tienen que estar entre comillas (apóstrofes o comillas).",
"<h4>Instrucciones</h4>",
"Lee los valores de las propiedades <code>\"an entree\"</code> y <code>\"the drink\"</code> de <code>testObj</code> usando la notación corchete."
"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.",
"Note that we do <em>not</em> use quotes around the variable name when using it to access the property because we are using the <em>value</em> of the variable, not the <em>name</em>.",
"Use the <code>playerNumber</code> variable to look up player <code>16</code> in <code>testObj</code> using bracket notation. Then assign that name to the <code>player</code> variable."
"assert(/testObj\\s*?\\[.*?\\]/.test(code),'message: You should use bracket notation to access <code>testObj</code>');",
"assert(/testObj\\s*?\\[\\s*playerNumber\\s*\\]/.test(code),'message: You should be using the variable <code>playerNumber</code> in your bracket notation');"
"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:",
"Nota que <em>no</em> usamos comillas alrededor del nombre de la variable (<code>miPerro</code>) cuando la usamos para acceder a la propiedad (<code>perros[miPerro]</code> porque estamos usando el <em>valor</em> de la variable y no su <em>nombre</em>",
"<h4>Instrucciones</h4>",
"Usa la variable <code>playerNumber</code> para buscar y asignar a <code>player</code> el jugador <code>16</code> de <code>testObj</code>, usa la notación corchete."
"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.",
"Update the <code>myDog</code> object's name property. Let's change her name from \"Coder\" to \"Happy Coder\". You can use either dot or bracket notation."
"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 <code>ourDog</code>:",
"Objects can be thought of as a key/value storage, like a dictionary. If you have tabular data, you can use an object to \"lookup\" values rather than a <code>switch</code> statement or an <code>if/else</code> chain. This is most useful when you know that your input data is limited to a certain range.",
"Convert the switch statement into an object called <code>lookup</code>. Use it to look up <code>val</code> and assign the associated string to the <code>result</code> variable."
"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 <code>switch</code> o una secuencia de <code>if/else</code>. 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:",
"Convierte la sentencia switch en una tabla de búsqueda llamada <code>lookup</code>. Usala para buscar <code>val</code> y asigna la cadena asociada a la variable <code>result</code>."
"Sometimes it is useful to check if the property of a given object exists or not. We can use the <code>.hasOwnProperty(propname)</code> method of objects to determine if that object has the given property name. <code>.hasOwnProperty()</code> returns <code>true</code> or <code>false</code> if the property is found or not.",
"Modify the function <code>checkObj</code> to test <code>myObj</code> for <code>checkProp</code>. If the property is found, return that property's value. If not, return <code>\"Not Found\"</code>."
"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 <code>.hasOwnProperty(nomprop)</code> para determinar si un objeto tiene la propiedad <code>nomprop</code>. <code>.hasOwnProperty()</code> retorna <code>true</code> o <code>false</code> si la propiedad es encontrada o no.",
"Modifica la función <code>checkObj</code> que prueba si <code>myObj</code> tiene la propiedad <code>checkProp</code>. Si la propiedad es encontrada, retorna el valor de esa propiedad. Si no, retorna <code>\"Not Found\"</code>."
"Sometimes you may want to store data in a flexible <dfn>Data Structure</dfn>. A JavaScript object is one way to handle flexible data. They allow for arbitrary combinations of <dfn>strings</dfn>, <dfn>numbers</dfn>, <dfn>booleans</dfn>, <dfn>arrays</dfn>, <dfn>functions</dfn>, and <dfn>objects</dfn>.",
"This is an array which contains one object inside. The object has various pieces of <dfn>metadata</dfn> about an album. It also has a nested <code>\"formats\"</code> 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, <code>\"artist\": \"Daft Punk\"</code> is a property that has a key of <code>\"artist\"</code> and a value of <code>\"Daft Punk\"</code>.",
"<a href='http://www.json.org/' target=_blank>JavaScript Object Notation</a> or <code>JSON</code> is a related data interchange format used to store data.",
"Add a new album to the <code>myMusic</code> array. Add <code>artist</code> and <code>title</code> strings, <code>release_year</code> number, and a <code>formats</code> array of strings."
"assert(Array.isArray(myMusic), 'message: <code>myMusic</code> should be an array');",
"assert(myMusic.length > 1, 'message: <code>myMusic</code> should have at least two elements');",
"assert(typeof myMusic[1] === 'object', 'message: <code>myMusic[1]</code> should be an object');",
"assert(Object.keys(myMusic[1]).length > 3, 'message: <code>myMusic[1]</code> should have at least 4 properties');",
"assert(myMusic[1].hasOwnProperty('artist') && typeof myMusic[1].artist === 'string', 'message: <code>myMusic[1]</code> should contain an <code>artist</code> property which is a string');",
"assert(myMusic[1].hasOwnProperty('title') && typeof myMusic[1].title === 'string', 'message: <code>myMusic[1]</code> should contain a <code>title</code> property which is a string');",
"assert(myMusic[1].hasOwnProperty('release_year') && typeof myMusic[1].release_year === 'number', 'message: <code>myMusic[1]</code> should contain a <code>release_year</code> property which is a number');",
"assert(myMusic[1].hasOwnProperty('formats') && Array.isArray(myMusic[1].formats), 'message: <code>myMusic[1]</code> should contain a <code>formats</code> property which is an array');",
"assert(myMusic[1].formats.every(function(item) { return (typeof item === \"string\")}) && myMusic[1].formats.length > 1, 'message: <code>formats</code> should be an array of strings with at least two elements');"
"Los objetos Javascript son flexibles porque permiten <dfn>Estructuras de Datos</dfn> con combinaciones arbitrarias de <dfn>cadenas</dfn>, <dfn>números</dfn>, <dfn>booleanos</dfn>, <dfn>vectores</dfn>, <dfn>funciones</dfn>, y <dfn>objetos</dfn>.",
"Este es un vector de objetos con diversos <dfn>metadatos</dfn> acerca de un álbum musical. Además tiene anidado un vector <code>formatos</code>. En el vector de nivel superior, pueden añadirse otros registros del álbum.",
"<strong>Nota</strong><br>En vectores que tengan más de un objeto, necesitarás separar un objeto de otro mediante comas.",
"<h4>Instrucciones</h4>",
"Agrega un nuevo álbum al objeto <code>myMusic</code>. Agrega las cadenas <code>artist</code> y <code>title</code>, el número <code>release_year</code> y un vector de cadenas <code>formats</code>."
"Access the <code>myStorage</code> object and assign the contents of the <code>glove box</code> property to the <code>gloveBoxContents</code> variable. Use bracket notation for properties with a space in their name."
"assert(/=\\s*myStorage\\.car\\.inside\\[\\s*(\"|')glove box\\1\\s*\\]/g.test(code), 'message: Use dot and bracket notation to access <code>myStorage</code>');"
"Accede al objeto <code>myStorage</code> para recuperar el contenido de <code>glove box</code>. Usa notación corchete para las propiedades con un espacio en su nombre."
"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.",
"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:",
"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 <code>id</code> (like <code>2548</code>), a property <code>prop</code> (like <code>\"artist\"</code> or <code>\"tracks\"</code>), and a <code>value</code> (like <code>\"Addicted to Love\"</code>) to modify the data in this collection.",
"If <code>prop</code> isn't <code>\"tracks\"</code> and <code>value</code> isn't empty (<code>\"\"</code>), update or set the <code>value</code> for that record album's property.",
"Your function must always return the entire collection object.",
"There are several rules for handling incomplete data:",
"If <code>prop</code> is <code>\"tracks\"</code> but the album doesn't have a <code>\"tracks\"</code> property, create an empty array before adding the new value to the album's corresponding property.",
"If <code>prop</code> is <code>\"tracks\"</code> and <code>value</code> isn't empty (<code>\"\"</code>), push the <code>value</code> onto the end of the album's existing <code>tracks</code> array.",
"If <code>value</code> is empty (<code>\"\"</code>), delete the given <code>prop</code> property from the album.",
"Push is an array method you can read about on <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push\" target=\"_blank\">Mozilla Developer Network</a>.",
"You may refer back to <a href=\"manipulating-complex-objects\" target=\"_blank\">Manipulating Complex Objects</a> Introducing JavaScript Object Notation (JSON) for a refresher."
"assert(updateRecords(5439, \"tracks\", \"Take a Chance on Me\")[5439][\"tracks\"].pop() === \"Take a Chance on Me\", 'message: After <code>updateRecords(5439, \"tracks\", \"Take a Chance on Me\")</code>, <code>tracks</code> should have <code>\"Take a Chance on Me\"</code> as the last element.');",
"updateRecords(2548, \"artist\", \"\"); assert(!collection[2548].hasOwnProperty(\"artist\"), 'message: After <code>updateRecords(2548, \"artist\", \"\")</code>, <code>artist</code> should not be set');",
"assert(updateRecords(1245, \"tracks\", \"Addicted to Love\")[1245][\"tracks\"].pop() === \"Addicted to Love\", 'message: After <code>updateRecords(1245, \"tracks\", \"Addicted to Love\")</code>, <code>tracks</code> should have <code>\"Addicted to Love\"</code> as the last element.');",
"assert(updateRecords(2468, \"tracks\", \"Free\")[2468][\"tracks\"][0] === \"1999\", 'message: After <code>updateRecords(2468, \"tracks\", \"Free\")</code>, <code>tracks</code> should have <code>\"1999\"</code> as the first element.');",
"updateRecords(2548, \"tracks\", \"\"); assert(!collection[2548].hasOwnProperty(\"tracks\"), 'message: After <code>updateRecords(2548, \"tracks\", \"\")</code>, <code>tracks</code> should not be set');",
"assert(updateRecords(1245, \"album\", \"Riptide\")[1245][\"album\"] === \"Riptide\", 'message: After <code>updateRecords(1245, \"album\", \"Riptide\")</code>, <code>album</code> should be <code>\"Riptide\"</code>');"
"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 <code>id</code>, una propiedad (<code>prop</code>) y un valor (<code>value</code>).",
"Para el <code>id</code> dado, en la colección <code>collection</code>:",
"Si el valor <code>value</code> no está en blanco (<code>value !== \"\"</code>) y <code>prop</code> no es <code>\"tracks\"</code> entonces actualiza o establece el valor de la propiedad <code>prop</code>.",
"Si la propiedad <code>prop</code> es <code>\"tracks\"</code> y <code>value</code> no está en blanco, empuja (<em>push</em>) el valor <code>value</code> al final del vector <code>tracks</code>.",
"Si el valor <code>value</code> está en blanco, elimina esa <code>prop</code>.",
"Siempre retorna el objeto <code>collection</code> entero.",
"<strong>Nota</strong><br>No olvides usar <code>notación corchete</code> cuando <a href=\"accessing-objects-properties-with-variables\" target=\"_blank\">accedes a propiedades de objetos con variables</a>."
"You can run the same code multiple times by using a loop.",
"Another type of JavaScript loop is called a \"<code>while loop</code>\", because it runs \"while\" a specified condition is true and stops once that condition is no longer true.",
"assert(code.match(/while/g), 'message: You should be using a <code>while</code> loop for this.');",
"assert.deepEqual(myArray, [0,1,2,3,4], 'message: <code>myArray</code> should equal <code>[0,1,2,3,4]</code>.');"
],
"type":"waypoint",
"challengeType":1,
"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í.",
"<code>var ourArray = [];</code>",
"<code>var i = 0;</code>",
"<code>while(i < 5) {</code>",
"<code> ourArray.push(i);</code>",
"<code> i++;</code>",
"<code>}</code>",
"Intentemos que un ciclo <code>while</code> empuje valores en un vector.",
"<h4>Instrucciones</h4>",
"Empuja los números de 0 a 4 para <code>myArray</code> utilizando un ciclo <code>while</code>."
"The <code>initialization</code> statement is executed one time only before the loop starts. It is typically used to define and setup your loop variable.",
"The <code>condition</code> statement is evaluated at the beginning of every loop iteration and will continue as long as it evaluates to <code>true</code>. When <code>condition</code> is <code>false</code> at the start of the iteration, the loop will stop executing. This means if <code>condition</code> starts as <code>false</code>, your loop will never execute.",
"The <code>final-expression</code> is executed at the end of each loop iteration, prior to the next <code>condition</code> check and is usually used to increment or decrement your loop counter.",
"In the following example we initialize with <code>i = 0</code> and iterate while our condition <code>i < 5</code> is true. We'll increment <code>i</code> by <code>1</code> in each loop iteration with <code>i++</code> as our <code>final-expression</code>.",
"<blockquote>var ourArray = [];<br>for (var i = 0; i < 5; i++) {<br> ourArray.push(i);<br>}</blockquote>",
"La <code>inicialización</code> se ejecuta sólo una vez antes de que empiece el ciclo. Normalmente se utiliza para definir e inicializar su variable de ciclo. ",
"La expresión <code>condición</code> se evalúa al principio de cada iteración del ciclo y continuará en el ciclo siempre y cuando sea verdadera (<code>true</code>). Cuando la <code>condición</code> sea falsa (<code>false</code>) al comienzo de la iteración, se detendrá la ejecución del ciclo. Esto significa que si la <code>condición</code> inicia en el valor falso <code>false</code>, el ciclo no se ejecutará. ",
"La <code>expresión final</code> se ejecuta al final de cada repetición del ciclo, antes del siguiente chequeo de la <code>condición</code> y se utiliza generalmente para aumentar o disminuir el contador del ciclo.",
"En el siguiente ejemplo inicializamos con <code>i = 0</code> e iteramos mientras nuestra condición <code>i <5</code> sea verdadera. Vamos a incrementar <code>i</code> en <code>1</code> en cada iteración del ciclo con <code>i++</code> como nuestra <code>expresión final</code>. ",
"title":"Itera por los números pares con un ciclo for",
"description":[
"Los ciclos <code>for</code> no siempre iteran incrementado de a uno. Cambiando nuestra <code>expresión final</code>, podemos contar los números pares.",
"Vamos a empezar con <code>i = 0</code> e iterar mientras <code>i <10</code>. Vamos a incrementar <code>i</code> de a 2 en cada iteración <code>i + = 2</code>. ",
"A for loop can also count backwards, so long as we can define the right conditions.",
"In order to count backwards by twos, we'll need to change our <code>initialization</code>, <code>condition</code>, and <code>final-expression</code>.",
"Un ciclo también puede contar hacia atrás, siempre y cuando definamos las condiciones adecuadas.",
"Para contar hacia atrás de dos en dos, tendremos que cambiar nuestra <code>inicialización</code>, la <code>condición</code> y la <code>última-expresión</code>.",
"Vamos a empezar con <code>i = 10</code> e iteraremos mientras <code>i > 0</code>. Vamos a decrementar <code>i</code> de a 2 por cada iteración con <code>i -= 2</code>. ",
"Vamos a cambiar nuestra <code>inicialización</code> y la <code>expresión final</code> para que podamos contar hacia atrás de dos en dos pero números impares.",
"<h4>Instrucciones</h4>",
"Empuja los números impares del 9 a 1 en <code>myArray</code> utilizando un ciclo <code>for</code>."
"A common task in JavaScript is to iterate through the contents of an array. One way to do that is with a <code>for</code> loop. This code will output each element of the array <code>arr</code> to the console:",
"Remember that Arrays have zero-based numbering, which means the last index of the array is length - 1. Our <dfn>condition</dfn> for this loop is <code>i < arr.length</code>, which stops when <code>i</code> is at length - 1.",
"Declare and initialize a variable <code>total</code> to <code>0</code>. Use a <code>for</code> loop to add the value of each element of the <code>myArr</code> array to <code>total</code>."
"assert(code.match(/for\\s*\\(/g).length > 1 && code.match(/myArr\\s*\\[/), 'message: You should use a <code>for</code> loop to iterate through <code>myArr</code>');",
"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 <code>for</code>. Este código imprimirá cada elemento del vector <code>arr</code> en la consola:",
"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 <dfn>condición</dfn> para este ciclo es <code>i < arr.length</code>, que lo detendrá cuando <code>i</code> sea la longitud - 1.",
"<h4>Instrucciones</h4>",
"Declara e inicializa una variable <code>total</code> en <code>0</code>. Usa un ciclo <code>for</code> para añadir el valor de cada elemento del vector <code>myArr</code> a <code>total</code>."
"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:",
"This outputs each sub-element in <code>arr</code> one at a time. Note that for the inner loop, we are checking the <code>.length</code> of <code>arr[i]</code>, since <code>arr[i]</code> is itself an array.",
"Modify function <code>multiplyAll</code> so that it multiplies the <code>product</code> variable by each number in the sub-arrays of <code>arr</code>"
"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:",
"Esto imprime cada sub-elemento en <code>arr</code> uno a la vez. Nota que en el ciclo interior, estamos comprobando la longitud <code>.length</code> de <code>arr[i]</code>, ya que <code>arr[i]</code> es por si mismo un vector.",
"<h4>Instrucciones</h4>",
"Modifica la función <code>multiplyAll</code> de manera que esta multiplique la variable <code>product</code> por cada número en los sub-vectores de <code>arr</code>"
"A <code>lookUpProfile</code> function that takes <code>name</code> and a property (<code>prop</code>) as arguments has been pre-written for you.",
"The function should check if <code>name</code> is an actual contact's <code>firstName</code> and the given property (<code>prop</code>) is a property of that contact.",
"If <code>name</code> does not correspond to any contacts then return <code>\"No such contact\"</code>",
"If <code>prop</code> does not correspond to any valid properties of a contact found to match <code>name</code> then return <code>\"No such property\"</code>"
"assert(lookUpProfile(\"Akira\", \"address\") === \"No such property\", 'message: <code>\"Akira\", \"address\"</code> should return \"No such property\"');"
"Tenemos un vector de objetos que representan diferentes personas en nuestra lista de contactos.",
"Una función <code>lookUp</code> que recibe el nombre (<code>firstName</code>) y una propiedad (<code>prop</code>) como argumentos ya ha sido escrita previamente para ti.",
"La función debe comprobar si <code>firstName</code> es un nombre (<code>firstName</code>) de algún contacto y si la propiedad dada (<code>prop</code>) es una propiedad de ese contacto.",
"Si ambos son verdaderos, entonces retorna el valor (<code>value</code>) de esa propiedad.",
"Si <code>firstName</code> no corresponde a ningun contacto entonces retorna <code>\"No such contact\"</code>",
"Si <code>prop</code> no corresponde a ninguna propiedad válida entonces retorna <code>\"No such property\"</code>",
"JavaScript has a <code>Math.random()</code> function that generates a random decimal number between <code>0</code> (inclusive) and not quite up to <code>1</code> (exclusive). Thus <code>Math.random()</code> can return a <code>0</code> but never quite return a <code>1</code>",
"<strong>Note</strong><br>Like <a href='storing-values-with-the-assignment-operator' target='_blank'>Storing Values with the Equal Operator</a>, all function calls will be resolved before the <code>return</code> executes, so we can <code>return</code> the value of the <code>Math.random()</code> function.",
"It's great that we can generate random decimal numbers, but it's even more useful if we use it to generate random whole numbers.",
"<ol><li>Use <code>Math.random()</code> to generate a random decimal.</li><li>Multiply that random decimal by <code>20</code>.</li><li>Use another function, <code>Math.floor()</code> to round the number down to its nearest whole number.</li></ol>",
"Remember that <code>Math.random()</code> can never quite return a <code>1</code> and, because we're rounding down, it's impossible to actually get <code>20</code>. This technique will give us a whole number between <code>0</code> and <code>19</code>.",
"We are calling <code>Math.random()</code>, multiplying the result by 20, then passing the value to <code>Math.floor()</code> function to round the value down to the nearest whole number.",
"assert(typeof randomWholeNum() === \"number\" && (function(){var r = randomWholeNum();return Math.floor(r) === r;})(), 'message: The result of <code>randomWholeNum</code> should be a whole 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 <code>Math.random</code> by 10 to make it a number that is between zero and nine.');",
"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 <code>Math.random()</code> para generar un decimal aleatorio.",
"Entonces vamos a multiplicar este decimal azar por 20.",
"Por último, vamos a usar otra función, <code>Math.floor()</code> para redondear el número hasta su número entero más próximo.",
"Esta técnica nos da un número entero entre 0 y 19.",
"Tenga en cuenta que debido a que estamos redondeando, es imposible obtener 20.",
"Poniendo todo junto, así es como se ve nuestro código:",
"<code>Math.floor(Math.random() * 20);</code>",
"¿Ves como <code>Math.floor</code> toma <code>(Math.random() * 20)</code> como su argumento? Así es - puedes pasar el resultado de un función como argumento de otra función.",
"<h4>Instrucciones</h4>",
"Usa esta técnica para generar y devolver un número entero aleatorio entre 0 y 9."
"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.",
"Create a function called <code>randomRange</code> that takes a range <code>myMin</code> and <code>myMax</code> and returns a random number that's greater than or equal to <code>myMin</code>, and is less than or equal to <code>myMax</code>, inclusive."
"assert(calcMin === 5, 'message: The lowest random number that can be generated by <code>randomRange</code> should be equal to your minimum number, <code>myMin</code>.');",
"assert(calcMax === 15, 'message: The highest random number that can be generated by <code>randomRange</code> should be equal to your maximum number, <code>myMax</code>.');",
"assert((function(){if(code.match(/myMax/g).length > 1 && code.match(/myMin/g).length > 2 && code.match(/Math.floor/g) && code.match(/Math.random/g)){return true;}else{return false;}})(), 'message: <code>randomRange</code> should use both <code>myMax</code> and <code>myMin</code>, and return a random number in your range.');"
"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 <code>min</code> y un número máximo <code>max</code>.",
"He aquí la fórmula que utilizaremos. Tómate un momento para leer y tratar de entender lo que el código está haciendo: ",
"<code>Math.floor(Math.random() * (max - min + 1)) + min</code>",
"Definir dos variables: <code>myMin</code> y <code>myMax</code>, y asignales valores enteros.",
"<h4>Instrucciones</h4>",
"A continuación, crea una función llamada <code>myFunction</code> que devuelva un número aleatorio mayor o igual a <code>myMin</code>, y menor o igual a <code>myMax</code>. "
"The <code>parseInt()</code> function parses a string and returns an integer. Here's an example:",
"<code>var a = parseInt(\"007\");</code>",
"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 <code>NaN</code>.",
"<hr>",
"Use <code>parseInt()</code> in the <code>convertToInteger</code> function so it converts the input string <code>str</code> into an integer, and returns it."
"The <code>parseInt()</code> 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:",
"<code>parseInt(string, radix);</code>",
"And here's an example:",
"<code>var a = parseInt(\"11\", 2);</code>",
"The radix variable says that \"11\" is in the binary system, or base 2. This example converts the string \"11\" to an integer 3.",
"<hr>",
"Use <code>parseInt()</code> in the <code>convertToInteger</code> function so it converts a binary number to an integer and returns it."
"The following function uses an if-else statement to check a condition:",
"<blockquote>function findGreater(a, b) {<br> if(a > b) {<br> return \"a is greater\";<br> }<br> else {<br> return \"b is greater\";<br> }<br>}</blockquote>",
"This can be re-written using the <code>conditional operator</code>:",
"<blockquote>function findGreater(a, b) {<br> return a > b ? \"a is greater\" : \"b is greater\";<br>}</blockquote>",
"<hr>",
"Use the <code>conditional operator</code> in the <code>checkEqual</code> function to check if two numbers are equal or not. The function should return either true or false."
"In the previous challenge, you used a single <code>conditional operator</code>. 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:",
"<blockquote>function findGreaterOrEqual(a, b) {<br> if(a === b) {<br> return \"a and b are equal\";<br> }<br> else if(a > b) {<br> return \"a is greater\";<br> }<br> else {<br> return \"b is greater\";<br> }<br>}</blockquote>",
"The above function can be re-written using multiple <code>conditional operators</code>:",
"<blockquote>function findGreaterOrEqual(a, b) {<br> return (a === b) ? \"a and b are equal\" : (a > b) ? \"a is greater\" : \"b is greater\";<br>}</blockquote>",
"<hr>",
"Use multiple <code>conditional operators</code> in the <code>checkSign</code> function to check if a number is positive, negative or zero."
"assert(/.+?\\s*?\\?\\s*?.+?\\s*?:\\s*?.+?\\s*?\\?\\s*?.+?\\s*?:\\s*?.+?/gi.test(code), 'message: <code>checkSign</code> should use multiple <code>conditional operators</code>');",
"assert(checkSign(10) === 'positive', 'message: <code>checkSign(10)</code> should return \"positive\". Note that capitalization matters');",
"assert(checkSign(-12) === 'negative', 'message: <code>checkSign(-12)</code> should return \"negative\". Note that capitalization matters');",
"assert(checkSign(0) === 'zero', 'message: <code>checkSign(0)</code> should return \"zero\". Note that capitalization matters');"