diff --git a/seed/challenges/01-responsive-web-design/applied-accessibility.json b/seed/challenges/01-responsive-web-design/applied-accessibility.json
index 2d41eff475..6caf7eb041 100644
--- a/seed/challenges/01-responsive-web-design/applied-accessibility.json
+++ b/seed/challenges/01-responsive-web-design/applied-accessibility.json
@@ -477,7 +477,7 @@
"HTML5's audio
element gives semantic meaning when it wraps sound or audio stream content in your markup. Audio content also needs a text alternative to be accessible to the deaf or hard of hearing. This can be done with nearby text on the page or a link to a transcript.",
"The audio
tag supports the controls
attribute. This shows the browser default play, pause, and other controls, and supports keyboard functionality. This is a boolean attribute, meaning it doesn't need a value, its presence on the tag turns the setting on.",
"Here's an example:",
- "
<audio id="meowClip" controls>", + "
<source src="audio/meow.mp3" type="audio/mpeg" />
<source src="audio/meow.ogg" type="audio/ogg" />
</audio>
<audio id="meowClip" controls>", "Note
<source src="audio/meow.mp3" type="audio/mpeg" />
<source src="audio/meow.ogg" type="audio/ogg" />
</audio>
audio
element after the p
. Include the controls
attribute. Then place a source
tag inside the audio
tags with the src
attribute set to \"https://s3.amazonaws.com/freecodecamp/screen-reader.mp3\" and type
attribute set to \"audio/mpeg\".",
@@ -548,7 +548,7 @@
"HTML5 introduced the figure
element, along with the related figcaption
. Used together, these items wrap a visual representation (like an image, diagram, or chart) along with its caption. This gives a two-fold accessibility boost by both semantically grouping related content, and providing a text alternative that explains the figure
.",
"For data visualizations like charts, the caption can be used to briefly note the trends or conclusions for users with visual impairments. Another challenge covers how to move a table version of the chart's data off-screen (using CSS) for screen reader users.",
"Here's an example - note that the figcaption
goes inside the figure
tags and can be combined with other elements:",
- "<figure>", + "
<img src="roundhouseDestruction.jpeg" alt="Photo of Camper Cat executing a roundhouse kick">
<br>
<figcaption>
Master Camper Cat demonstrates proper form of a roundhouse kick.
</figcaption>
</figure>
<figure>", "
<img src="roundhouseDestruction.jpeg" alt="Photo of Camper Cat executing a roundhouse kick">
<br>
<figcaption>
Master Camper Cat demonstrates proper form of a roundhouse kick.
</figcaption>
</figure>
div
tag he used to a figure
tag, and the p
tag that surrounds the caption to a figcaption
tag."
],
@@ -644,7 +644,7 @@
"The label
tag wraps the text for a specific form control item, usually the name or label for a choice. This ties meaning to the item and makes the form more readable. The for
attribute on a label
tag explicitly associates that label
with the form control and is used by screen readers.",
"You learned about radio buttons and their labels in a lesson in the Basic HTML section. In that lesson, we wrapped the radio button input element inside a label
element along with the label text in order to make the text clickable. Another way to achieve this is by using the for
attribute as explained in this lesson.",
"The value of the for
attribute must be the same as the value of the id
attribute of the form control. Here's an example:",
- "<form>", + "
<label for="name">Name:</label>
<input type="text" id="name" name="name">
</form>
<form>", "
<label for="name">Name:</label>
<input type="text" id="name" name="name">
</form>
for
attribute on the email label
that matches the id
on its input
field."
],
@@ -715,7 +715,7 @@
"The fieldset
tag surrounds the entire grouping of radio buttons to achieve this. It often uses a legend
tag to provide a description for the grouping, which is read by screen readers for each choice in the fieldset
element.",
"The fieldset
wrapper and legend
tag are not necessary when the choices are self-explanatory, like a gender selection. Using a label
with the for
attribute for each radio button is sufficient.",
"Here's an example:",
- "<form>", + "
<fieldset>
<legend>Choose one of these three items:</legend>
<input id="one" type="radio" name="items" value="one">
<label for="one">Choice One</label><br>
<input id="two" type="radio" name="items" value="two">
<label for="two">Choice Two</label><br>
<input id="three" type="radio" name="items" value="three">
<label for="three">Choice Three</label>
</fieldset>
</form>
<form>", "
<fieldset>
<legend>Choose one of these three items:</legend>
<input id="one" type="radio" name="items" value="one">
<label for="one">Choice One</label><br>
<input id="two" type="radio" name="items" value="two">
<label for="two">Choice Two</label><br>
<input id="three" type="radio" name="items" value="three">
<label for="three">Choice Three</label>
</fieldset>
</form>
for
attributes for each choice. Go Camper Cat! However, his code still needs some help. Change the div tag surrounding the radio buttons to a fieldset tag, and change the p tag inside it to a legend."
],
@@ -954,7 +954,7 @@
"Have you noticed that all of the applied accessibility challenges so far haven't used any CSS? This is to show the importance of a logical document outline, and using semantically meaningful tags around your content before introducing the visual design aspect.",
"However, CSS's magic can also improve accessibility on your page when you want to visually hide content meant only for screen readers. This happens when information is in a visual format (like a chart), but screen reader users need an alternative presentation (like a table) to access the data. CSS is used to position the screen reader-only elements off the visual area of the browser window.",
"Here's an example of the CSS rules that accomplish this:",
- ".sr-only {", + "
position: absolute;
left: -10000px;
width: 1px;
height: 1px;
top: auto;
overflow: hidden;
}
.sr-only {", "Note
position: absolute;
left: -10000px;
width: 1px;
height: 1px;
top: auto;
overflow: hidden;
}
display: none;
or visibility: hidden;
hides content for everyone, including screen reader userswidth
property in CSS. Values can be given in relative length units (such as em), absolute length units (such as px), or as a percentage of its containing parent element. Here's an example that changes the width of an image to 220px:",
- "img {", + "
width: 220px;
}
img {", "
width: 220px;
}
width
property to the entire card and set it to an absolute value of 245px. Use the fullCard
class to select the element."
],
@@ -148,7 +148,7 @@
"title": "Adjust the Height of an Element Using the height Property",
"description": [
"You can specify the height of an element using the height
property in CSS, similar to the width
property. Here's an example that changes the height of an image to 20px:",
- "img {", + "
height: 20px;
}
img {", "
height: 20px;
}
height
property to the h4
tag and set it to 25px."
],
@@ -595,7 +595,7 @@
"title": "Adjust the background-color Property of Text",
"description": [
"Instead of adjusting your overall background or the color of the text to make the foreground easily readable, you can add a background-color
to the element holding the text you want to emphasize. This challenge uses rgba()
instead of hex
codes or normal rgb()
.",
- "rgba stands for:", + "
r = red
g = green
b = blue
a = alpha/level of opacity
rgba stands for:", "The RGB values can range from 0 to 255. The alpha value can range from 1, which is fully opaque or a solid color, to 0, which is fully transparent or clear.
r = red
g = green
b = blue
a = alpha/level of opacity
rgba()
is great to use in this case, as it allows you to adjust the opacity. This means you don't have to completely block out the background.",
"You'll use background-color: rgba(45, 45, 45, 0.1)
for this challenge. It produces a dark gray color that is nearly transparent given the low opacity value of 0.1.",
":hover
pseudo-class selector. Here's the CSS to change the color
of the anchor tag to red during its hover state:",
- "a:hover {", + "
color: red;
}
a:hover {", "
color: red;
}
a
tags black. Add a rule so that when the user hovers over the a
tag, the color
is blue."
],
@@ -1269,7 +1269,7 @@
"description": [
"CSS treats each HTML element as its own box, which is usually referred to as the CSS Box Model
. Block-level items automatically start on a new line (think headings, paragraphs, and divs) while inline items sit within surrounding content (like images or spans). The default layout of elements in this way is called the normal flow
of a document, but CSS offers the position property to override it.",
"When the position of an element is set to relative
, it allows you to specify how CSS should move it relative to its current position in the normal flow of the page. It pairs with the CSS offset properties of left
or right
, and top
or bottom
. These say how many pixels, percentages, or ems to move the item away from where it is normally positioned. The following example moves the paragraph 10 pixels away from the bottom:",
- "p {", + "
position: relative;
bottom: 10px;
}
p {", "Changing an element's position to relative does not remove it from the normal flow - other elements around it still behave as if that item were in its default position.", "Note
position: relative;
bottom: 10px;
}
transform
property, along with its scale()
function. The following code example doubles the size of all the paragraph elements on the page:",
- "p {", + "
transform:scale(2);
}
p {", "
transform:scale(2);
}
ball2
to 1.5 times its original size."
],
@@ -2244,7 +2244,7 @@
"description": [
"The transform
property has a variety of functions that lets you scale, move, rotate, skew, etc., your elements. When used with pseudo-classes such as :hover
that specify a certain state of an element, the transform
property can easily add interactivity to your elements.",
"Here's an example to scale the paragraph elements to 2.1 times their original size when a user hovers over them:",
- "p:hover {", + "
transform: scale(2.1);
}
p:hover {", "
transform: scale(2.1);
}
hover
state of the div
and use the transform
property to scale the div
element to 1.1 times its original size when a user hovers over it."
],
@@ -2296,7 +2296,7 @@
"description": [
"The next function of the transform
property is skewX()
, which skews the selected element along its X (horizontal) axis by a given degree.",
"The following code skews the paragraph element by -32 degrees along the X-axis.",
- "p {", + "
transform: skewX(-32deg);
}
p {", "
transform: skewX(-32deg);
}
bottom
by 24 degrees along the X-axis by using the transform
property."
],
@@ -2457,7 +2457,7 @@
"title": "Create a More Complex Shape Using CSS and HTML",
"description": [
"One of the most popular shapes in the world is the heart shape, and this challenge creates it with raw CSS. But first, you need to understand the :before
and :after
selectors. These selectors are used to add something before or after a selected element. In the following example, a :before
selector is used to add a rectangle to an element with the class heart
:",
- ".heart:before {", + "
content: \"\";
background-color: yellow;
border-radius: 25%;
position: absolute;
height: 50px;
width: 70px;
top: -50px;
left: 5px;
}
.heart:before {", "For the
content: \"\";
background-color: yellow;
border-radius: 25%;
position: absolute;
height: 50px;
width: 70px;
top: -50px;
left: 5px;
}
:before
and :after
selectors to function properly, they must have a defined content
property. It usually has content such as a photo or text. When the :before
and :after
selectors add shapes, the content
property is still required, but it's set to an empty string.",
"In the above example, the element with the class of heart
has a :before
selector that produces a yellow rectangle with height
and width
of 50px and 70px, respectively. This rectangle has round corners due to its 25% border radius and is positioned absolutely at 5px from the left
and 50px above the top
of the element.",
"animation-name
sets the name of the animation, which is later used by @keyframes
to tell CSS which rules go with which animations.",
"animation-duration
sets the length of time for the animation.",
"@keyframes
is how to specify exactly what happens within the animation over the duration. This is done by giving CSS properties for specific \"frames\" during the animation, with percentages ranging from 0% to 100%. If you compare this to a movie, the CSS properties for 0% is how the element displays in the opening scene. The CSS properties for 100% is how the element appears at the end, right before the credits roll. Then CSS applies the magic to transition the element over the given duration to act out the scene. Here's an example to illustrate the usage of @keyframes
and the animation properties:",
- "#anim {", + "
animation-name: colorful;
animation-duration: 3s;
}
@keyframes colorful {
0% {
background-color: blue;
}
100% {
background-color: yellow;
}
}
#anim {", "For the element with the
animation-name: colorful;
animation-duration: 3s;
}
@keyframes colorful {
0% {
background-color: blue;
}
100% {
background-color: yellow;
}
}
anim
id, the code snippet above sets the animation-name
to colorful
and sets the animation-duration
to 3 seconds. Then the @keyframes
rule links to the animation properties with the name colorful
. It sets the color to blue at the beginning of the animation (0%) which will transition to yellow by the end of the animation (100%). You aren't limited to only beginning-end transitions, you can set properties for the element for any percentage between 0% and 100%.",
"rect
, by setting the animation-name
to rainbow and the animation-duration
to 4 seconds. Next, declare a @keyframes
rule, and set the background-color
at the beginning of the animation (0%
) to blue, the middle of the animation (50%
) to green, and the end of the animation (100%
) to yellow."
@@ -2618,7 +2618,7 @@
"description": [
"You can use CSS @keyframes
to change the color of a button in its hover state.",
"Here's an example of changing the width of an image on hover:",
- "<style>", + "
img:hover {
animation-name: width;
animation-duration: 500ms;
}
@keyframes width {
100% {
width: 40px;
}
}
</style>
<img src="https://bit.ly/smallgooglelogo" alt="Google's Logo" />
<style>", "
img:hover {
animation-name: width;
animation-duration: 500ms;
}
@keyframes width {
100% {
width: 40px;
}
}
</style>
<img src="https://bit.ly/smallgooglelogo" alt="Google's Logo" />
ms
stands for milliseconds, where 1000ms is equal to 1s.",
"Use CSS @keyframes
to change the background-color
of the button
element so it becomes #4791d0
when a user hovers over it. The @keyframes
rule should only have an entry for 100%
."
@@ -2726,7 +2726,7 @@
"description": [
"When elements have a specified position
, such as fixed
or relative
, the CSS offset properties right
, left
, top
, and bottom
can be used in animation rules to create movement.",
"As shown in the example below, you can push the item downwards then upwards by setting the top
property of the 50%
keyframe to 50px, but having it set to 0px for the first (0%
) and the last (100%
) keyframe.",
- "@keyframes rainbow {", + "
0% {
background-color: blue;
top: 0px;
}
50% {
background-color: green;
top: 50px;
}
100% {
background-color: yellow;
top: 0px;
}
}
@keyframes rainbow {", "
0% {
background-color: blue;
top: 0px;
}
50% {
background-color: green;
top: 50px;
}
100% {
background-color: yellow;
top: 0px;
}
}
div
animation. Using the left
offset property, add to the @keyframes
rule so rainbow starts at 0 pixels at 0%
, moves to 25 pixels at 50%
, and ends at -25 pixels at 100%
. Don't replace the top
property in the editor - the animation should have both vertical and horizontal motion."
],
diff --git a/seed/challenges/01-responsive-web-design/basic-css.json b/seed/challenges/01-responsive-web-design/basic-css.json
index 0cc9c02192..e09c6e457b 100644
--- a/seed/challenges/01-responsive-web-design/basic-css.json
+++ b/seed/challenges/01-responsive-web-design/basic-css.json
@@ -2822,7 +2822,7 @@
"You have been giving id
or class
attributes to elements that you wish to specifically style. These are known as ID and class selectors. There are other CSS Selectors you can use to select custom groups of elements to style.",
"Let's bring out CatPhotoApp again to practice using CSS Selectors.",
"For this challenge, you will use the [attr=value]
attribute selector to style the checkboxes in CatPhotoApp. This selector matches and styles elements with a specific attribute value. For example, the below code changes the margins of all elements with the attribute type
and a corresponding value of radio
:",
- "[type='radio'] {", + "
margin: 20px 0px 20px 0px;
}
[type='radio'] {", "
margin: 20px 0px 20px 0px;
}
type
attribute selector, try to give the checkboxes in CatPhotoApp a top margin of 10px and a bottom margin of 15px."
],
@@ -3759,7 +3759,7 @@
"Did you know there are other ways to represent colors in CSS? One of these ways is called hexadecimal code, or hex code
for short.",
"We usually use decimals
, or base 10 numbers, which use the symbols 0 to 9 for each digit. Hexadecimals
(or hex
) are base 16 numbers. This means it uses sixteen distinct symbols. Like decimals, the symbols 0-9 represent the values zero to nine. Then A,B,C,D,E,F represent the values ten to fifteen. Altogether, 0 to F can represent a digit in hexadecimal
, giving us 16 total possible values. You can find more information about hexadecimal numbers here.",
"In CSS, we can use 6 hexadecimal digits to represent colors, two each for the red (R), green (G), and blue (B) components. For example, #000000
is black and is also the lowest possible value. You can find more information about the RGB color system here.",
- "body {", + "
color: #000000;
}
body {", "
color: #000000;
}
black
in our body
element's background-color with its hex code
representation, #000000
."
],
@@ -4087,7 +4087,7 @@
"Instead of using six hexadecimal digits like you do with hex code, with RGB
you specify the brightness of each color with a number between 0 and 255.",
"If you do the math, the two digits for one color equal 16 times 16, which gives us 256 total values. So RGB
, which starts counting from zero, has the exact same number of possible values as hex code.",
"Here's an example of how you'd change the body background to orange using its RGB code.",
- "body {", + "
background-color: rgb(255, 165, 0);
}
body {", "
background-color: rgb(255, 165, 0);
}
body
element's background color with the RGB value for black: rgb(0, 0, 0)
"
],
diff --git a/seed/challenges/01-responsive-web-design/basic-html-and-html5.json b/seed/challenges/01-responsive-web-design/basic-html-and-html5.json
index fa2f65dd90..958e2dbe9c 100644
--- a/seed/challenges/01-responsive-web-design/basic-html-and-html5.json
+++ b/seed/challenges/01-responsive-web-design/basic-html-and-html5.json
@@ -2013,9 +2013,9 @@
"Each of your radio buttons can be nested within its own label
element. By wrapping an input
element inside of a label
element it will autoatically associate the radio button input with the label element surrounding it.",
"All related radio buttons should have the same name
attribute to create a radio button group. By creating a radio group, selecting any single radio button will automatically deselect the other buttons within the same group ensuring only one answer is provided by the user.",
"Here's an example of a radio button:",
- "<label>", + "
<input type=\"radio\" name=\"indoor-outdoor\">Indoor
</label>
<label>", "It is considered best practice to set a
<input type=\"radio\" name=\"indoor-outdoor\">Indoor
</label>
for
attribute on the label
element, with a value that matches the value of the id
attribute of the input
element. This allows assistive technologies to create a linked relationship between the label and the child input
element. For example:",
- "<label for=\"indoor\">", + "
<input id=\"indoor\" type=\"radio\" name=\"indoor-outdoor\">Indoor
</label>
<label for=\"indoor\">", "
<input id=\"indoor\" type=\"radio\" name=\"indoor-outdoor\">Indoor
</label>
indoor
and the other should have the option of outdoor
. Both should share the name
attribute of indoor-outdoor
to create a radio group."
],
@@ -2493,7 +2493,7 @@
"The !
and uppercase DOCTYPE
is important, especially for older browsers. The html
is not case sensitive.",
"Next, the rest of your HTML code needs to be wrapped in html
tags. The opening <html>
goes directly below the <!DOCTYPE html>
line, and the closing </html>
goes at the end of the page.",
"Here's an example of the page structure:",
- "<!DOCTYPE html>", + "
<html>
<!-- Your HTML code goes here -->
</html>
<!DOCTYPE html>", "
<html>
<!-- Your HTML code goes here -->
</html>
DOCTYPE
tag for HTML5 to the top of the blank HTML document in the code editor. Under it, add opening and closing html
tags, which wrap around an h1
element. The heading can include any text."
],
@@ -2522,7 +2522,7 @@
"O !
e o DOCTYPE
todo em maiúsculas são importantes, especialmente para navegadores mais velhos. O html
não é sensível a maiúsculas e minúsculas.",
"Em seguida, o resto do seu código HTML deve estar delimitado por tags html
. A tag <html>
vai diretamente abaixo da linha <!DOCTYPE html>
, e a tag </html>
vai no final da página.",
"Aqui está um exemplo da estrutura de uma página:",
- "<!DOCTYPE html>", + "
<html>
<!-- Seu código HTML vai aqui -->
</html>
<!DOCTYPE html>", "
<html>
<!-- Seu código HTML vai aqui -->
</html>
DOCTYPE
para HTML5 no topo do documento HTML em branco no editor de texto. Abaixo dela, adicione tags html
de abertura e fechamento, ao redor de um elemento h1
. O texto do h1
pode ser qualquer um."
]
@@ -2546,7 +2546,7 @@
"You can add another level of organization in your HTML document within the html
tags with the head
and body
elements. Any markup with information about your page would go into the head
tag. Then any markup with the content of the page (what displays for a user) would go into the body
tag.",
"Metadata elements, such as link
, meta
, title
, and style
, typically go inside the head
element.",
"Here's an example of a page's layout:",
- "<!DOCTYPE html>", + "
<html>
<head>
<!-- metadata elements -->
</head>
<body>
<!-- page contents -->
</body>
</html>
<!DOCTYPE html>", "
<html>
<head>
<!-- metadata elements -->
</head>
<body>
<!-- page contents -->
</body>
</html>
head
and a body
. The head
element should only include the title
, and the body
element should only include the h1
and p
."
],
@@ -2584,7 +2584,7 @@
"Você pode adicionar mais um nível de organização ao seu documento HTML dentro da tag html
com os elementos head
(cabeça) e body
(corpo). Qualquer código com informações sobre a sua página deve estar dentro da tag head
. Assim, qualquer código com o conteúdo da sua página (o que aparece para o usuário) deve estar dentro da tag body
.",
"Elementos de metadados, como link
, meta
, title
e style
, tipicamente aparecem dentro do elemento head
.",
"Aqui está um exemplo da estrutura de uma página:",
- "<!DOCTYPE html>", + "
<html>
<head>
<!-- elementos de metadados -->
</head>
<body>
<!-- conteúdo da página -->
</body>
</html>
<!DOCTYPE html>", "
<html>
<head>
<!-- elementos de metadados -->
</head>
<body>
<!-- conteúdo da página -->
</body>
</html>
head
e um body
. O elemento head
deve incluir apenas o title
, e o elemento body
deve conter apenas o h1
e o p
."
]
diff --git a/seed/challenges/01-responsive-web-design/css-grid.json b/seed/challenges/01-responsive-web-design/css-grid.json
index 2f1e82f20f..715d4c9090 100644
--- a/seed/challenges/01-responsive-web-design/css-grid.json
+++ b/seed/challenges/01-responsive-web-design/css-grid.json
@@ -66,7 +66,7 @@
"title": "Add Columns with grid-template-columns",
"description": [
"Simply creating a grid element doesn't get you very far. You need to define the structure of the grid as well. To add some columns to the grid, use the grid-template-columns
property on a grid container as demonstrated below:",
- ".container {", + "
display: grid;
grid-template-columns: 50px 50px;
}
.container {", "This will give your grid two columns that are 50px wide each.", "The number of parameters given to the
display: grid;
grid-template-columns: 50px 50px;
}
grid-template-columns
property indicates the number of columns in the grid, and the value of each parameter indicates the width of each column.",
"grid-template-areas
on the container like this:",
- "grid-template-areas:", + "
\"header header header\"
\"advert content content\"
\"footer footer footer\";
grid-template-areas:", "The code above merges the top three cells together into an area named
\"header header header\"
\"advert content content\"
\"footer footer footer\";
header
, the bottom three cells into a footer
area, and it makes two areas in the middle row; advert
and content
.",
"Note.
) to designate an empty cell in the grid.",
diff --git a/seed/challenges/01-responsive-web-design/responsive-web-design.json b/seed/challenges/01-responsive-web-design/responsive-web-design.json
index f1015442a7..82c40c65b0 100644
--- a/seed/challenges/01-responsive-web-design/responsive-web-design.json
+++ b/seed/challenges/01-responsive-web-design/responsive-web-design.json
@@ -75,7 +75,7 @@
"Making images responsive with CSS is actually very simple. Instead of applying an absolute width to an element:",
"img { width: 720px; }
",
"You can use:",
- "img {", + "
max-width: 100%;
display: block;
height: auto;
}
img {", "The
max-width: 100%;
display: block;
height: auto;
}
max-width
property of 100% scales the image to fit the width of its container, but the image won't stretch wider than its original width. Setting the display
property to block changes the image from an inline element (its default), to a block element on its own line. The height
property of auto keeps the original aspect ratio of the image.",
"img
tag to make it responsive to the size of its container. It should display as a block-level element, it should fit the full width of its container without stretching, and it should keep its original aspect ratio."
@@ -105,7 +105,7 @@
"Fazer com que imagens sejam responsivas é muito simples com CSS. Ao invés de aplicar uma largura absoluta a um elemento:",
"img { width: 720px; }
",
"Você pode usar:",
- "img {", + "
max-width: 100%;
display: block;
height: auto;
}
img {", "A propriedade
max-width: 100%;
display: block;
height: auto;
}
max-width
em 100% ajusta o tamanho da imagem para preencher a largura de seu container, mas a imagem não irá esticar mais que sua largura original. Ajustando a propriedade display
como block muda imagem de elemento inline (o padrão) para um elemento block com uma linha própria. A propriedade height
na configuração auto mantem a proporção original da imagem.",
"img
para torná-la responsiva com relação ao tamanho do seu container. Ela deve ser exibida como um elemento de nível block, e deve preencher toda a largura de seu container sem esticar, mantendo as proporções originais."
@@ -135,7 +135,7 @@
"description": [
"The simplest way to make your images appear \"retina\" (and optimize them for retina displays) is to define their width
and height
values as only half of what the original file is.",
"Here is an example of an image that is only using half of the original height and width:",
- "<style>", + "
img { height: 250px; width: 250px; }
</style>
<img src="coolPic500x500" alt="A most excellent picture">
<style>", "
img { height: 250px; width: 250px; }
</style>
<img src="coolPic500x500" alt="A most excellent picture">
width
and height
of the img
tag to half of their original values. In this case, both the original height
and the original width
are 200px."
],
@@ -159,7 +159,7 @@
"description": [
"A maneira mais simples de fazer com que suas imagens tenham uma aparência \"retina\" (e otimizadas para telas retina) é definindo seus valores de width
e height
como somente metade do tamanho original dos arquivos.",
"Segue um exemplo de imagem que possui somente metade dos valores originais de altura e largura:",
- "<style>", + "
img { height: 250px; width: 250px; }
</style>
<img src="coolPic500x500" alt="A most excellent picture">
<style>", "
img { height: 250px; width: 250px; }
</style>
<img src="coolPic500x500" alt="A most excellent picture">
width
e height
da tag img
como metade do seu tamanho original. Nesse caso, o valor original de height
e o valor original de width
são de 200px."
]
diff --git a/seed/challenges/02-javascript-algorithms-and-data-structures/basic-data-structures.json b/seed/challenges/02-javascript-algorithms-and-data-structures/basic-data-structures.json
index c858270f74..f82a4e6824 100644
--- a/seed/challenges/02-javascript-algorithms-and-data-structures/basic-data-structures.json
+++ b/seed/challenges/02-javascript-algorithms-and-data-structures/basic-data-structures.json
@@ -12,7 +12,7 @@
"let simpleArray = ['one', 2, 'three’, true, false, undefined, null];", "All array's have a length property, which as shown above, can be very easily accessed with the syntax
console.log(simpleArray.length);
// logs 7
Array.length
.",
"A more complex implementation of an array can be seen below. This is known as a multi-dimensional array, or an array that contains other arrays. Notice that this array also contains JavaScript objects, which we will examine very closely in our next section, but for now, all you need to know is that arrays are also capable of storing complex objects.",
- "let complexArray = [", + "
[
{
one: 1,
two: 2
},
{
three: 3,
four: 4
}
],
[
{
a: \"a\",
b: \"b\"
},
{
c: \"c\",
d: “d”
}
]
];
let complexArray = [", "
[
{
one: 1,
two: 2
},
{
three: 3,
four: 4
}
],
[
{
a: \"a\",
b: \"b\"
},
{
c: \"c\",
d: “d”
}
]
];
yourArray
. Complete the statement by assigning an array of at least 5 elements in length to the yourArray
variable. Your array should contain at least one string, one number, and one boolean."
],
@@ -641,7 +641,7 @@
"title": "Add Key-Value Pairs to JavaScript Objects",
"description": [
"At their most basic, objects are just collections of key-value pairs, or in other words, pieces of data mapped to unique identifiers that we call properties or keys. Let's take a look at a very simple example:",
- "let FCC_User = {", + "
username: 'awesome_coder',
followers: 572,
points: 1741,
completedProjects: 15
};
let FCC_User = {", "The above code defines an object called
username: 'awesome_coder',
followers: 572,
points: 1741,
completedProjects: 15
};
FCC_User
that has four properties, each of which map to a specific value. If we wanted to know the number of followers
FCC_User
has, we can access that property by writing:",
"let userData = FCC_User.followers;", "This is called dot notation. Alternatively, we can also access the property with brackets, like so:", @@ -704,7 +704,7 @@ "title": "Modify an Object Nested Within an Object", "description": [ "Now let's take a look at a slightly more complex object. Object properties can be nested to an arbitrary depth, and their values can be any type of data supported by JavaScript, including arrays and even other objects. Consider the following:", - "
// userData equals 572
let nestedObject = {", + "
id: 28802695164,
date: 'December 31, 2016',
data: {
totalUsers: 99,
online: 80,
onlineStatus: {
active: 67,
away: 13
}
}
};
let nestedObject = {", "
id: 28802695164,
date: 'December 31, 2016',
data: {
totalUsers: 99,
online: 80,
onlineStatus: {
active: 67,
away: 13
}
}
};
nestedObject
has three unique keys: id
, whose value is a number, date
whose value is a string, and data
, whose value is an object which has yet another object nested within it. While structures can quickly become complex, we can still use the same notations to access the information we need.",
"userActivity
, which includes another object nested within it. You can modify properties on this nested object in the same way you modified properties in the last challenge. Set the value of the online
key to 45
."
@@ -943,7 +943,7 @@
"title": " Iterate Through the Keys of an Object with a for...in Statement",
"description": [
"Sometimes you may need to iterate through all the keys within an object. This requires a specific syntax in JavaScript called a for...in statement. For our users
object, this could look like:",
- "for (let user in users) {", + "
console.log(user);
};
// logs:
Alan
Jeff
Sarah
Ryan
for (let user in users) {", "In this statement, we defined a variable
console.log(user);
};
// logs:
Alan
Jeff
Sarah
Ryan
user
, and as you can see, this variable was reset during each iteration to each of the object's keys as the statement looped through the object, resulting in each user's name being printed to the console.",
"NOTE://
will tell JavaScript to ignore the remainder of the text on the current line:",
"// This is an in-line comment.", "You can make a multi-line comment beginning with
/*
and ending with */
:",
- "/* This is a", + "
multi-line comment */
/* This is a", "Best Practice
multi-line comment */
var arr = [", + "
[1,2,3],
[4,5,6],
[7,8,9],
[[10,11,12], 13, 14]
];
arr[3]; // equals [[10,11,12], 13, 14]
arr[3][0]; // equals [10,11,12]
arr[3][0][1]; // equals 11
var arr = [", "Note
[1,2,3],
[4,5,6],
[7,8,9],
[[10,11,12], 13, 14]
];
arr[3]; // equals [[10,11,12], 13, 14]
arr[3][0]; // equals [10,11,12]
arr[3][0][1]; // equals 11
array [0][0]
and even this array [0] [0]
is not allowed. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.",
"myArray
such that myData
is equal to 8
."
@@ -2544,7 +2544,7 @@
"description": [
"Una manera de pensar un vector multi-dimensional, es como un vector de vectores. Cuando usas corchetes para acceder a tu vector, el primer conjunto de brackets se refiere a las entradas en el vector más externo y cada nivel subsecuente de brackets se refiere al siguiente nivel de vectores internos.",
"Ejemplo",
- "var vec = [", + "
[1,2,3],
[4,5,6],
[7,8,9],
[[10,11,12], 13, 14]
];
vec[0]; // es igual [1,2,3]
vec[1][2]; // es igual 6
vec[3][0][1]; // es igual 11
var vec = [", "
[1,2,3],
[4,5,6],
[7,8,9],
[[10,11,12], 13, 14]
];
vec[0]; // es igual [1,2,3]
vec[1][2]; // es igual 6
vec[3][0][1]; // es igual 11
myArray
usando la notación corchete de modo que myData sea igual a 8
"
]
@@ -2901,7 +2901,7 @@
"description": [
"In JavaScript, we can divide up our code into reusable parts called functions.",
"Here's an example of a function:",
- "function functionName() {", + "
console.log(\"Hello World\");
}
function functionName() {", "You can call or invoke this function by using its name followed by parentheses, like this:", "
console.log(\"Hello World\");
}
functionName();
",
"Each time the function is called it will print out the message \"Hello World\"
on the dev console. All of the code between the curly braces will be executed every time the function is called.",
@@ -2998,7 +2998,7 @@
"description": [
"Parameters are variables that act as placeholders for the values that are to be input to a function when it is called. When a function is defined, it is typically defined along with one or more parameters. The actual values that are input (or \"passed\") into a function when it is called are known as arguments.",
"Here is a function with two parameters, param1
and param2
:",
- "function testFun(param1, param2) {", + "
console.log(param1, param2);
}
function testFun(param1, param2) {", "Then we can call
console.log(param1, param2);
}
testFun
:",
"testFun(\"Hello\", \"World\");
",
"We have passed two arguments, \"Hello\"
and \"World\"
. Inside the function, param1
will equal \"Hello\" and param2
will equal \"World\". Note that you could call testFun
again with different arguments and the parameters would take on the value of the new arguments.",
@@ -3034,7 +3034,7 @@
"description": [
"Los parámetros son variables que actúan como marcadores de lugar para los valores que han de ser entrada para una función cuando esta es llamada. Cuando una función es definida, es típicamente definida con uno o más parámetros. Los valores actuales que son entrada (or \"pasados\") dentro de una función cuando esta es llamada son concidos como argumentos.",
"Aquí hay una función con dos parámetros, param1
y param2
:",
- "function testFun(param1, param2) {", + "
console.log(param1, param2);
}
function testFun(param1, param2) {", "Entonces nosotros podemos llamar
console.log(param1, param2);
}
testFun
:",
"testFun(\"Hello\", \"World\");
",
"Nosotros hemos pasado dos argumentos, \"Hello\"
y \"World\"
. Dentro de la función, param1
será igual a \"Hello\" y param2
será igual a \"World\". Nota que puedes llamar testFun
otra vez con argumentos diferentes y los parámetros asumirían el valor de los nuevos argumentos.",
@@ -3201,7 +3201,7 @@
"description": [
"Variables which are declared within a function, as well as the function parameters have local scope. That means, they are only visible within that function.",
"Here is a function myTest
with a local variable called loc
.",
- "function myTest() {", + "
var loc = \"foo\";
console.log(loc);
}
myTest(); // logs \"foo\"
console.log(loc); // loc is not defined
function myTest() {", "
var loc = \"foo\";
console.log(loc);
}
myTest(); // logs \"foo\"
console.log(loc); // loc is not defined
loc
is not defined outside of the function.",
"myVar
inside myLocalScope
. Run the tests and then follow the instructions commented out in the editor.",
@@ -3228,7 +3228,7 @@
"description": [
"Las variables que son declaradas dentro de una función, así como los parámetros de la función tienen alcance local. Eso significa que solo son visibles dentro de esa función.",
"Aquí está una función myTest
con una variable local llamada loc
.",
- "function myTest() {", + "
var loc = \"foo\";
console.log(loc);
}
myTest(); // \"foo\"
console.log(loc); // \"undefined\"
function myTest() {", "
var loc = \"foo\";
console.log(loc);
}
myTest(); // \"foo\"
console.log(loc); // \"undefined\"
loc
no está definida fuera de la función.",
"myVar
dentro de myLocalScope
"
@@ -3289,7 +3289,7 @@
"description": [
"It is possible to have both local and global variables with the same name. When you do this, the local
variable takes precedence over the global
variable.",
"In this example:",
- "var someVar = \"Hat\";", + "
function myFun() {
var someVar = \"Head\";
return someVar;
}
var someVar = \"Hat\";", "The function
function myFun() {
var someVar = \"Head\";
return someVar;
}
myFun
will return \"Head\"
because the local
version of the variable is present.",
"myOutfit
function to override the value of outerWear
with \"sweater\"
."
@@ -3319,7 +3319,7 @@
"description": [
"Es posible tener variables locales y globales con el mismo nombre. Cuando tu haces esto, la variable local
toma precedencia sobre la variable global
.",
"En este ejemplo:",
- "var algunaVar = \"Sombrero\";", + "
function miFun() {
var algunaVar = \"Cabeza\";
return algunaVar;
}
var algunaVar = \"Sombrero\";", "La función
function miFun() {
var algunaVar = \"Cabeza\";
return algunaVar;
}
miFun
regresará \"Cabeza\"
porque la versión local
de la variable tiene precedencia.",
"myOutfit
para sobreescribir el valor de outerWear
con \"sweater\"
."
@@ -3357,7 +3357,7 @@
"description": [
"We can pass values into a function with arguments. You can use a return
statement to send a value back out of a function.",
"Example",
- "function plusThree(num) {", + "
return num + 3;
}
var answer = plusThree(5); // 8
function plusThree(num) {", "
return num + 3;
}
var answer = plusThree(5); // 8
plusThree
takes an argument for num
and returns a value equal to num + 3
.",
"timesFive
that accepts one argument, multiplies it by 5
, and returns the new value. See the last line in the editor for an example of how you can test your timesFive
function."
@@ -3395,7 +3395,7 @@
"description": [
"Podemos pasar valores a una función mediante los argumentos. Puedes usar una sentencia return
para enviar un valor de vuelta de una función.",
"Ejemplo",
- "function masTres(num) {", + "
return num + 3;
}
var respuesta = masTres(5); // 8
function masTres(num) {", "
return num + 3;
}
var respuesta = masTres(5); // 8
masTres
toma un argumento que es num
y retorna un valor igual a num + 3
.",
"timesFive
que acepte un argumento, lo multiplique por 5
y retorne el nuevo valor."
@@ -3430,7 +3430,7 @@
"description": [
"A function can include the return
statement but it does not have to. In the case that the function doesn't have a return
statement, when you call it, the function processes the inner code but the returned value is undefined
.",
"Example",
- "var sum = 0;", + "
function addSum(num) {
sum = sum + num;
}
var returnedValue = addSum(3); // sum will be modified but returned value is undefined
var sum = 0;", "
function addSum(num) {
sum = sum + num;
}
var returnedValue = addSum(3); // sum will be modified but returned value is undefined
addSum
is a function without a return
statement. The function will change the global sum
variable but the returned value of the function is undefined
",
"addFive
without any arguments. This function adds 5 to the sum
variable, but its returned value is undefined
."
@@ -3719,9 +3719,9 @@
"If
statements are used to make decisions in code. The keyword if
tells JavaScript to execute the code in the curly braces under certain conditions, defined in the parentheses. These conditions are known as Boolean
conditions and they may only be true
or false
.",
"When the condition evaluates to true
, the program executes the statement inside the curly braces. When the Boolean condition evaluates to false
, the statement inside the curly braces will not execute.",
"Pseudocode",
- "if (condition is true) {", + "
statement is executed
}
if (condition is true) {", "Example", - "
statement is executed
}
function test (myCondition) {", + "
if (myCondition) {
return \"It was true\";
}
return \"It was false\";
}
test(true); // returns \"It was true\"
test(false); // returns \"It was false\"
function test (myCondition) {", "When
if (myCondition) {
return \"It was true\";
}
return \"It was false\";
}
test(true); // returns \"It was true\"
test(false); // returns \"It was false\"
test
is called with a value of true
, the if
statement evaluates myCondition
to see if it is true
or not. Since it is true
, the function returns \"It was true\"
. When we call test
with a value of false
, myCondition
is not true
and the statement in the curly braces is not executed and the function returns \"It was false\"
.",
"if
statement inside the function to return \"Yes, that was true\"
if the parameter wasThatTrue
is true
and return \"No, that was false\"
otherwise."
@@ -3809,10 +3809,10 @@
"description": [
"There are many Comparison Operators in JavaScript. All of these operators return a boolean true
or false
value.",
"The most basic operator is the equality operator ==
. The equality operator compares two values and returns true
if they're equivalent or false
if they are not. Note that equality is different from assignment (=
), which assigns the value at the right of the operator to a variable in the left.",
- "function equalityTest(myVal) {", + "
if (myVal == 10) {
return \"Equal\";
}
return \"Not Equal\";
}
function equalityTest(myVal) {", "If
if (myVal == 10) {
return \"Equal\";
}
return \"Not Equal\";
}
myVal
is equal to 10
, the equality operator returns true
, so the code in the curly braces will execute, and the function will return \"Equal\"
. Otherwise, the function will return \"Not Equal\"
.",
"In order for JavaScript to compare two different data types
(for example, numbers
and strings
), it must convert one type to another. This is known as \"Type Coercion\". Once it does, however, it can compare terms as follows:",
- "1 == 1 // true", + "
1 == 2 // false
1 == '1' // true
\"3\" == 3 // true
1 == 1 // true", "
1 == 2 // false
1 == '1' // true
\"3\" == 3 // true
equality operator
to the indicated line so that the function will return \"Equal\" when val
is equivalent to 12
"
],
@@ -3845,10 +3845,10 @@
"description": [
"Hay muchos Operadores de Comparación en JavaScript. Todos estos operadores retornan un valor booleano true
(verdadero) o false
(falso).",
"El operador más básico es el operador de igualdad ==
. El operador de igualdad compara dos valores y retorna true
si son equivalentes o false
si no lo son. Nota que la igualdad es diferente de la asignación (=
), la cual asigna el valor a la derecha del operador a la variable en la izquierda.",
- "function pruebaIgualdad(miVal) {", + "
if (miVal == 10) {
return \"Igual\";
}
return \"No Es Igual\";
}
function pruebaIgualdad(miVal) {", "Si
if (miVal == 10) {
return \"Igual\";
}
return \"No Es Igual\";
}
miVal
es igual a 10
, el operador de igualdad retornará true
(verdadero), así el código entre llaves será ejecutado y la función retornará \"Equal\"
. De otra manera, la función retornará \"Not Equal\"
.",
"Para que JavaScript pueda comparar dos tipos de datos
diferentes (por ejemplo, números
y cadenas de texto
), debe convertir un tipo a otro. Una vez que lo hace, sin embargo, puede comparar términos de la siguiente manera:",
- "1 == 1 // true", + "
1 == 2 // false
1 == '1' // true
\"3\" == 3 // true
1 == 1 // true", "
1 == 2 // false
1 == '1' // true
\"3\" == 3 // true
operador de igualdad
a la línea indicada de manera que la función retornará \"Equal\" cuando val
sea equivalente a 12
"
]
@@ -4339,7 +4339,7 @@
"description": [
"The less than operator (<
) compares the values of two numbers. If the number to the left is less than the number to the right, it returns true
. Otherwise, it returns false
. Like the equality operator, less than operator converts data types while comparing.",
"Examples",
- "2 < 5 // true", + "
'3' < 7 // true
5 < 5 // false
3 < 2 // false
'8' < 4 // false
2 < 5 // true", "
'3' < 7 // true
5 < 5 // false
3 < 2 // false
'8' < 4 // false
less than
operator to the indicated lines so that the return statements make sense."
],
@@ -4384,7 +4384,7 @@
"description": [
"El operador menor que (<
) compara los valores de dos números. Si el número a la izquierda es menor que el número de la derecha, este retorna true
(verdadero). De otra manera, este retorna false
(falso). Como el operador de igualdad, el operador menor que convierte tipos de datos mientra compara.",
"Ejemplos",
- "2 < 5 // true", + "
'3' < 7 // true
5 < 5 // false
3 < 2 // false
'8' < 4 // false
2 < 5 // true", "
'3' < 7 // true
5 < 5 // false
3 < 2 // false
'8' < 4 // false
menor que
a las líneas indicadas de modo que las sentencias de retorno tengan sentido."
]
@@ -4422,7 +4422,7 @@
"description": [
"The less than or equal to
operator (<=
) compares the values of two numbers. If the number to the left is less than or equal to the number to the right, it returns true
. If the number on the left is greater than the number on the right, it returns false
. Like the equality operator, less than or equal to
converts data types.",
"Examples",
- "4 <= 5 // true", + "
'7' <= 7 // true
5 <= 5 // true
3 <= 2 // false
'8' <= 4 // false
4 <= 5 // true", "
'7' <= 7 // true
5 <= 5 // true
3 <= 2 // false
'8' <= 4 // false
less than or equal to
operator to the indicated lines so that the return statements make sense."
],
@@ -4471,7 +4471,7 @@
"description": [
"El operador menor o igual
(<=
) compara los valores de dos números. Si el número a la izquierda es menor o igual que el número de la derecha, este retorna true
(verdadero). Si el número a la izquierda es mayor que el número de la derecha, este retorna false
(falso). Al igual que el operador de igualdad, menor o igual
convierte tipos de datos.",
"Ejemplos",
- "4 <= 5 // true", + "
'7' <= 7 // true
5 <= 5 // true
3 <= 2 // false
'8' <= 4 // false
4 <= 5 // true", "
'7' <= 7 // true
5 <= 5 // true
3 <= 2 // false
'8' <= 4 // false
menor o igual
a las líneas indicadas de modo que las sentencias de retorno tengan sentido."
]
@@ -4510,9 +4510,9 @@
"description": [
"Sometimes you will need to test more than one thing at a time. The logical and operator (&&
) returns true
if and only if the operands to the left and right of it are true.",
"The same effect could be achieved by nesting an if statement inside another if:",
- "if (num > 5) {", + "
if (num < 10) {
return \"Yes\";
}
}
return \"No\";
if (num > 5) {", "will only return \"Yes\" if
if (num < 10) {
return \"Yes\";
}
}
return \"No\";
num
is greater than 5
and less than 10
. The same logic can be written as:",
- "if (num > 5 && num < 10) {", + "
return \"Yes\";
}
return \"No\";
if (num > 5 && num < 10) {", "
return \"Yes\";
}
return \"No\";
\"Yes\"
if val
is less than or equal to 50
and greater than or equal to 25
. Otherwise, will return \"No\"
."
],
@@ -4569,9 +4569,9 @@
"description": [
"A veces necesitarás probar más de una cosa a la vez. El operador lógico y (&&
) retorna true
(verdadero) si y solo si los operandos a la izquierda y derecha de este son verdaderos.",
"El mismo efecto podría lograrse anidando una sentencia if dentro de otro if:",
- "if (num > 5) {", + "
if (num < 10) {
return \"Yes\";
}
}
return \"No\";
if (num > 5) {", "solo retornará \"Yes\" si
if (num < 10) {
return \"Yes\";
}
}
return \"No\";
num
está entre 6
y 9
(6 y 9 incluidos). La misma lógica puede ser escrita como:",
- "if (num > 5 && num < 10) {", + "
return \"Yes\";
}
return \"No\";
if (num > 5 && num < 10) {", "
return \"Yes\";
}
return \"No\";
\"Yes\"
si val
es menor o igual a 50
y mayor o igual a 25
. De otra manera, retornará \"No\"
."
]
@@ -4611,9 +4611,9 @@
"The logical or operator (||
) returns true
if either of the operands is true
. Otherwise, it returns false
.",
"The logical or operator is composed of two pipe symbols (|
). This can typically be found between your Backspace and Enter keys.",
"The pattern below should look familiar from prior waypoints:",
- "if (num > 10) {", + "
return \"No\";
}
if (num < 5) {
return \"No\";
}
return \"Yes\";
if (num > 10) {", "will return \"Yes\" only if
return \"No\";
}
if (num < 5) {
return \"No\";
}
return \"Yes\";
num
is between 5
and 10
(5 and 10 included). The same logic can be written as:",
- "if (num > 10 || num < 5) {", + "
return \"No\";
}
return \"Yes\";
if (num > 10 || num < 5) {", "
return \"No\";
}
return \"Yes\";
if
statements into one statement which returns \"Outside\"
if val
is not between 10
and 20
, inclusive. Otherwise, return \"Inside\"
."
],
@@ -4670,9 +4670,9 @@
"description": [
"El operador lógico o (||
) retorna true
(verdadero) si cualquiera de los operandos es true
(verdadero). De otra manera, este retorna false
(falso).",
"El patrón de abajo debería ser familiar de los puntos de referencia anteriores:",
- "if (num > 10) {", + "
return \"No\";
}
if (num < 5) {
return \"No\";
}
return \"Yes\";
if (num > 10) {", "retornará \"Yes\" solo si
return \"No\";
}
if (num < 5) {
return \"No\";
}
return \"Yes\";
num
está entre 5
y 10
(5 y 10 incluidos). La misma lógica puede ser escrita como:",
- "if (num > 10 || num < 5) {", + "
return \"No\";
}
return \"Yes\";
if (num > 10 || num < 5) {", "
return \"No\";
}
return \"Yes\";
if
dentro de una sentencia la cual retorne \"Outside\"
si val
no está entre 10
y 20
, inclusive. De otra manera, retorna \"Inside\"
."
]
@@ -4712,7 +4712,7 @@
"title": "Introducing Else Statements",
"description": [
"When a condition for an if
statement is true, the block of code following it is executed. What about when that condition is false? Normally nothing would happen. With an else
statement, an alternate block of code can be executed.",
- "if (num > 10) {", + "
return \"Bigger than 10\";
} else {
return \"10 or Less\";
}
if (num > 10) {", "
return \"Bigger than 10\";
} else {
return \"10 or Less\";
}
if
statements into a single if/else
statement."
],
@@ -4756,7 +4756,7 @@
"title": "Introducción de las sentencias else",
"description": [
"Cuando una condición de una sentencia if
es verdadera, el siguiente bloque de código es ejecutado. ¿Y cuando esa condición es falsa? Normalmente nada pasaría. Con una sentencia else
(además), un bloque alternativo de código puede ser ejecutado.",
- "if (num > 10) {", + "
return \"Más grande que 10\";
} else {
return \"10 o Menos\";
}
if (num > 10) {", "
return \"Más grande que 10\";
} else {
return \"10 o Menos\";
}
if
dentro de una sola sentencia if/else
."
]
@@ -4798,7 +4798,7 @@
"title": "Introducing Else If Statements",
"description": [
"If you have multiple conditions that need to be addressed, you can chain if
statements together with else if
statements.",
- "if (num > 15) {", + "
return \"Bigger than 15\";
} else if (num < 5) {
return \"Smaller than 5\";
} else {
return \"Between 5 and 15\";
}
if (num > 15) {", "
return \"Bigger than 15\";
} else if (num < 5) {
return \"Smaller than 5\";
} else {
return \"Between 5 and 15\";
}
else if
statements."
],
@@ -4842,7 +4842,7 @@
"title": "Introducción de las sentencias else if",
"description": [
"Si tienes múltiples condiciones que deben abordarse, puedes encadenar sentencias if
juntas con sentencias else if
.",
- "if (num > 15) {", + "
return \"Más grande que 15\";
} else if (num < 5) {
return \"Más pequeño que 5\";
} else {
return \"Entre 5 y 15\";
}
if (num > 15) {", "
return \"Más grande que 15\";
} else if (num < 5) {
return \"Más pequeño que 5\";
} else {
return \"Entre 5 y 15\";
}
else if
."
]
@@ -4883,9 +4883,9 @@
"The function is executed from top to bottom so you will want to be careful of what statement comes first.",
"Take these two functions as an example.",
"Here's the first:",
- "function foo(x) {", + "
if (x < 1) {
return \"Less than one\";
} else if (x < 2) {
return \"Less than two\";
} else {
return \"Greater than or equal to two\";
}
}
function foo(x) {", "And the second just switches the order of the statements:", - "
if (x < 1) {
return \"Less than one\";
} else if (x < 2) {
return \"Less than two\";
} else {
return \"Greater than or equal to two\";
}
}
function bar(x) {", + "
if (x < 2) {
return \"Less than two\";
} else if (x < 1) {
return \"Less than one\";
} else {
return \"Greater than or equal to two\";
}
}
function bar(x) {", "While these two functions look nearly identical if we pass a number to both we get different outputs.", "
if (x < 2) {
return \"Less than two\";
} else if (x < 1) {
return \"Less than one\";
} else {
return \"Greater than or equal to two\";
}
}
foo(0) // \"Less than one\"", "
bar(0) // \"Less than two\"
function foo(x) {", + "
if (x < 1) {
return \"Menor que uno\";
} else if (x < 2) {
return \"Menor que dos\";
} else {
return \"Mayor o igual a dos\";
}
}
function foo(x) {", "Y el segundo solo cambia el orden de las sentencias:", - "
if (x < 1) {
return \"Menor que uno\";
} else if (x < 2) {
return \"Menor que dos\";
} else {
return \"Mayor o igual a dos\";
}
}
function bar(x) {", + "
if (x < 2) {
return \"Menor que dos\";
} else if (x < 1) {
return \"Menor que uno\";
} else {
return \"Mayor o igual a dos\";
}
}
function bar(x) {", "Mientras esas dos funciones parecen casi idénticas, si nosotros pasamos un número a ambas obtendremos diferentes salidas.", "
if (x < 2) {
return \"Menor que dos\";
} else if (x < 1) {
return \"Menor que uno\";
} else {
return \"Mayor o igual a dos\";
}
}
foo(0) // \"Menor que uno\"", "
bar(0) // \"Menor que dos\"
if/else
statements can be chained together for complex logic. Here is pseudocode of multiple chained if
/ else if
statements:",
- "if (condition1) {", + "
statement1
} else if (condition2) {
statement2
} else if (condition3) {
statement3
. . .
} else {
statementN
}
if (condition1) {", "
statement1
} else if (condition2) {
statement2
} else if (condition3) {
statement3
. . .
} else {
statementN
}
if
/else if
statements to fulfill the following conditions:",
"num < 5
- return \"Tiny\"num < 10
- return \"Small\"num < 15
- return \"Medium\"num < 20
- return \"Large\"num >= 20
- return \"Huge\""
@@ -5025,7 +5025,7 @@
"title": "Encadenamiento de sentencias else if",
"description": [
"Las sentencias if/else
(si/de lo contrario) pueden ser encadenadas juntas por una lógica compleja. Aquí está el pseudocódigo de múltiples sentencias if
/ else if
encadenadas:",
- "if (condicion1) {", + "
sentencias1
} else if (condicion2) {
sentencias2
} else if (condicion3) {
sentencias3
. . .
} else {
sentenciasN
}
if (condicion1) {", "
sentencias1
} else if (condicion2) {
sentencias2
} else if (condicion3) {
sentencias3
. . .
} else {
sentenciasN
}
if
/else if
encadenadas para cumplir las siguientes condiciones:",
"num < 5
- retorna \"Tiny\"num < 10
- retorna \"Small\"num < 15
- retorna \"Medium\"num < 20
- retorna \"Large\"num >= 20
- retorna \"Huge\""
@@ -5154,7 +5154,7 @@
"description": [
"If you have many options to choose from, use a switch
statement. A switch
statement tests a value and can have many case
statements which define various possible values. Statements are executed from the first matched case
value until a break
is encountered.",
"Here is a pseudocode example:",
- "switch(num) {", + "
case value1:
statement1;
break;
case value2:
statement2;
break;
...
case valueN:
statementN;
break;
}
switch(num) {", "
case value1:
statement1;
break;
case value2:
statement2;
break;
...
case valueN:
statementN;
break;
}
case
values are tested with strict equality (===
). The break
tells JavaScript to stop executing statements. If the break
is omitted, the next statement will be executed.",
"val
and sets answer
for the following conditions:1
- \"alpha\"2
- \"beta\"3
- \"gamma\"4
- \"delta\""
@@ -5199,7 +5199,7 @@
"description": [
"Si tienes varias opciones para elegir, usa una sentencia switch
. Una sentencia switch
prueba un valor y puede tener varias sentencias case
las cuales definen varios posibles valores. Las sentencias son ejecutadas desde el primer valor case
igualado hasta que se encuentr un break
.",
"Aquí hay un pseudocódigo de ejemplo:",
- "switch(num) {", + "
case valor1:
sentencia1;
break;
case valor2:
sentencia2;
break;
...
case valorN:
sentenciaN;
break;
}
switch(num) {", "Los valores
case valor1:
sentencia1;
break;
case valor2:
sentencia2;
break;
...
case valorN:
sentenciaN;
break;
}
case
son probados con estricta igualdad (===
). El break
le dice a JavaScript que pare la ejecución del bloque de sentencias en el que está. Si se omite break
, se ejecutará la siguiente sentencia.",
"switch
que pruebe val
y establezca answer
para las siguientes condiciones:1
- \"alpha\"2
- \"beta\"3
- \"gamma\"4
- \"delta\""
@@ -5237,7 +5237,7 @@
"description": [
"In a switch
statement you may not be able to specify all possible values as case
statements. Instead, you can add the default
statement which will be executed if no matching case
statements are found. Think of it like the final else
statement in an if/else
chain.",
"A default
statement should be the last case.",
- "switch (num) {", + "
case value1:
statement1;
break;
case value2:
statement2;
break;
...
default:
defaultStatement;
break;
}
switch (num) {", "
case value1:
statement1;
break;
case value2:
statement2;
break;
...
default:
defaultStatement;
break;
}
answer
for the following conditions:\"a\"
- \"apple\"\"b\"
- \"bird\"\"c\"
- \"cat\"default
- \"stuff\""
],
@@ -5286,7 +5286,7 @@
"description": [
"En una sentencia switch
puede que no seas capaz de especificar todos los posibles valores en las sentencias case
. En su lugar, puedes agregar la sentencia default
la cual será ejecutada si no es encontrada ninguna coincidencia con alguna sentencia case
. Piensa en esto como la última sentencia else
en una cadena if/else
.",
"Una sentencia default
debería ser el último caso.",
- "switch(num) {", + "
case valor1:
sentencia1;
break;
case valor2:
sentencia2;
break;
...
default:
sentenciaDefault;
}
switch(num) {", "
case valor1:
sentencia1;
break;
case valor2:
sentencia2;
break;
...
default:
sentenciaDefault;
}
answer
para las siguientes condiciones:\"a\"
- \"apple\"\"b\"
- \"bird\"\"c\"
- \"cat\"default
- \"stuff\""
]
@@ -5323,7 +5323,7 @@
"title": "Multiple Identical Options in Switch Statements",
"description": [
"If the break
statement is omitted from a switch
statement's case
, the following case
statement(s) are executed until a break
is encountered. If you have multiple inputs with the same output, you can represent them in a switch
statement like this:",
- "switch(val) {", + "
case 1:
case 2:
case 3:
result = \"1, 2, or 3\";
break;
case 4:
result = \"4 alone\";
}
switch(val) {", "Cases for 1, 2, and 3 will all produce the same result.", "
case 1:
case 2:
case 3:
result = \"1, 2, or 3\";
break;
case 4:
result = \"4 alone\";
}
answer
for the following ranges:1-3
- \"Low\"4-6
- \"Mid\"7-9
- \"High\"",
@@ -5385,7 +5385,7 @@
"title": "Múltiples opciones idénticas en una sentencias switch",
"description": [
"Si la sentencia break
es omitida de una sentencia case
de un switch
, las siguientes sentencias case
son ejecutadas hasta que sea encontrado un break
. Si tienes multiples entradas con la misma salida, puede representarlas en una sentencia switch
así:",
- "switch(val) {", + "
case 1:
case 2:
case 3:
result = \"1, 2, or 3\";
break;
case 4:
result = \"4 alone\";
}
switch(val) {", "Los casos 1, 2, y 3 producirán el mismo resultado.", "
case 1:
case 2:
case 3:
result = \"1, 2, or 3\";
break;
case 4:
result = \"4 alone\";
}
switch
para establecer answer
para los siguientes rangos:1-3
- \"Low\"4-6
- \"Mid\"7-9
- \"High\"",
@@ -5423,9 +5423,9 @@
"title": "Replacing If Else Chains with Switch",
"description": [
"If you have many options to choose from, a switch
statement can be easier to write than many chained if
/else if
statements. The following:",
- "if (val === 1) {", + "
answer = \"a\";
} else if (val === 2) {
answer = \"b\";
} else {
answer = \"c\";
}
if (val === 1) {", "can be replaced with:", - "
answer = \"a\";
} else if (val === 2) {
answer = \"b\";
} else {
answer = \"c\";
}
switch(val) {", + "
case 1:
answer = \"a\";
break;
case 2:
answer = \"b\";
break;
default:
answer = \"c\";
}
switch(val) {", "
case 1:
answer = \"a\";
break;
case 2:
answer = \"b\";
break;
default:
answer = \"c\";
}
if
/else if
statements into a switch
statement."
],
@@ -5481,9 +5481,9 @@
"title": "Reemplazar cadenas if else con switch",
"description": [
"Si tienes varias opciones para elegir, una sentencia switch
puede ser más fácil de escribir que varias sentencias if
/if else
anidadas. Lo siguiente:",
- "if (val === 1) {", + "
respuesta = \"a\";
} else if (val === 2) {
respuesta = \"b\";
} else {
respuesta = \"c\";
}
if (val === 1) {", "puede ser reemplazado con:", - "
respuesta = \"a\";
} else if (val === 2) {
respuesta = \"b\";
} else {
respuesta = \"c\";
}
switch(val) {", + "
case 1:
respuesta = \"a\";
break;
case 2:
respuesta = \"b\";
break;
default:
respuesta = \"c\";
}
switch(val) {", "
case 1:
respuesta = \"a\";
break;
case 2:
respuesta = \"b\";
break;
default:
respuesta = \"c\";
}
if
/if else
anidadas dentro de una sentencia switch
."
]
@@ -5530,9 +5530,9 @@
"description": [
"You may recall from Comparison with the Equality Operator that all comparison operators return a boolean true
or false
value.",
"Sometimes people use an if/else statement to do a comparison, like this:",
- "function isEqual(a,b) {", + "
if (a === b) {
return true;
} else {
return false;
}
}
function isEqual(a,b) {", "But there's a better way to do this. Since
if (a === b) {
return true;
} else {
return false;
}
}
===
returns true
or false
, we can return the result of the comparison:",
- "function isEqual(a,b) {", + "
return a === b;
}
function isEqual(a,b) {", "
return a === b;
}
isLess
to remove the if/else
statements."
],
@@ -5561,9 +5561,9 @@
"description": [
"Tal vez recuerdes de La comparación con el operador de igualdad que todos los operadores de comparación retornan un valor booleano true
(verdadero) o false
(falso).",
"Un anti-patrón común es usar una sentencia if/else
para hacer una comparación y entonces retornar true
o false
:",
- "function sonIguales(a,b) {", + "
if (a === b) {
return true;
} else {
return false;
}
}
function sonIguales(a,b) {", "Ya que
if (a === b) {
return true;
} else {
return false;
}
}
===
returna true
(verdadero) o false
(falso), podemos simplemente retornar el resultado de la comparación:",
- "function sonIguales(a,b) {", + "
return a === b;
}
function sonIguales(a,b) {", "
return a === b;
}
isLess
para remover las sentencias if/else
."
]
@@ -5598,7 +5598,7 @@
"description": [
"When a return
statement is reached, the execution of the current function stops and control returns to the calling location.",
"Example",
- "function myFun() {", + "
console.log(\"Hello\");
return \"World\";
console.log(\"byebye\")
}
myFun();
function myFun() {", "The above outputs \"Hello\" to the console, returns \"World\", but
console.log(\"Hello\");
return \"World\";
console.log(\"byebye\")
}
myFun();
\"byebye\"
is never output, because the function exits at the return
statement.",
"abTest
so that if a
or b
are less than 0
the function will immediately exit with a value of undefined
.",
@@ -5641,7 +5641,7 @@
"description": [
"Cuando se alcanza una sentencia return
, la ejecución de la presente función se detiene y el control la retorna a la ubicación de la llamada.",
"Ejemplo",
- "function miFuncion() {", + "
console.log(\"Hola\");
return \"Mundo\";
console.log(\"chaochao\")
}
miFuncion();
function miFuncion() {", "Esta presenta en consola \"Hola\", retorna \"Mundo\", pero
console.log(\"Hola\");
return \"Mundo\";
console.log(\"chaochao\")
}
miFuncion();
\"chaochao\"
nunca se presenta, porque la función sale con la sentencia return
.",
"abTest
de manera que si a
o b
son menores que 0
la función saldrá inmediatamente con un valor undefined
.",
@@ -5765,9 +5765,9 @@
"Objects are similar to arrays
, except that instead of using indexes to access and modify their data, you access the data in objects through what are called properties
.",
"Objects are useful for storing data in a structured way, and can represent real world objects, like a cat.",
"Here's a sample cat object:",
- "var cat = {", + "
\"name\": \"Whiskers\",
\"legs\": 4,
\"tails\": 1,
\"enemies\": [\"Water\", \"Dogs\"]
};
var cat = {", "In this example, all the properties are stored as strings, such as -
\"name\": \"Whiskers\",
\"legs\": 4,
\"tails\": 1,
\"enemies\": [\"Water\", \"Dogs\"]
};
\"name\"
, \"legs\"
, and \"tails\"
. However, you can also use numbers as properties. You can even omit the quotes for single-word string properties, as follows:",
- "var anotherObject = {", + "
make: \"Ford\",
5: \"five\",
\"model\": \"focus\"
};
var anotherObject = {", "However, if your object has any non-string properties, JavaScript will automatically typecast them as strings.", "
make: \"Ford\",
5: \"five\",
\"model\": \"focus\"
};
myDog
which contains the properties \"name\"
(a string), \"legs\"
, \"tails\"
and \"friends\"
.",
@@ -5855,7 +5855,7 @@
"There are two ways to access the properties of an object: dot notation (.
) and bracket notation ([]
), similar to an array.",
"Dot notation is what you use when you know the name of the property you're trying to access ahead of time.",
"Here is a sample of using dot notation (.
) to read an object's property:",
- "var myObj = {", + "
prop1: \"val1\",
prop2: \"val2\"
};
var prop1val = myObj.prop1; // val1
var prop2val = myObj.prop2; // val2
var myObj = {", "
prop1: \"val1\",
prop2: \"val2\"
};
var prop1val = myObj.prop1; // val1
var prop2val = myObj.prop2; // val2
testObj
using dot notation. Set the variable hatValue
equal to the object's property hat
and set the variable shirtValue
equal to the object's property shirt
."
],
@@ -5893,7 +5893,7 @@
"Hay dos maneras de acceder a las propiedades de un objeto: con el operador punto (.
) y con la notación corchete ([]
), similar al caso de un vector.",
"El operador punto es el que usas cuando de antemano sabes el nombre de la propiedad que estás intentando acceder.",
"Aquí está un ejemplo del uso del operador punto (.
) para leer una propiedad de un objeto:",
- "var miObj = {", + "
prop1: \"val1\",
prop2: \"val2\"
};
var prop1val = miObj.prop1; // val1
var prop2val = miObj.prop2; // val2
var miObj = {", "
prop1: \"val1\",
prop2: \"val2\"
};
var prop1val = miObj.prop1; // val1
var prop2val = miObj.prop2; // val2
testObj
usando notación punto. Asigna la variable hatValue
igual a la propiedad objeto hat
y asigna la variable shirtValue
igual a la propiedad objeto shirt
."
]
@@ -5931,7 +5931,7 @@
"The second way to access the properties of an object is bracket notation ([]
). If the property of the object you are trying to access has a space in its name, you will need to use bracket notation.",
"However, you can still use bracket notation on object properties without spaces.",
"Here is a sample of using bracket notation to read an object's property:",
- "var myObj = {", + "
\"Space Name\": \"Kirk\",
\"More Space\": \"Spock\",
\"NoSpace\": \"USS Enterprise\"
};
myObj[\"Space Name\"]; // Kirk
myObj['More Space']; // Spock
myObj[\"NoSpace\"]; // USS Enterprise
var myObj = {", "Note that property names with spaces in them must be in quotes (single or double).", "
\"Space Name\": \"Kirk\",
\"More Space\": \"Spock\",
\"NoSpace\": \"USS Enterprise\"
};
myObj[\"Space Name\"]; // Kirk
myObj['More Space']; // Spock
myObj[\"NoSpace\"]; // USS Enterprise
\"an entree\"
and \"the drink\"
of testObj
using bracket notation and assign them to entreeValue
and drinkValue
respectively."
@@ -5969,7 +5969,7 @@
"description": [
"La segunda manera de acceder a las propiedades de un objeto es con la notación corchete ([]
). Si el nombre de la propiedad del objeto que estás intentando acceder tiene un espacio, necesitarás usar la notación corchete.",
"Aquí está un ejemplo del uso de la notación corchete para leer una propiedad de un objeto:",
- "var miObj = {", + "
\"Nombre con espacio\": \"Kirk\",
\"Mas espacio\": \"Spock\"
};
miObj[\"Nombre con espacio\"]; // Kirk
miObj['Mas espacio']; // Spock
var miObj = {", "Nota que los nombres de propiedades con espacios tienen que estar entre comillas (apóstrofes o comillas).", "
\"Nombre con espacio\": \"Kirk\",
\"Mas espacio\": \"Spock\"
};
miObj[\"Nombre con espacio\"]; // Kirk
miObj['Mas espacio']; // Spock
\"an entree\"
y \"the drink\"
de testObj
usando la notación corchete."
@@ -6008,9 +6008,9 @@
"description": [
"Another use of bracket notation on objects is to access a property which is stored as the value of a variable. This can be very useful for iterating through an object's properties or when accessing a lookup table.",
"Here is an example of using a variable to access a property:",
- "var dogs = {", + "
Fido: \"Mutt\",\n Hunter: \"Doberman\",\n Snoopie: \"Beagle\"
};
var myDog = \"Hunter\";
var myBreed = dogs[myDog];
console.log(myBreed); // \"Doberman\"
var dogs = {", "Another way you can use this concept is when the property's name is collected dynamically during the program execution, as follows:", - "
Fido: \"Mutt\",\n Hunter: \"Doberman\",\n Snoopie: \"Beagle\"
};
var myDog = \"Hunter\";
var myBreed = dogs[myDog];
console.log(myBreed); // \"Doberman\"
var someObj = {", + "
propName: \"John\"
};
function propPrefix(str) {
var s = \"prop\";
return s + str;
}
var someProp = propPrefix(\"Name\"); // someProp now holds the value 'propName'
console.log(someObj[someProp]); // \"John\"
var someObj = {", "Note that we do not use quotes around the variable name when using it to access the property because we are using the value of the variable, not the name.", "
propName: \"John\"
};
function propPrefix(str) {
var s = \"prop\";
return s + str;
}
var someProp = propPrefix(\"Name\"); // someProp now holds the value 'propName'
console.log(someObj[someProp]); // \"John\"
playerNumber
variable to look up player 16
in testObj
using bracket notation. Then assign that name to the player
variable."
@@ -6052,9 +6052,9 @@
"description": [
"Otro uso de la notación corchete sobre objetos es usar una variable para acceder a una propiedad. Esto puede ser muy útil en iteraciones sobre la lista de propiedades de un objetos o para hacer operaciones de búsqueda.",
"Aquí está un ejemplo del uso de una variable para acceder a una propiedad:",
- "var algunaProp = \"propNombre\";", + "
var miObj = {
propNombre: \"Algún valor\"
}
miObj[algunaProp]; // \"Algún valor\"
var algunaProp = \"propNombre\";", "Aquí hay uno más:", - "
var miObj = {
propNombre: \"Algún valor\"
}
miObj[algunaProp]; // \"Algún valor\"
var miPerro = \"Cazador\";", + "
var perros = {
Fido: \"Mutt\",\n Cazador: \"Doberman\",\n Snoopie: \"Beagle\"
}
var raza = perros[miPerro]; // \"Cazador\"
console.log(raza)// \"Doberman\"
var miPerro = \"Cazador\";", "Nota que no usamos comillas alrededor del nombre de la variable (
var perros = {
Fido: \"Mutt\",\n Cazador: \"Doberman\",\n Snoopie: \"Beagle\"
}
var raza = perros[miPerro]; // \"Cazador\"
console.log(raza)// \"Doberman\"
miPerro
) cuando la usamos para acceder a la propiedad (perros[miPerro]
porque estamos usando el valor de la variable y no su nombre",
"playerNumber
para buscar y asignar a player
el jugador 16
de testObj
, usa la notación corchete."
@@ -6093,7 +6093,7 @@
"description": [
"After you've created a JavaScript object, you can update its properties at any time just like you would update any other variable. You can use either dot or bracket notation to update.",
"For example, let's look at ourDog
:",
- "var ourDog = {", + "
\"name\": \"Camper\",
\"legs\": 4,
\"tails\": 1,
\"friends\": [\"everything!\"]
};
var ourDog = {", "Since he's a particularly happy dog, let's change his name to \"Happy Camper\". Here's how we update his object's name property:", "
\"name\": \"Camper\",
\"legs\": 4,
\"tails\": 1,
\"friends\": [\"everything!\"]
};
ourDog.name = \"Happy Camper\";
or",
"ourDog[\"name\"] = \"Happy Camper\";
",
@@ -6321,7 +6321,7 @@
"description": [
"Objects can be thought of as a key/value storage, like a dictionary. If you have tabular data, you can use an object to \"lookup\" values rather than a switch
statement or an if/else
chain. This is most useful when you know that your input data is limited to a certain range.",
"Here is an example of a simple reverse alphabet lookup:",
- "var alpha = {", + "
1:\"Z\",
2:\"Y\",
3:\"X\",
4:\"W\",
...
24:\"C\",
25:\"B\",
26:\"A\"
};
alpha[2]; // \"Y\"
alpha[24]; // \"C\"
var value = 2;
alpha[value]; // \"Y\"
var alpha = {", "
1:\"Z\",
2:\"Y\",
3:\"X\",
4:\"W\",
...
24:\"C\",
25:\"B\",
26:\"A\"
};
alpha[2]; // \"Y\"
alpha[24]; // \"C\"
var value = 2;
alpha[value]; // \"Y\"
lookup
. Use it to look up val
and assign the associated string to the result
variable."
],
@@ -6374,7 +6374,7 @@
"description": [
"Los objetos pueden ser considerados como un almacenamiento llave/valor, como un diccionario. Si tienes datos tabulados, puedes almacenarlos en un objeto para después \"buscar\" valores, en lugar de emplear una sentencia switch
o una secuencia de if/else
. Esto es más útil cuando sabes que tus datos de entrada son limitados a un cierto rango.",
"Aquí está un ejemplo de una simple búsqueda inversa de alfabeto:",
- "var alfa = {", + "
1:\"Z\",
2:\"Y\",
3:\"X\",
4:\"W\",
...
24:\"C\",
25:\"B\",
26:\"A\"
};
alfa[2]; // \"Y\"
alfa[24]; // \"C\"
var valor = 2;
alfa[valor]; // \"Y\"
var alfa = {", "
1:\"Z\",
2:\"Y\",
3:\"X\",
4:\"W\",
...
24:\"C\",
25:\"B\",
26:\"A\"
};
alfa[2]; // \"Y\"
alfa[24]; // \"C\"
var valor = 2;
alfa[valor]; // \"Y\"
lookup
. Usala para buscar val
y asigna la cadena asociada a la variable result
."
]
@@ -6429,7 +6429,7 @@
"description": [
"Sometimes it is useful to check if the property of a given object exists or not. We can use the .hasOwnProperty(propname)
method of objects to determine if that object has the given property name. .hasOwnProperty()
returns true
or false
if the property is found or not.",
"Example",
- "var myObj = {", + "
top: \"hat\",
bottom: \"pants\"
};
myObj.hasOwnProperty(\"top\"); // true
myObj.hasOwnProperty(\"middle\"); // false
var myObj = {", "
top: \"hat\",
bottom: \"pants\"
};
myObj.hasOwnProperty(\"top\"); // true
myObj.hasOwnProperty(\"middle\"); // false
checkObj
to test myObj
for checkProp
. If the property is found, return that property's value. If not, return \"Not Found\"
."
],
@@ -6458,7 +6458,7 @@
"description": [
"A veces es útil revisar si cierta propiedad existe o no en un objeto dado. Podemos usar el método de objetos .hasOwnProperty(nomprop)
para determinar si un objeto tiene la propiedad nomprop
. .hasOwnProperty()
retorna true
o false
si la propiedad es encontrada o no.",
"Ejemplo",
- "var miObj = {", + "
arriba: \"sombrero\",
abajo: \"pantalones\"
};
miObj.hasOwnProperty(\"arriba\"); // true
miObj.hasOwnProperty(\"medio\"); // false
var miObj = {", "
arriba: \"sombrero\",
abajo: \"pantalones\"
};
miObj.hasOwnProperty(\"arriba\"); // true
miObj.hasOwnProperty(\"medio\"); // false
checkObj
que prueba si myObj
tiene la propiedad checkProp
. Si la propiedad es encontrada, retorna el valor de esa propiedad. Si no, retorna \"Not Found\"
."
]
@@ -6497,11 +6497,11 @@
"description": [
"Sometimes you may want to store data in a flexible Data Structure. A JavaScript object is one way to handle flexible data. They allow for arbitrary combinations of strings, numbers, booleans, arrays, functions, and objects.",
"Here's an example of a complex data structure:",
- "var ourMusic = [", + "
{
\"artist\": \"Daft Punk\",
\"title\": \"Homework\",
\"release_year\": 1997,
\"formats\": [
\"CD\",
\"Cassette\",
\"LP\"
],
\"gold\": true
}
];
var ourMusic = [", "This is an array which contains one object inside. The object has various pieces of metadata about an album. It also has a nested
{
\"artist\": \"Daft Punk\",
\"title\": \"Homework\",
\"release_year\": 1997,
\"formats\": [
\"CD\",
\"Cassette\",
\"LP\"
],
\"gold\": true
}
];
\"formats\"
array. If you want to add more album records, you can do this by adding records to the top level array.",
"Objects hold data in a property, which has a key-value format. In the example above, \"artist\": \"Daft Punk\"
is a property that has a key of \"artist\"
and a value of \"Daft Punk\"
.",
"JavaScript Object Notation or JSON
is a related data interchange format used to store data.",
- "{", + "
\"artist\": \"Daft Punk\",
\"title\": \"Homework\",
\"release_year\": 1997,
\"formats\": [
\"CD\",
\"Cassette\",
\"LP\"
],
\"gold\": true
}
{", "Note
\"artist\": \"Daft Punk\",
\"title\": \"Homework\",
\"release_year\": 1997,
\"formats\": [
\"CD\",
\"Cassette\",
\"LP\"
],
\"gold\": true
}
myMusic
array. Add artist
and title
strings, release_year
number, and a formats
array of strings."
@@ -6555,7 +6555,7 @@
"description": [
"Los objetos JavaScript son flexibles porque permiten Estructuras de Datos con combinaciones arbitrarias de cadenas, números, booleanos, vectores, funciones, y objetos.",
"Aquí está un ejemplo de un objeto complicado:",
- "var nuestraMusica = [", + "
{
\"artista\": \"Daft Punk\",
\"titulo\": \"Homework\",
\"año_publicacion\": 1997,
\"formatos\": [
\"CD\",
\"Cassette\",
\"LP\" ],
\"oro\": true
}
];
var nuestraMusica = [", "Este es un vector de objetos con diversos metadatos acerca de un álbum musical. Además tiene anidado un vector
{
\"artista\": \"Daft Punk\",
\"titulo\": \"Homework\",
\"año_publicacion\": 1997,
\"formatos\": [
\"CD\",
\"Cassette\",
\"LP\" ],
\"oro\": true
}
];
formatos
. En el vector de nivel superior, pueden añadirse otros registros del álbum.",
"Notavar ourStorage = {", + "
\"desk\": {
\"drawer\": \"stapler\"
},
\"cabinet\": {
\"top drawer\": {
\"folder1\": \"a file\",
\"folder2\": \"secrets\"
},
\"bottom drawer\": \"soda\"
}
};
ourStorage.cabinet[\"top drawer\"].folder2; // \"secrets\"
ourStorage.desk.drawer; // \"stapler\"
var ourStorage = {", "
\"desk\": {
\"drawer\": \"stapler\"
},
\"cabinet\": {
\"top drawer\": {
\"folder1\": \"a file\",
\"folder2\": \"secrets\"
},
\"bottom drawer\": \"soda\"
}
};
ourStorage.cabinet[\"top drawer\"].folder2; // \"secrets\"
ourStorage.desk.drawer; // \"stapler\"
myStorage
object and assign the contents of the glove box
property to the gloveBoxContents
variable. Use bracket notation for properties with a space in their name."
],
@@ -6623,7 +6623,7 @@
"description": [
"Las sub-propiedades de los objetos pueden ser accesadas mediante encadenamiento de la notación punto o corchete.",
"Aquí está un objeto anidado:",
- "var nuestroAlmacen = {", + "
\"escritorio\": {
\"cajon\": \"grapadora\"
},
\"armario\": {
\"cajón superior\": {
\"legajador1\": \"un archivo\",
\"legajador2\": \"secretos\"
},
\"cajón inferior\": \"gaseosa\"
}
}
nuestroAlmacen.armario[\"cajón superior\"].legajador2; // \"secretos\"
nuestroAlmacen.escritorio.cajon; // \"grapadora\"
var nuestroAlmacen = {", "
\"escritorio\": {
\"cajon\": \"grapadora\"
},
\"armario\": {
\"cajón superior\": {
\"legajador1\": \"un archivo\",
\"legajador2\": \"secretos\"
},
\"cajón inferior\": \"gaseosa\"
}
}
nuestroAlmacen.armario[\"cajón superior\"].legajador2; // \"secretos\"
nuestroAlmacen.escritorio.cajon; // \"grapadora\"
myStorage
para recuperar el contenido de glove box
. Usa notación corchete para las propiedades con un espacio en su nombre."
]
@@ -6670,7 +6670,7 @@
"description": [
"As we have seen in earlier examples, objects can contain both nested objects and nested arrays. Similar to accessing nested objects, Array bracket notation can be chained to access nested arrays.",
"Here is an example of how to access a nested array:",
- "var ourPets = [", + "
{
animalType: \"cat\",
names: [
\"Meowzer\",
\"Fluffy\",
\"Kit-Cat\"
]
},
{
animalType: \"dog\",
names: [
\"Spot\",
\"Bowser\",
\"Frankie\"
]
}
];
ourPets[0].names[1]; // \"Fluffy\"
ourPets[1].names[0]; // \"Spot\"
var ourPets = [", "
{
animalType: \"cat\",
names: [
\"Meowzer\",
\"Fluffy\",
\"Kit-Cat\"
]
},
{
animalType: \"dog\",
names: [
\"Spot\",
\"Bowser\",
\"Frankie\"
]
}
];
ourPets[0].names[1]; // \"Fluffy\"
ourPets[1].names[0]; // \"Spot\"
myPlants
using object dot and array bracket notation."
],
@@ -6695,7 +6695,7 @@
"description": [
"Como hemos visto en ejemplos anteriores, los objetos pueden contener objetos anidados y vectores anidados. De forma similar a acceder a objetos anidados, la notación corchete en vectores puede ser encadenada para acceder a vectores anidados.",
"Aquí está un ejemplo de como acceder a un vector anidado:",
- "var nuestrasMascotas = {", + "
\"gatos\": [
\"Maullador\",
\"Blandito\",
\"Kit-Cat\"
],
\"perros\": [
\"Mancha\",
\"Bowser\",
\"Frankie\"
]
};
nuestrasMascotas.cats[1]; // \"Blandito\"
nuestrasMascotas.dogs[0]; // \"Mancha\"
var nuestrasMascotas = {", "
\"gatos\": [
\"Maullador\",
\"Blandito\",
\"Kit-Cat\"
],
\"perros\": [
\"Mancha\",
\"Bowser\",
\"Frankie\"
]
};
nuestrasMascotas.cats[1]; // \"Blandito\"
nuestrasMascotas.dogs[0]; // \"Mancha\"
myPlants
usando notación punto para objetos y notación corchete para vectores."
]
@@ -6870,7 +6870,7 @@
"description": [
"You can run the same code multiple times by using a loop.",
"The first type of loop we will learn is called a \"while
\" loop because it runs \"while\" a specified condition is true and stops once that condition is no longer true.",
- "var ourArray = [];", + "
var i = 0;
while(i < 5) {
ourArray.push(i);
i++;
}
var ourArray = [];", "Let's try getting a while loop to work by pushing values to an array.", "
var i = 0;
while(i < 5) {
ourArray.push(i);
i++;
}
myArray
using a while
loop."
@@ -6939,7 +6939,7 @@
"The condition
statement is evaluated at the beginning of every loop iteration and will continue as long as it evaluates to true
. When condition
is false
at the start of the iteration, the loop will stop executing. This means if condition
starts as false
, your loop will never execute.",
"The final-expression
is executed at the end of each loop iteration, prior to the next condition
check and is usually used to increment or decrement your loop counter.",
"In the following example we initialize with i = 0
and iterate while our condition i < 5
is true. We'll increment i
by 1
in each loop iteration with i++
as our final-expression
.",
- "var ourArray = [];", + "
for (var i = 0; i < 5; i++) {
ourArray.push(i);
}
var ourArray = [];", "
for (var i = 0; i < 5; i++) {
ourArray.push(i);
}
ourArray
will now contain [0,1,2,3,4]
.",
"for
loop to work to push the values 1 through 5 onto myArray
."
@@ -7013,7 +7013,7 @@
"description": [
"For loops don't have to iterate one at a time. By changing our final-expression
, we can count by even numbers.",
"We'll start at i = 0
and loop while i < 10
. We'll increment i
by 2 each loop with i += 2
.",
- "var ourArray = [];", + "
for (var i = 0; i < 10; i += 2) {
ourArray.push(i);
}
var ourArray = [];", "
for (var i = 0; i < 10; i += 2) {
ourArray.push(i);
}
ourArray
will now contain [0,2,4,6,8]
.",
"Let's change our initialization
so we can count by odd numbers.",
"initialization
, condition
, and final-expression
.",
"We'll start at i = 10
and loop while i > 0
. We'll decrement i
by 2 each loop with i -= 2
.",
- "var ourArray = [];", + "
for (var i=10; i > 0; i-=2) {
ourArray.push(i);
}
var ourArray = [];", "
for (var i=10; i > 0; i-=2) {
ourArray.push(i);
}
ourArray
will now contain [10,8,6,4,2]
.",
"Let's change our initialization
and final-expression
so we can count backward by twos by odd numbers.",
"for
loop. This code will output each element of the array arr
to the console:",
- "var arr = [10,9,8,7,6];", + "
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
var arr = [10,9,8,7,6];", "Remember that Arrays have zero-based numbering, which means the last index of the array is length - 1. Our condition for this loop is
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
i < arr.length
, which stops when i
is at length - 1.",
"total
to 0
. Use a for
loop to add the value of each element of the myArr
array to total
."
@@ -7191,7 +7191,7 @@
"title": "Iterar a través de un vector con un ciclo for",
"description": [
"Una tarea común en JavaScript es iterar a traves del contenido de un vector. Una manera de hacerlo es con un ciclo for
. Este código imprimirá cada elemento del vector arr
en la consola:",
- "var arr = [10,9,8,7,6];", + "
for (var i=0; i < arr.length; i++) {
console.log(arr[i]);
}
var arr = [10,9,8,7,6];", "Recuerda que los vectores tienen numeración que comienza en cero, la cual significa que el último índice del vector es su longitud - 1. Nuestra condición para este ciclo es
for (var i=0; i < arr.length; i++) {
console.log(arr[i]);
}
i < arr.length
, que lo detendrá cuando i
sea la longitud - 1.",
"total
en 0
. Usa un ciclo for
para añadir el valor de cada elemento del vector myArr
a total
."
@@ -7231,7 +7231,7 @@
"title": "Nesting For Loops",
"description": [
"If you have a multi-dimensional array, you can use the same logic as the prior waypoint to loop through both the array and any sub-arrays. Here is an example:",
- "var arr = [", + "
[1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) {
console.log(arr[i][j]);
}
}
var arr = [", "This outputs each sub-element in
[1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) {
console.log(arr[i][j]);
}
}
arr
one at a time. Note that for the inner loop, we are checking the .length
of arr[i]
, since arr[i]
is itself an array.",
"multiplyAll
so that it multiplies the product
variable by each number in the sub-arrays of arr
"
@@ -7260,7 +7260,7 @@
"title": "Anidar ciclos for",
"description": [
"Si tienes una matriz multi-dimensional, puedes usar la misma lógica del punto anterior para iterar a través de un vector y cualquier sub-vector. Aquí está un ejemplo:",
- "var arr = [", + "
[1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) {
console.log(arr[i][j]);
}
}
var arr = [", "Esto imprime cada sub-elemento en
[1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) {
console.log(arr[i][j]);
}
}
arr
uno a la vez. Nota que en el ciclo interior, estamos comprobando la longitud .length
de arr[i]
, ya que arr[i]
es por si mismo un vector.",
"multiplyAll
de manera que esta multiplique la variable product
por cada número en los sub-vectores de arr
"
@@ -7296,13 +7296,13 @@
"description": [
"You can run the same code multiple times by using a loop.",
"The next type of loop you will learn is called a \"do...while
\" loop because it first will \"do
\" one pass of the code inside the loop no matter what, and then it runs \"while
\" a specified condition is true and stops once that condition is no longer true. Let's look at an example.",
- "var ourArray = [];", + "
var i = 0;
do {
ourArray.push(i);
i++;
} while (i < 5);
var ourArray = [];", "This behaves just as you would expect with any other type of loop, and the resulting array will look like
var i = 0;
do {
ourArray.push(i);
i++;
} while (i < 5);
[0, 1, 2, 3, 4]
. However, what makes the do...while
different from other loops is how it behaves when the condition fails on the first check. Let's see this in action.",
"Here is a regular while loop that will run the code in the loop as long as i < 5
.",
- "var ourArray = [];", + "
var i = 5;
while (i < 5) {
ourArray.push(i);
i++;
}
var ourArray = [];", "Notice that we initialize the value of
var i = 5;
while (i < 5) {
ourArray.push(i);
i++;
}
i
to be 5. When we execute the next line, we notice that i
is not less than 5. So we do not execute the code inside the loop. The result is that ourArray
will end up with nothing added to it, so it will still look like this []
when all the code in the example above finishes running.",
"Now, take a look at a do...while
loop.",
- "var ourArray = [];", + "
var i = 5;
do {
ourArray.push(i);
i++;
} while (i < 5);
var ourArray = [];", "In this case, we initialize the value of
var i = 5;
do {
ourArray.push(i);
i++;
} while (i < 5);
i
as 5, just like we did with the while loop. When we get to the next line, there is no check for the value of i
, so we go to the code inside the curly braces and execute it. We will add one element to the array and increment i
before we get to the condition check. Then, when we get to checking if i < 5
see that i
is now 6, which fails the conditional check. So we exit the loop and are done. At the end of the above example, the value of ourArray
is [5]
.",
"Essentially, a do...while
loop ensures that the code inside the loop will run at least once.",
"Let's try getting a do...while
loop to work by pushing values to an array.",
@@ -7804,9 +7804,9 @@
"The syntax is:",
"condition ? statement-if-true : statement-if-false;
",
"The following function uses an if-else statement to check a condition:",
- "function findGreater(a, b) {", + "
if(a > b) {
return \"a is greater\";
}
else {
return \"b is greater\";
}
}
function findGreater(a, b) {", "This can be re-written using the
if(a > b) {
return \"a is greater\";
}
else {
return \"b is greater\";
}
}
conditional operator
:",
- "function findGreater(a, b) {", + "
return a > b ? \"a is greater\" : \"b is greater\";
}
function findGreater(a, b) {", "
return a > b ? \"a is greater\" : \"b is greater\";
}
conditional operator
in the checkEqual
function to check if two numbers are equal or not. The function should return either true or false."
],
@@ -7855,9 +7855,9 @@
"description": [
"In the previous challenge, you used a single conditional operator
. You can also chain them together to check for multiple conditions.",
"The following function uses if, else if, and else statements to check multiple conditions:",
- "function findGreaterOrEqual(a, b) {", + "
if(a === b) {
return \"a and b are equal\";
}
else if(a > b) {
return \"a is greater\";
}
else {
return \"b is greater\";
}
}
function findGreaterOrEqual(a, b) {", "The above function can be re-written using multiple
if(a === b) {
return \"a and b are equal\";
}
else if(a > b) {
return \"a is greater\";
}
else {
return \"b is greater\";
}
}
conditional operators
:",
- "function findGreaterOrEqual(a, b) {", + "
return (a === b) ? \"a and b are equal\" : (a > b) ? \"a is greater\" : \"b is greater\";
}
function findGreaterOrEqual(a, b) {", "
return (a === b) ? \"a and b are equal\" : (a > b) ? \"a is greater\" : \"b is greater\";
}
conditional operators
in the checkSign
function to check if a number is positive, negative or zero."
],
diff --git a/seed/challenges/02-javascript-algorithms-and-data-structures/es6.json b/seed/challenges/02-javascript-algorithms-and-data-structures/es6.json
index d8385c712e..40b8892763 100644
--- a/seed/challenges/02-javascript-algorithms-and-data-structures/es6.json
+++ b/seed/challenges/02-javascript-algorithms-and-data-structures/es6.json
@@ -69,13 +69,13 @@
"When you declare a variable with the var
keyword, it is declared globally, or locally if declared inside a function.",
"The let
keyword behaves similarly, but with some extra features. When you declare a variable with the let
keyword inside a block, statement, or expression, its scope is limited to that block, statement, or expression.",
"For example:",
- "var numArray = [];", + "
for (var i = 0; i < 3; i++) {
numArray.push(i);
}
console.log(numArray);
// returns [0, 1, 2]
console.log(i);
// returns 3
var numArray = [];", "With the
for (var i = 0; i < 3; i++) {
numArray.push(i);
}
console.log(numArray);
// returns [0, 1, 2]
console.log(i);
// returns 3
var
keyword, i
is declared globally. So when i++
is executed, it updates the global variable. This code is similar to the following:",
- "var numArray = [];", + "
var i;
for (i = 0; i < 3; i++) {
numArray.push(i);
}
console.log(numArray);
// returns [0, 1, 2]
console.log(i);
// returns 3
var numArray = [];", "This behavior will cause problems if you were to create a function and store it for later use inside a for loop that uses the
var i;
for (i = 0; i < 3; i++) {
numArray.push(i);
}
console.log(numArray);
// returns [0, 1, 2]
console.log(i);
// returns 3
i
variable. This is because the stored function will always refer to the value of the updated global i
variable.",
- "var printNumTwo;", + "
for (var i = 0; i < 3; i++) {
if(i === 2){
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
// returns 3
var printNumTwo;", "As you can see,
for (var i = 0; i < 3; i++) {
if(i === 2){
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
// returns 3
printNumTwo()
prints 3 and not 2. This is because the value assigned to i
was updated and the printNumTwo()
returns the global i
and not the value i
had when the function was created in the for loop. The let
keyword does not follow this behavior:",
- "'use strict';", + "
let printNumTwo;
for (let i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
// returns 2
console.log(i);
// returns \"i is not defined\"
'use strict';", "
let printNumTwo;
for (let i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
// returns 2
console.log(i);
// returns \"i is not defined\"
i
is not defined because it was not declared in the global scope. It is only declared within the for loop statement. printNumTwo()
returned the correct value because three different i
variables with unique values (0, 1, and 2) were created by the let
keyword within the loop statement.",
"i
declared in the if statement is a separate variable than i
declared in the first line of the function. Be certain not to use the var
keyword anywhere in your code.",
@@ -239,7 +239,7 @@
"description": [
"As seen in the previous challenge, const
declaration alone doesn't really protect your data from mutation. To ensure your data doesn't change, JavaScript provides a function Object.freeze
to prevent data mutation.",
"Once the object is frozen, you can no longer add, update, or delete properties from it. Any attempt at changing the object will be rejected without an error.",
- "", + "
let obj = {
name:\"FreeCodeCamp\"
review:\"Awesome\"
};
Object.freeze(obj);
obj.review = \"bad\"; //will be ignored. Mutation not allowed
obj.newProp = \"Test\"; // will be ignored. Mutation not allowed
console.log(obj);
// { name: \"FreeCodeCamp\", review:\"Awesome\"}
", "
let obj = {
name:\"FreeCodeCamp\"
review:\"Awesome\"
};
Object.freeze(obj);
obj.review = \"bad\"; //will be ignored. Mutation not allowed
obj.newProp = \"Test\"; // will be ignored. Mutation not allowed
console.log(obj);
// { name: \"FreeCodeCamp\", review:\"Awesome\"}
Object.freeze
to prevent mathematical constants from changing. You need to freeze the MATH_CONSTANTS
object so that no one is able alter the value of PI
, add, or delete properties ."
],
@@ -299,9 +299,9 @@
"description": [
"In JavaScript, we often don't need to name our functions, especially when passing a function as an argument to another function. Instead, we create inline functions. We don't need to name these functions because we do not reuse them anywhere else.",
"To achieve this, we often use the following syntax:",
- "const myFunc = function() {", + "
const myVar = \"value\";
return myVar;
}
const myFunc = function() {", "ES6 provides us with the syntactic sugar to not have to write anonymous functions this way. Instead, you can use arrow function syntax:", - "
const myVar = \"value\";
return myVar;
}
const myFunc = () => {", + "
const myVar = \"value\";
return myVar;
}
const myFunc = () => {", "When there is no function body, and only a return value, arrow function syntax allows you to omit the keyword
const myVar = \"value\";
return myVar;
}
return
as well as the brackets surrounding the code. This helps simplify smaller functions into one-line statements:",
"const myFunc= () => \"value\"", "This code will still return
value
by default.",
@@ -409,7 +409,7 @@
"It's time we see how powerful arrow functions are when processing data.",
"Arrow functions work really well with higher order functions, such as map()
, filter()
, and reduce()
, that take other functions as arguments for processing collections of data.",
"Read the following code:",
- "FBPosts.filter(function(post) {", + "
return post.thumbnail !== null && post.shares > 100 && post.likes > 500;
})
FBPosts.filter(function(post) {", "We have written this with
return post.thumbnail !== null && post.shares > 100 && post.likes > 500;
})
filter()
to at least make it somewhat readable. Now compare it to the following code which uses arrow function syntax instead:",
"FBPosts.filter((post) => post.thumbnail !== null && post.shares > 100 && post.likes > 500)", "This code is more succinct and accomplishes the same task with fewer lines of code.", @@ -478,7 +478,7 @@ "description": [ "In order to help us create more flexible functions, ES6 introduces default parameters for functions.", "Check out this code:", - "
function greeting(name = \"Anonymous\") {", + "
return \"Hello \" + name;
}
console.log(greeting(\"John\")); // Hello John
console.log(greeting()); // Hello Anonymous
function greeting(name = \"Anonymous\") {", "The default parameter kicks in when the argument is not specified (it is undefined). As you can see in the example above, the parameter
return \"Hello \" + name;
}
console.log(greeting(\"John\")); // Hello John
console.log(greeting()); // Hello Anonymous
name
will receive its default value \"Anonymous\"
when you do not provide a value for the parameter. You can add default values for as many parameters as you want.",
"increment
by adding default parameters so that it will add 1 to number
if value
is not specified."
@@ -526,7 +526,7 @@
"description": [
"In order to help us create more flexible functions, ES6 introduces the rest operator for function parameters. With the rest operator, you can create functions that take a variable number of arguments. These arguments are stored in an array that can be accessed later from inside the function.",
"Check out this code:",
- "function howMany(...args) {", + "
return \"You have passed \" + args.length + \" arguments.\";
}
console.log(howMany(0, 1, 2)); // You have passed 3 arguments
console.log(howMany(\"string\", null, [1, 2, 3], { })); // You have passed 4 arguments.
function howMany(...args) {", "The rest operator eliminates the need to check the
return \"You have passed \" + args.length + \" arguments.\";
}
console.log(howMany(0, 1, 2)); // You have passed 3 arguments
console.log(howMany(\"string\", null, [1, 2, 3], { })); // You have passed 4 arguments.
args
array and allows us to apply map()
, filter()
and reduce()
on the parameters array.",
"sum
so that it uses the rest operator and it works in the same way with any number of parameters."
@@ -691,7 +691,7 @@
"description": [
"We can similarly destructure nested objects into variables.",
"Consider the following code:",
- "const a = {", + "
start: { x: 5, y: 6},
end: { x: 6, y: -9 }
};
const { start : { x: startX, y: startY }} = a;
console.log(startX, startY); // 5, 6
const a = {", "In the example above, the variable
start: { x: 5, y: 6},
end: { x: 6, y: -9 }
};
const { start : { x: startX, y: startY }} = a;
console.log(startX, startY); // 5, 6
start
is assigned the value of a.start
, which is also an object.",
"max
of forecast.tomorrow
and assign it to maxOfTomorrow
."
@@ -845,9 +845,9 @@
"description": [
"In some cases, you can destructure the object in a function argument itself.",
"Consider the code below:",
- "const profileUpdate = (profileData) => {", + "
const { name, age, nationality, location } = profileData;
// do something with these variables
}
const profileUpdate = (profileData) => {", "This effectively destructures the object sent into the function. This can also be done in-place:", - "
const { name, age, nationality, location } = profileData;
// do something with these variables
}
const profileUpdate = ({ name, age, nationality, location }) => {", + "
/* do something with these fields */
}
const profileUpdate = ({ name, age, nationality, location }) => {", "This removes some extra lines and makes our code look neat.", "This has the added benefit of not having to manipulate an entire object in a function; only the fields that are needed are copied inside the function.", "
/* do something with these fields */
}
const person = {", + "
name: \"Zodiac Hasbro\",
age: 56
};
// string interpolation
const greeting = `Hello, my name is ${person.name}!
I am ${person.age} years old.`;
console.log(greeting); // prints
// Hello, my name is Zodiac Hasbro!
// I am 56 years old.
const person = {", "A lot of things happened there.", "Firstly, the
name: \"Zodiac Hasbro\",
age: 56
};
// string interpolation
const greeting = `Hello, my name is ${person.name}!
I am ${person.age} years old.`;
console.log(greeting); // prints
// Hello, my name is Zodiac Hasbro!
// I am 56 years old.
${variable}
syntax used above is a place holder. Basically, you won't have to use concatenation with the +
operator anymore. To add variables to strings, you just drop the variable in a template string and wrap it with ${
and }
.",
"Secondly, the example uses backticks (`
), not quotes ('
or \"
), to wrap the string. Notice that the string is multi-line.",
@@ -973,7 +973,7 @@
"description": [
"ES6 adds some nice support for easily defining object literals.",
"Consider the following code:",
- "const getMousePosition = (x, y) => ({", + "
x: x,
y: y
});
const getMousePosition = (x, y) => ({", "
x: x,
y: y
});
getMousePosition
is a simple function that returns an object containing two fields.",
"ES6 provides the syntactic sugar to eliminate the redundancy of having to write x: x
. You can simply write x
once, and it will be converted tox: x
(or something equivalent) under the hood.",
"Here is the same function from above rewritten to use this new syntax:",
@@ -1022,9 +1022,9 @@
"title": "Write Concise Declarative Functions with ES6",
"description": [
"When defining functions within objects in ES5, we have to use the keyword function
as follows:",
- "const person = {", + "
name: \"Taylor\",
sayHello: function() {
return `Hello! My name is ${this.name}.`;
}
};
const person = {", "With ES6, You can remove the
name: \"Taylor\",
sayHello: function() {
return `Hello! My name is ${this.name}.`;
}
};
function
keyword and colon altogether when defining functions in objects. Here's an example of this syntax:",
- "const person = {", + "
name: \"Taylor\",
sayHello() {
return `Hello! My name is ${this.name}.`;
}
};
const person = {", "
name: \"Taylor\",
sayHello() {
return `Hello! My name is ${this.name}.`;
}
};
setGear
inside the object bicycle
to use the shorthand syntax described above."
],
@@ -1071,9 +1071,9 @@
"ES6 provides a new syntax to help create objects, using the keyword class.",
"This is to be noted, that the class
syntax is just a syntax, and not a full-fledged class based implementation of object oriented paradigm, unlike in languages like Java, or Python, or Ruby etc.",
"In ES5, we usually define a constructor function, and use the new
keyword to instantiate an object.",
- "var SpaceShuttle = function(targetPlanet){", + "
this.targetPlanet = targetPlanet;
}
var zeus = new SpaceShuttle('Jupiter');
var SpaceShuttle = function(targetPlanet){", "The class syntax simply replaces the constructor function creation:", - "
this.targetPlanet = targetPlanet;
}
var zeus = new SpaceShuttle('Jupiter');
class SpaceShuttle {", + "
constructor(targetPlanet){
this.targetPlanet = targetPlanet;
}
}
const zeus = new SpaceShuttle('Jupiter');
class SpaceShuttle {", "Notice that the
constructor(targetPlanet){
this.targetPlanet = targetPlanet;
}
}
const zeus = new SpaceShuttle('Jupiter');
class
keyword declares a new function, and a constructor was added, which would be invoked when new
is called - to create a new object.",
"class
keyword and write a proper constructor to create the Vegetable
class.",
@@ -1126,7 +1126,7 @@
"These are classically called getters and setters.",
"Getter functions are meant to simply return (get) the value of an object's private variable to the user without the user directly accessing the private variable.",
"Setter functions are meant to modify (set) the value of an object's private variable based on the value passed into the setter function. This change could involve calculations, or even overwriting the previous value completely.",
- "class Book {", + "
constructor(author) {
this._author = author;
}
// getter
get writer(){
return this._author;
}
// setter
set writer(updatedAuthor){
this._author = updatedAuthor;
}
}
const lol = new Book('anonymous');
console.log(lol.writer);
lol.writer = 'wut';
console.log(lol.writer);
class Book {", "Notice the syntax we are using to invoke the getter and setter - as if they are not even functions.", "Getters and setters are important, because they hide internal implementation details.", "
constructor(author) {
this._author = author;
}
// getter
get writer(){
return this._author;
}
// setter
set writer(updatedAuthor){
this._author = updatedAuthor;
}
}
const lol = new Book('anonymous');
console.log(lol.writer);
lol.writer = 'wut';
console.log(lol.writer);
import
and how it can be leveraged to import small amounts of code from large files. In order for this to work, though, we must utilize one of the statements that goes with import
, known as export. When we want some code - a function, or a variable - to be usable in another file, we must export it in order to import it into another file. Like import
, export
is a non-browser feature.",
"The following is what we refer to as a named export. With this, we can import any code we export into another file with the import
syntax you learned in the last lesson. Here's an example:",
- "const capitalizeString = (string) => {", + "
return string.charAt(0).toUpperCase() + string.slice(1);
}
export { capitalizeString } //How to export functions.
export const foo = \"bar\"; //How to export variables.
const capitalizeString = (string) => {", "Alternatively, if you would like to compact all your
return string.charAt(0).toUpperCase() + string.slice(1);
}
export { capitalizeString } //How to export functions.
export const foo = \"bar\"; //How to export variables.
export
statements into one line, you can take this approach:",
- "const capitalizeString = (string) => {", + "
return string.charAt(0).toUpperCase() + string.slice(1);
}
const foo = \"bar\";
export { capitalizeString, foo }
const capitalizeString = (string) => {", "Either approach is perfectly acceptable.", "
return string.charAt(0).toUpperCase() + string.slice(1);
}
const foo = \"bar\";
export { capitalizeString, foo }
export
, export the two variables."
@@ -1317,7 +1317,7 @@
"In the export
lesson, you learned about the syntax referred to as a named export. This allowed you to make multiple functions and variables available for use in other files.",
"There is another export
syntax you need to know, known as export default. Usually you will use this syntax if only one value is being exported from a file. It is also used to create a fallback value for a file or module.",
"Here is a quick example of export default
:",
- "export default function add(x,y) {", + "
return x + y;
}
export default function add(x,y) {", "Note: Since
return x + y;
}
export default
is used to declare a fallback value for a module or file, you can only have one value be a default export in each module or file. Additionally, you cannot use export default
with var
, let
, or const
",
"react-redux
package to help accomplish these tasks.",
"React Redux provides a small API with two key features: Provider
and connect
. Another challenge covers connect
. The Provider
is a wrapper component from React Redux that wraps your React app. This wrapper then allows you to access the Redux store
and dispatch
functions throughout your component tree. Provider
takes two props, the Redux store and the child components of your app. Defining the Provider
for an App component might look like this:",
- "<Provider store={store}>", + "
<App/>
</Provider>
<Provider store={store}>", "
<App/>
</Provider>
DisplayMessages
component. The only new piece is the AppWrapper
component at the bottom. Use this top level component to render the Provider
from ReactRedux
, and pass the Redux store as a prop. Then render the DisplayMessages
component as a child. Once you are finished, you should see your React component rendered to the page.",
"Note: React Redux is available as a global variable here, so you can access the Provider with dot notation. The code in the editor takes advantage of this and sets it to a constant Provider
for you to use in the AppWrapper
render method."
@@ -397,7 +397,7 @@
"description": [
"The mapDispatchToProps()
function is used to provide specific action creators to your React components so they can dispatch actions against the Redux store. It's similar in structure to the mapStateToProps()
function you wrote in the last challenge. It returns an object that maps dispatch actions to property names, which become component props
. However, instead of returning a piece of state
, each property returns a function that calls dispatch
with an action creator and any relevant action data. You have access to this dispatch
because it's passed in to mapDispatchToProps()
as a parameter when you define the function, just like you passed state
to mapStateToProps()
. Behind the scenes, React Redux is using Redux's store.dispatch()
to conduct these dispatches with mapDispatchToProps()
. This is similar to how it uses store.subscribe()
for components that are mapped to state
.",
"For example, you have a loginUser()
action creator that takes a username
as an action payload. The object returned from mapDispatchToProps()
for this action creator would look something like:",
- "{", + "
submitLoginUser: function(username) {
dispatch(loginUser(username));
}
}
{", "
submitLoginUser: function(username) {
dispatch(loginUser(username));
}
}
addMessage()
. Write the function mapDispatchToProps()
that takes dispatch
as an argument, then returns an object. The object should have a property submitNewMessage
set to the dispatch function, which takes a parameter for the new message to add when it dispatches addMessage()
."
],
@@ -914,4 +914,4 @@
"reactRedux": true
}
]
-}
\ No newline at end of file
+}
diff --git a/seed/challenges/03-front-end-libraries/react.json b/seed/challenges/03-front-end-libraries/react.json
index 998106189e..5498166e96 100644
--- a/seed/challenges/03-front-end-libraries/react.json
+++ b/seed/challenges/03-front-end-libraries/react.json
@@ -71,7 +71,7 @@
"For instance, several JSX elements written as siblings with no parent wrapper element will not transpile.",
"Here's an example:",
"Valid JSX:",
- "<div>", + "
<p>Paragraph One</p>
<p>Paragraph Two</p>
<p>Paragraph Three</p>
</div>
<div>", "Invalid JSX:", "
<p>Paragraph One</p>
<p>Paragraph Two</p>
<p>Paragraph Three</p>
</div>
<p>Paragraph One</p>", "
<p>Paragraph Two</p>
<p>Paragraph Three</p>
null
. One important thing to note is that React requires your function name to begin with a capital letter. Here's an example of a stateless functional component that assigns an HTML class in JSX:",
- "// After being transpiled, the <div> will have a CSS class of 'customClass'", + "
const DemoComponent = function() {
return (
<div className='customClass' />
);
};
// After being transpiled, the <div> will have a CSS class of 'customClass'", "Because a JSX component represents HTML, you could put several components together to create a more complex HTML page. This is one of the key advantages of the component architecture React provides. It allows you to compose your UI from many separate, isolated components. This makes it easier to build and maintain complex user interfaces.", "
const DemoComponent = function() {
return (
<div className='customClass' />
);
};
MyComponent
. Complete this function so it returns a single div
element which contains some string of text.",
@@ -403,7 +403,7 @@
"releasedOn": "December 25, 2017",
"description": [
"The other way to define a React component is with the ES6 class
syntax. In the following example, Kitten
extends React.Component
:",
- "class Kitten extends React.Component {", + "
constructor(props) {
super(props);
}
render() {
return (
<h1>Hi</h1>
);
}
}
class Kitten extends React.Component {", "This creates an ES6 class
constructor(props) {
super(props);
}
render() {
return (
<h1>Hi</h1>
);
}
}
Kitten
which extends the React.Component
class. So the Kitten
class now has access to many useful React features, such as local state and lifecycle hooks. Don't worry if you aren't familiar with these terms yet, they will be covered in greater detail in later challenges.",
"Also notice the Kitten
class has a constructor
defined within it that calls super()
. It uses super()
to call the constructor of the parent class, in this case React.Component
. The constructor is a special method used during the initialization of objects that are created with the class
keyword. It is best practice to call a component's constructor
with super
, and pass props
to both. This makes sure the component is initialized properly. For now, know that it is standard for this code to be included. Soon you will see other uses for the constructor as well as props
.",
"Navbar
, Dashboard
, and Footer
.",
"To compose these components together, you could create an App
parent component which renders each of these three components as children. To render a component as a child in a React component, you include the component name written as a custom HTML tag in the JSX. For example, in the render
method you could write:",
- "return (", + "
<App>
<Navbar />
<Dashboard />
<Footer />
</App>
)
return (", "When React encounters a custom HTML tag that references another component (a component name wrapped in
<App>
<Navbar />
<Dashboard />
<Footer />
</App>
)
< />
like in this example), it renders the markup for that component in the location of the tag. This should illustrate the parent/child relationship between the App
component and the Navbar
, Dashboard
, and Footer
.",
"ChildComponent
and a React component called ParentComponent
. Compose the two together by rendering the ChildComponent
within the ParentComponent
. Make sure to close the ChildComponent
tag with a forward slash.",
@@ -898,7 +898,7 @@
"releasedOn": "December 25, 2017",
"description": [
"The previous challenges covered a lot about creating and composing JSX elements, functional components, and ES6 style class components in React. With this foundation, it's time to look at another feature very common in React: props. In React, you can pass props, or properties, to child components. Say you have an App
component which renders a child component called Welcome
that is a stateless functional component. You can pass Welcome
a user
property by writing:",
- "<App>", + "
<Welcome user='Mark' />
</App>
<App>", "You use custom HTML attributes that React provides support for to pass the property
<Welcome user='Mark' />
</App>
user
to the component Welcome
. Since Welcome
is a stateless functional component, it has access to this value like so:",
"const Welcome = (props) => <h1>Hello, {props.user}!</h1>", "It is standard to call this value
props
and when dealing with stateless functional components, you basically consider it as an argument to a function which returns JSX. You can access the value of the argument in the function body. With class components, you will see this is a little different.",
@@ -980,7 +980,7 @@
"releasedOn": "December 25, 2017",
"description": [
"The last challenge demonstrated how to pass information from a parent component to a child component as props
or properties. This challenge looks at how arrays can be passed as props
. To pass an array to a JSX element, it must be treated as JavaScript and wrapped in curly braces.",
- "<ParentComponent>", + "
<ChildComponent colors={[\"green\", \"blue\", \"red\"]} />
</ParentComponent>
<ParentComponent>", "The child component then has access to the array property
<ChildComponent colors={[\"green\", \"blue\", \"red\"]} />
</ParentComponent>
colors
. Array methods such as join()
can be used when accessing the property.",
"const ChildComponent = (props) => <p>{props.colors.join(', ')}</p>
",
"This will join all colors
array items into a comma separated string and produce:",
@@ -1416,7 +1416,7 @@
"description": [
"One of the most important topics in React is state
. State consists of any data your application needs to know about, that can change over time. You want your apps to respond to state changes and present an updated UI when necessary. React offers a nice solution for the state management of modern web applications.",
"You create state in a React component by declaring a state
property on the component class in its constructor
. This initializes the component with state
when it is created. The state
property must be set to a JavaScript object
. Declaring it looks like this:",
- "this.state = {
// describe your state here
}", + "this.state = {
// describe your state here
}", "You have access to thestate
object throughout the life of your component. You can update it, render it in your UI, and pass it as props to child components. Thestate
object can be as complex or as simple as you need it to be. Note that you must create a class component by extendingReact.Component
in order to createstate
like this.", "
", "There is a component in the code editor that is trying to render aname
property from itsstate
. However, there is nostate
defined. Initialize the component withstate
in theconstructor
and assign your name to a property ofname
." @@ -1615,7 +1615,7 @@ "releasedOn": "December 25, 2017", "description": [ "The previous challenges covered componentstate
and how to initialize state in theconstructor
. There is also a way to change the component'sstate
. React provides a method for updating componentstate
calledsetState
. You call thesetState
method within your component class like so:this.setState()
, passing in an object with key-value pairs. The keys are your state properties and the values are the updated state data. For instance, if we were storing ausername
in state and wanted to update it, it would look like this:", - "this.setState({", + "
username: 'Lewis'
});this.setState({", "React expects you to never modify
username: 'Lewis'
});state
directly, instead always usethis.setState()
when state changes occur. Also, you should note that React may batch multiple state updates in order to improve performance. What this means is that state updates through thesetState
method can be asynchronous. There is an alternative syntax for thesetState
method which provides a way around this problem. This is rarely needed but it's good to keep it in mind! Please consult the React documentation for further details.", "
", "There is abutton
element in the code editor which has anonClick()
handler. This handler is triggered when thebutton
receives a click event in the browser, and runs thehandleClick
method defined onMyComponent
. Within thehandleClick
method, update the componentstate
usingthis.setState()
. Set thename
property instate
to equal the stringReact Rocks!
.", diff --git a/seed/challenges/03-front-end-libraries/redux.json b/seed/challenges/03-front-end-libraries/redux.json index bb9f214504..b73acbc577 100644 --- a/seed/challenges/03-front-end-libraries/redux.json +++ b/seed/challenges/03-front-end-libraries/redux.json @@ -576,7 +576,7 @@ "When the state of your app begins to grow more complex, it may be tempting to divide state into multiple pieces. Instead, remember the first principle of Redux: all app state is held in a single state object in the store. Therefore, Redux provides reducer composition as a solution for a complex state model. You define multiple reducers to handle different pieces of your application's state, then compose these reducers together into one root reducer. The root reducer is then passed into the ReduxcreateStore()
method.", "In order to let us combine multiple reducers together, Redux provides thecombineReducers()
method. This method accepts an object as an argument in which you define properties which associate keys to specific reducer functions. The name you give to the keys will be used by Redux as the name for the associated piece of state.", "Typically, it is a good practice to create a reducer for each piece of application state when they are distinct or unique in some way. For example, in a note-taking app with user authentication, one reducer could handle authentication while another handles the text and notes that the user is submitting. For such an application, we might write thecombineReducers()
method like this:", - "const rootReducer = Redux.combineReducers({", + "
auth: authenticationReducer,
notes: notesReducer
});const rootReducer = Redux.combineReducers({", "Now, the key
auth: authenticationReducer,
notes: notesReducer
});notes
will contain all of the state associated with our notes and handled by ournotesReducer
. This is how multiple reducers can be composed to manage more complex application state. In this example, the state held in the Redux store would then be a single object containingauth
andnotes
properties.", "
", "There arecounterReducer()
andauthReducer()
functions provided in the code editor, along with a Redux store. Finish writing therootReducer()
function using theRedux.combineReducers()
method. AssigncounterReducer
to a key calledcount
andauthReducer
to a key calledauth
." @@ -1152,4 +1152,4 @@ "redux": true } ] -} \ No newline at end of file +} diff --git a/seed/challenges/04-data-visualization/data-visualization-with-d3.json b/seed/challenges/04-data-visualization/data-visualization-with-d3.json index 7eead6f4e4..4c262bfd97 100644 --- a/seed/challenges/04-data-visualization/data-visualization-with-d3.json +++ b/seed/challenges/04-data-visualization/data-visualization-with-d3.json @@ -21,7 +21,7 @@ "Theappend()
method takes an argument for the element you want to add to the document. It appends an HTML node to a selected item, and returns a handle to that node.", "Thetext()
method either sets the text of the selected node, or gets the current text. To set the value, you pass a string as an argument inside the parentheses of the method.", "Here's an example that selects an unordered list, appends a list item, and adds text:", - "d3.select(\"ul\")", + "
.append(\"li\")
.text(\"Very important item\");d3.select(\"ul\")", "D3 allows you to chain several methods together with periods to perform a number of actions in a row.", "
.append(\"li\")
.text(\"Very important item\");
", "Use theselect
method to select thebody
tag in the document. Thenappend
anh1
tag to it, and add the text \"Learning D3\" into theh1
element." @@ -152,7 +152,7 @@ "A common workflow pattern is to create a new element in the document for each piece of data in the set. D3 has theenter()
method for this purpose.", "Whenenter()
is combined with thedata()
method, it looks at the selected elements from the page and compares them to the number of data items in the set. If there are fewer elements than data items, it creates the missing elements.", "Here is an example that selects aul
element and creates a new list item based on the number of entries in the array:", - "<body>", + "
<ul></ul>
<script>
const dataset = [\"a\", \"b\", \"c\"];
d3.select(\"ul\").selectAll(\"li\")
.data(dataset)
.enter()
.append(\"li\")
.text(\"New item\");
</script>
</body><body>", "It may seem confusing to select elements that don't exist yet. This code is telling D3 to first select the
<ul></ul>
<script>
const dataset = [\"a\", \"b\", \"c\"];
d3.select(\"ul\").selectAll(\"li\")
.data(dataset)
.enter()
.append(\"li\")
.text(\"New item\");
</script>
</body>ul
on the page. Next, select all list items, which returns an empty selection. Then thedata()
method reviews the dataset and runs the following code three times, once for each item in the array. Theenter()
method sees there are noli
elements on the page, but it needs 3 (one for each piece of data indataset
). Newli
elements are appended to theul
and have the text \"New item\".", "
", "Select thebody
node, then select allh2
elements. Have D3 create and append anh2
tag for each item in thedataset
array. The text in theh2
should say \"New Title\". Your code should use thedata()
andenter()
methods." @@ -360,7 +360,7 @@ "description": [ "D3 is about visualization and presentation of data. It's likely you'll want to change the styling of elements based on the data. You can use a callback function in thestyle()
method to change the styling for different elements.", "For example, you may want to color a data point blue if has a value less than 20, and red otherwise. You can use a callback function in thestyle()
method and include the conditional logic. The callback function uses thed
parameter to represent the data point:", - "selection.style(\"color\", (d) => {", + "
/* Logic that returns the color based on a condition */
});selection.style(\"color\", (d) => {", "The
/* Logic that returns the color based on a condition */
});style()
method is not limited to setting thecolor
- it can be used with other CSS properties as well.", "
", "Add thestyle()
method to the code in the editor to set thecolor
of theh2
elements conditionally. Write the callback function so if the data value is less than 20, it returns \"red\", otherwise it returns \"green\".", @@ -848,7 +848,7 @@ "description": [ "The last challenge added only one rectangle to thesvg
element to represent a bar. Here, you'll combine what you've learned so far aboutdata()
,enter()
, and SVG shapes to create and append a rectangle for each data point indataset
.", "A previous challenge showed the format for how to create and append adiv
for each item indataset
:", - "d3.select(\"body\").selectAll(\"div\")", + "
.data(dataset)
.enter()
.append(\"div\")d3.select(\"body\").selectAll(\"div\")", "There are a few differences working with
.data(dataset)
.enter()
.append(\"div\")rect
elements instead ofdivs
. Therects
must be appended to ansvg
element, not directly to thebody
. Also, you need to tell D3 where to place eachrect
within thesvg
area. The bar placement will be covered in the next challenge.", "
", "Use thedata()
,enter()
, andappend()
methods to create and append arect
for each item indataset
. The bars should display all on top of each other, this will be fixed in the next challenge." @@ -925,7 +925,7 @@ "The placement of a rectangle is handled by thex
andy
attributes. They tell D3 where to start drawing the shape in thesvg
area. The last challenge set them each to 0, so every bar was placed in the upper-left corner.", "For a bar chart, all of the bars should sit on the same vertical level, which means they
value stays the same (at 0) for all bars. Thex
value, however, needs to change as you add new bars. Remember that largerx
values push items farther to the right. As you go through the array elements indataset
, the x value should increase.", "Theattr()
method in D3 accepts a callback function to dynamically set that attribute. The callback function takes two arguments, one for the data point itself (usuallyd
) and one for the index of the data point in the array. The second argument for the index is optional. Here's the format:", - "selection.attr(\"property\", (d, i) => {", + "
/*
* d is the data point value
* i is the index of the data point in the array
*/
})selection.attr(\"property\", (d, i) => {", "It's important to note that you do NOT need to write a
/*
* d is the data point value
* i is the index of the data point in the array
*/
})for
loop or useforEach()
to iterate over the items in the data set. Recall that thedata()
method parses the data set, and any method that's chained afterdata()
is run once for each item in the data set.", "
", "Change thex
attribute callback function so it returns the index times 30.", @@ -1024,7 +1024,7 @@ ], "description": [ "The height of each bar can be set to the value of the data point in the array, similar to how thex
value was set dynamically.", - "selection.attr(\"property\", (d, i) => {", + "
/*
* d is the data point value
* i is the index of the data point in the array
*/
})selection.attr(\"property\", (d, i) => {", "
/*
* d is the data point value
* i is the index of the data point in the array
*/
})
", "Change the callback function for theheight
attribute to return the data value times 3.", "Note
Remember that multiplying all data points by the same constant scales the data (like zooming in). It helps to see the differences between bar values in this example." @@ -2172,7 +2172,7 @@ "Given a complex data set, one priority is to set the scale so the visualization fits the SVG container's width and height. You want all the data plotted inside the SVG canvas so it's visible on the web page.", "The example below sets the x-axis scale for scatter plot data. Thedomain()
method passes information to the scale about the raw data values for the plot. Therange()
method gives it information about the actual space on the web page for the visualization.", "In the example, the domain goes from 0 to the maximum in the set. It uses themax()
method with a callback function based on the x values in the arrays. The range uses the SVG canvas' width (w
), but it includes some padding, too. This puts space between the scatter plot dots and the edge of the SVG canvas.", - "const dataset = [", + "
[ 34, 78 ],
[ 109, 280 ],
[ 310, 120 ],
[ 79, 411 ],
[ 420, 220 ],
[ 233, 145 ],
[ 333, 96 ],
[ 222, 333 ],
[ 78, 320 ],
[ 21, 123 ]
];
const w = 500;
const h = 500;
// Padding between the SVG canvas boundary and the plot
const padding = 30;
const xScale = d3.scaleLinear()
.domain([0, d3.max(dataset, (d) => d[0])])
.range([padding, w - padding]);const dataset = [", "The padding may be confusing at first. Picture the x-axis as a horizontal line from 0 to 500 (the width value for the SVG canvas). Including the padding in the
[ 34, 78 ],
[ 109, 280 ],
[ 310, 120 ],
[ 79, 411 ],
[ 420, 220 ],
[ 233, 145 ],
[ 333, 96 ],
[ 222, 333 ],
[ 78, 320 ],
[ 21, 123 ]
];
const w = 500;
const h = 500;
// Padding between the SVG canvas boundary and the plot
const padding = 30;
const xScale = d3.scaleLinear()
.domain([0, d3.max(dataset, (d) => d[0])])
.range([padding, w - padding]);range()
method forces the plot to start at 30 along that line (instead of 0), and end at 470 (instead of 500).", "
", "Use theyScale
variable to create a linear y-axis scale. The domain should start at zero and go to the maximum y value in the set. The range should use the SVG height (h
) and include padding.", @@ -2260,7 +2260,7 @@ "description": [ "With the scales set up, it's time to map the scatter plot again. The scales are like processing functions that turn the x and y raw data into values that fit and render correctly on the SVG canvas. They keep the data within the screen's plotting area.", "You set the coordinate attribute values for an SVG shape with the scaling function. This includesx
andy
attributes forrect
ortext
elements, orcx
andcy
forcircles
. Here's an example:", - "shape", + "
.attr(\"x\", (d) => xScale(d[0]))shape", "Scales set shape coordinate attributes to place the data points onto the SVG canvas. You don't need to apply scales when you display the actual data value, for example, in the
.attr(\"x\", (d) => xScale(d[0]))text()
method for a tooltip or label.", "
", "UsexScale
andyScale
to position both thecircle
andtext
shapes onto the SVG canvas. For thecircles
, apply the scales to set thecx
andcy
attributes. Give them a radius of 5 units, too.", @@ -2444,7 +2444,7 @@ "Unlikerect
,circle
, andtext
, an axis is just a straight line when it's rendered. Because it is a simple shape, usingg
works.", "The last step is to apply atransform
attribute to position the axis on the SVG canvas in the right place. Otherwise, the line would render along the border of SVG canvas and wouldn't be visible.", "SVG supports different types oftransforms
, but positioning an axis needstranslate
. When it's applied to theg
element, it moves the whole group over and down by the given amounts. Here's an example:", - "const xAxis = d3.axisBottom(xScale);", + "
svg.append(\"g\")
.attr(\"transform\", \"translate(0, \" + (h - padding) + \")\")
.call(xAxis);const xAxis = d3.axisBottom(xScale);", "The above code places the x-axis at the bottom of the SVG canvas. Then it's passed as an argument to the
svg.append(\"g\")
.attr(\"transform\", \"translate(0, \" + (h - padding) + \")\")
.call(xAxis);call()
method.", "The y-axis works is the same way, except thetranslate
argument is in the form (x, 0). Becausetranslate
is a string in theattr()
method above, you can use concatenation to include variable values for its arguments.", "
", @@ -2544,4 +2544,4 @@ } } ] -} \ No newline at end of file +} diff --git a/seed/challenges/04-data-visualization/json-apis-and-ajax.json b/seed/challenges/04-data-visualization/json-apis-and-ajax.json index 3d96f97dd5..971c9e8fe3 100644 --- a/seed/challenges/04-data-visualization/json-apis-and-ajax.json +++ b/seed/challenges/04-data-visualization/json-apis-and-ajax.json @@ -180,7 +180,7 @@ "These properties and their values are often referred to as \"key-value pairs\".", "However, JSON transmitted by APIs are sent asbytes
, and your application receives it as astring
. These can be converted into JavaScript objects, but they are not JavaScript objects by default. TheJSON.parse
method parses the string and constructs the JavaScript object described by it.", "You can request the JSON from freeCodeCamp's Cat Photo API. Here's the code you can put in your click event to do this:", - "req=new XMLHttpRequest();", + "
req.open(\"GET\",'/json/cats.json',true);
req.send();
req.onload=function(){
json=JSON.parse(req.responseText);
document.getElementsByClassName('message')[0].innerHTML=JSON.stringify(json);
};req=new XMLHttpRequest();", "Here's a review of what each piece is doing. The JavaScript
req.open(\"GET\",'/json/cats.json',true);
req.send();
req.onload=function(){
json=JSON.parse(req.responseText);
document.getElementsByClassName('message')[0].innerHTML=JSON.stringify(json);
};XMLHttpRequest
object has a number of properties and methods that are used to transfer data. First, an instance of theXMLHttpRequest
object is created and saved in thereq
variable.", "Next, theopen
method initializes a request - this example is requesting data from an API, therefore is a \"GET\" request. The second argument foropen
is the URL of the API you are requesting data from. The third argument is a Boolean value wheretrue
makes it an asynchronous request.", "Thesend
method sends the request. Finally, theonload
event handler parses the returned data and applies theJSON.stringify
method to convert the JavaScript object into a string. This string is then inserted as the message text.", @@ -376,11 +376,11 @@ "First, declare an html variable withvar html = \"\";
.", "Then, loop through the JSON, adding HTML to the variable that wraps the key names instrong
tags, followed by the value. When the loop is finished, you render it.", "Here's the code that does this:", - "json.forEach(function(val) { var keys = Object.keys(val); html += \"<div class = 'cat'>\"; keys.forEach(function(key) { html += \"<strong>\" + key + \"</strong>: \" + val[key] + \"<br>\"; }); html += \"</div><br>\";});", + "json.forEach(function(val) { var keys = Object.keys(val); html += \"<div class = 'cat'>\"; keys.forEach(function(key) { html += \"<strong>\" + key + \"</strong>: \" + val[key] + \"<br>\"; }); html += \"</div><br>\";});", "
", "Add aforEach
method to loop over the JSON data and create the HTML elements to display it.", "Here is some example JSON", - "[ { \"id\":0, \"imageLink\":\"https://s3.amazonaws.com/freecodecamp/funny-cat.jpg\", \"altText\":\"A white cat wearing a green helmet shaped melon on its head. \", \"codeNames\":[ \"Juggernaut\", \"Mrs. Wallace\", \"Buttercup\" ] }]" + "[ { \"id\":0, \"imageLink\":\"https://s3.amazonaws.com/freecodecamp/funny-cat.jpg\", \"altText\":\"A white cat wearing a green helmet shaped melon on its head. \", \"codeNames\":[ \"Juggernaut\", \"Mrs. Wallace\", \"Buttercup\" ] }]" ], "tests": [ { @@ -565,7 +565,7 @@ "If you don't want to render every cat photo you get from the freeCodeCamp Cat Photo API, you can pre-filter the JSON before looping through it.", "Given that the JSON data is stored in an array, you can use thefilter
method to filter out the cat whose \"id\" key has a value of 1.", "Here's the code to do this:", - "json = json.filter(function(val) {", + "
return (val.id !== 1);
});json = json.filter(function(val) {", "
return (val.id !== 1);
});
", "Add code tofilter
the json data to remove the cat with the \"id\" value of 1." ], @@ -661,7 +661,7 @@ "You will see a prompt to allow or block this site from knowing your current location. The challenge can be completed either way, as long as the code is correct.", "By selecting allow, you will see the text on the output phone change to your latitude and longitude.", "Here's code that does this:", - "if (navigator.geolocation){", + "
navigator.geolocation.getCurrentPosition(function(position) {
document.getElementById('data').innerHTML=\"latitude: \"+ position.coords.latitude + \"<br>longitude: \" + position.coords.longitude;
});
}if (navigator.geolocation){", "First, it checks if the
navigator.geolocation.getCurrentPosition(function(position) {
document.getElementById('data').innerHTML=\"latitude: \"+ position.coords.latitude + \"<br>longitude: \" + position.coords.longitude;
});
}navigator.geolocation
object exists. If it does, thegetCurrentPosition
method on that object is called, which initiates an asynchronous request for the user's position. If the request is successful, the callback function in the method runs. This function accesses theposition
object's values for latitude and longitude using dot notation and updates the HTML.", "
", "Add the example code inside thescript
tags to check a user's current location and insert it into the HTML." @@ -717,7 +717,7 @@ "description": [ "In the previous examples, you received data from an external resource. You can also send data to an external resource, as long as that resource supports AJAX requests and you know the URL.", "JavaScript'sXMLHttpRequest
method is also used to post data to a server. Here's an example:", - "req=new XMLHttpRequest();", + "
req.open(\"POST\",url,true);
req.setRequestHeader('Content-Type','text/plain');
req.onreadystatechange=function(){
if(req.readyState==4 && req.status==200){
document.getElementsByClassName('message')[0].innerHTML=req.responseText;
}
};
req.send(userName);req=new XMLHttpRequest();", "You've seen several of these methods before. Here the
req.open(\"POST\",url,true);
req.setRequestHeader('Content-Type','text/plain');
req.onreadystatechange=function(){
if(req.readyState==4 && req.status==200){
document.getElementsByClassName('message')[0].innerHTML=req.responseText;
}
};
req.send(userName);open
method initializes the request as a \"POST\" to the given URL of the external resource, and uses thetrue
Boolean to make it asynchronous.", "ThesetRequestHeader
method sets the value of an HTTP request header, which contains information about the sender and the request. It must be called after theopen
method, but before thesend
method. The two parameters are the name of the header and the value to set as the body of that header.", "Next, theonreadystatechange
event listener handles a change in the state of the request. AreadyState
of 4 means the operation is complete, and astatus
of 200 means it was a successful request. The document's HTML can be updated.", @@ -819,4 +819,4 @@ } } ] -} \ No newline at end of file +}