Příspěvky

Zobrazují se příspěvky z květen, 2017

FreeCodeCamp.com - Basic JavaSript - Iterate with JavaScript For Loops

Link to FreeCodeCamp You can run the same code multiple times by using a loop. The most common type of JavaScript loop is called a " for loop " because it runs "for" a specific number of times. For loops are declared with three optional expressions separated by semicolons: for ([initialization]; [condition]; [final-expression]) The initialization statement is executed one time only before the loop starts. It is typically used to define and setup your loop variable. The condition statement is evaluated at the beginning of every loop iteration and will continue as long as it evaluates to true . When condition is false at the start of the iteration, the loop will stop executing. This means if condition starts as false , your loop will never execute. The final-expression is executed at the end of each loop iteration, prior to the next condition check and is usually used to increment or decrement your loop counter. In the following example we i...

FreeCodeCamp.com - Basic JavaSript - Accessing Nested Arrays

Link to FreeCodeCamp 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" Instructions Retrieve the second tree from the variable myPlants using object dot and array bracket notation. Sollution // Setup var myPlants = [   {      type: "flowers",     list: [       "rose",       "tulip",       "dandelion"     ]   },   {     type: "trees...

FreeCodeCamp.com - Basic JavaSript - Accessing Objects Properties with Variables

Link to FreeCodeCamp A big thank you goes for  amykotas    fro giving this advice in the feed. Another use of bracket notation on objects is to use a variable to access a property. This can be very useful for iterating through lists of the object properties or for doing the lookup. Here is an example of using a variable to access a property: var someProp = "propName"; var myObj = { propName: "Some Value" } myObj[someProp]; // "Some Value" Here is one more: var myDog = "Hunter"; var dogs = { Fido: "Mutt", Hunter: "Doberman", Snoopie: "Beagle" } var breed = dogs[myDog]; console.log(breed);// "Doberman" Note that we do not use quotes around the variable name when using it to access the property because we are using the value of the variable, not the name Instructions Use the playerNumber variable to lookup player 16 in testObj using bracket notation. Sollution // Set...

FreeCodeCamp.com - Basic JavaSript - Using Objects for Lookups

Link to FreeCodeCamp A big thank you goes to  SaintPeter , for giving this advice . 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" Instructions Convert the switch statement into a lookup table called lookup . Use it to lookup val and assign the associated string to the result variable. Sollution // Setup function phoneticLookup(val) {   var result = "";   // Only change code below this line var lo...

FreeCodeCamp.com - Basic JavaSript - Understand String Immutability

Link to FreeCodeCamp In JavaScript, String values are immutable , which means that they cannot be altered once created. For example, the following code: var myStr = "Bob"; myStr[0] = "J"; cannot change the value of myStr to "Job", because the contents of myStr cannot be altered. Note that this does not mean that myStr cannot be changed, just that the individual characters of a string literal cannot be changed. The only way to change myStr would be to assign it with a new string, like this: var myStr = "Bob"; myStr = "Job"; Instructions Correct the assignment to myStr to achieve the desired effect. Sollution // Setup var myStr = "Jello World"; // Only change code below this line myStr = "Hello World";

FreeCodeCamp.com - Basic JavaSript - Word Blanks

Link to FreeCodeCamp We will now use our knowledge of strings to build a " Mad Libs " style word game we're calling "Word Blanks". You will create an (optionally humorous) "Fill in the Blanks" style sentence. You will need to use string operators to build a new string, result , using the provided variables: myNoun , myAdjective , myVerb , and myAdverb . You will also need to use additional strings, which will not change, and must be in between all of the provided words. The output should be a complete sentence. We have provided a framework for testing your results with different words. The tests will run your function with several different inputs to make sure all of the provided words appear in the output, as well as your extra strings. Sollution function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) {   var result = "";   // Your code below this line   result+= "My "+myAdjective+" "+myNoun+...

FreeCodeCamp.com - Basic JavaSript - Golf Code

Link to FreeCodeCamp In the game of golf each hole has a par meaning the average number of strokes a golfer is expected to make in order to sink the ball in a hole to complete the play. Depending on how far above or below par your strokes are, there is a different nickname. Your function will be passed par and strokes arguments. Return the correct string according to this table which lists the strokes in order of priority; top (highest) to bottom (lowest): Strokes Return 1 "Hole-in-one!" <= par - 2 "Eagle" par - 1 "Birdie" par "Par" par + 1 "Bogey" par + 2 "Double Bogey" >= par + 3 "Go Home!" par and strokes will always be numeric and positive. Sollution function golfScore(par, strokes) {   // Only change code below this line   if (strokes === 1){     return "Hole-in-one!";   } else if (strokes <= par - 2){     return "Eagle";   } else i...

FreeCodeCamp.com - Basic JavaSript - Chaining If Else Statements

Link to FreeCodeCamp 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 } Instructions Write chained if / else if statements to fulfill the following conditions: num < 5 - return "Tiny" num < 10 - return "Small" num < 15 - return "Medium" num < 20 - return "Large" num >= 20 - return "Huge" Sollution function testSize(num) {   // Only change code below this line      if (num < 5) {     return "Tiny";   } else if (num <  10) {     return "Small";   } else if (num <  15) {     return "Medium";   } else if (num <  20) {     return "Large";   } else if (num >= 20) {     return "Huge"; ...

FreeCodeCamp.com - Basic JavaSript - Passing Values to Functions with Arguments

Link Parameters are variables that act as placeholders for the values that are to be input to a function when it is called. When a function is defined, it is typically defined along with one or more parameters. The actual values that are input (or "passed" ) into a function when it is called are known as arguments . Here is a function with two parameters, param1 and param2 : function testFun(param1, param2) { console.log(param1, param2); } Then we can call testFun : testFun("Hello", "World"); We have passed two arguments, "Hello" and "World" . Inside the function, param1 will equal "Hello" and param2 will equal "World". Note that you could call testFun again with different arguments and the parameters would take on the value of the new arguments. Instructions Create a function called functionWithArgs that accepts two arguments and outputs their sum to the dev console. Call the function...

FreeCodeCamp.com - Basic JavaSript - Manipulate Arrays With push

Link An easy way to append data to the end of an array is via the push() function. .push() takes one or more parameters and "pushes" them onto the end of the array. var arr = [1,2,3]; arr.push(4); // arr is now [1,2,3,4] Instructions Push ["dog", 3] onto the end of the myArray variable. Sollution // Example var ourArray = ["Stimpson", "J", "cat"]; ourArray.push(["happy", "joy"]);  // ourArray now equals ["Stimpson", "J", "cat", ["happy", "joy"]] // Setup var myArray = [["John", 23], ["cat", 2]]; // Only change code below this line. myArray.push(["dog", 3]);

FreeCodeCamp.com - Basic JavaSript - Modify Array Data With Indexes

Link Unlike strings, the entries of arrays are mutable and can be changed freely. Example var ourArray = [3,2,1]; ourArray[0] = 1; // equals [1,2,1] Instructions Modify the data stored at index 0 of myArray to a value of 3 . Sollution: // Example var ourArray = [1,2,3]; ourArray[1] = 3; // ourArray now equals [1,3,3]. // Setup var myArray = [1,2,3]; // Only change code below this line. myArray[0] = 3;

FreeCodeCamp.com - Basic JavaSript - Nest one Array within Another Array

Link You can also nest arrays within other arrays, like this: [["Bulls", 23], ["White Sox", 45]] . This is also called a Multi-dimensional Array . Instructions Create a nested array called myArray . Sollution: // Example var ourArray = [["the universe", 42], ["everything", 101010]]; // Only change code below this line. var myArray = [["hi", 22],["people",6]];

FreeCodeCamp.com - Basic JavaSript - Use Bracket Notation to Find the Last Character in a String

Link to FreeCodeCamp In order to get the last letter of a string, you can subtract one from the string's length. For example, if var firstName = "Charles" , you can get the value of the last letter of the string by using firstName[firstName.length - 1] . Instructions Use bracket notation to find the last character in the lastName variable. Hint Try looking at the lastLetterOfFirstName variable declaration if you get stuck. Sollution: // Example var firstName = "Ada"; var lastLetterOfFirstName = firstName[firstName.length - 1]; // Setup var lastName = "Lovelace"; // Only change code below this line. var lastLetterOfLastName = lastName[lastName.length - 1];

FreeCodeCamp.com - Basic JavaSript - Use Bracket Notation to Find the Nth Character in a String

Link to FreeCodeCamp You can also use bracket notation to get the character at other positions within a string. Remember that computers start counting at 0 , so the first character is actually the zeroth character. Instructions Let's try to set thirdLetterOfLastName to equal the third letter of the lastName variable using bracket notation. Hint Try looking at the secondLetterOfFirstName variable declaration if you get stuck. Sollution: // Example var firstName = "Ada"; var secondLetterOfFirstName = firstName[1]; // Setup var lastName = "Lovelace"; // Only change code below this line. var thirdLetterOfLastName = lastName[2];

FreeCodeCamp.com - Basic JavaSript - Appending Variables to Strings

Link to FreeCodeCamp Just as we can build a string over multiple lines out of string literals , we can also append variables to a string using the plus equals ( += ) operator. Instructions Set someAdjective and append it to myStr using the += operator. Sollution: // Example var anAdjective = "awesome!"; var ourStr = "Free Code Camp is "; ourStr += anAdjective; // Only change code below this line var someAdjective = "great"; var myStr = "Learning to code is "; myStr += someAdjective;

FreeCodeCamp.com - Basic JavaSript - Concatenating Strings with the Plus Equals Operator

Link: https://www.freecodecamp.com/challenges/concatenating-strings-with-the-plus-equals-operator#?solution=%0A%2F%2F%20Example%0Avar%20ourStr%20%3D%20%22I%20come%20first.%20%22%3B%0AourStr%20%2B%3D%20%22I%20come%20second.%22%3B%0A%0A%2F%2F%20Only%20change%20code%20below%20this%20line%0A%0Avar%20myStr%20%3D%20%22This%20is%20the%20first%20sentence.%20%22%3B%0AmyStr%20%2B%3D%20%22This%20is%20the%20second%20sentence.%22%3B%0A%0A%0A We can also use the += operator to concatenate a string onto the end of an existing string variable. This can be very helpful to break a long string over several lines. Note Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself. Instructions Build myStr over several lines by concatenating these two strings: "This is the first sentence. " and "This is the second sentence." using the += operator. Sollution: // Example var ourStr = "I come...

FreeCodeCamp.com - Basic JavaSript - Convert Celsius to Fahrenheit

Link: https://www.freecodecamp.com/challenges/convert-celsius-to-fahrenheit#?solution=%0Afunction convertToF(celsius) {%0A var fahrenheit%3B%0A %2F%2F Only change code below this line%0A%0A fahrenheit %3D celsius * 9 %2F 5 %2B 32%3B %0A%0A %2F%2F Only change code above this line%0A return fahrenheit%3B%0A}%0A%0A%2F%2F Change the inputs below to test your code%0AconvertToF(30)%3B%0A To test your learning, you will create a solution "from scratch". Place your code between the indicated lines and it will be tested against multiple test cases. The algorithm to convert from Celsius to Fahrenheit is the temperature in Celsius times 9/5 , plus 32 . You are given a variable celsius representing a temperature in Celsius. Use the variable fahrenheit already defined and apply the algorithm to assign it the corresponding temperature in Fahrenheit. Note Don't worry too much about the function and return statements as they will be covered in future challenges. For no...

FreeCodeCamp.com - Basic JavaSript - Decrement a Number with JavaScript

Link: https://www.freecodecamp.com/challenges/decrement-a-number-with-javascript#?solution=%0Avar%20myVar%20%3D%2011%3B%0A%0A%2F%2F%20Only%20change%20code%20below%20this%20line%0AmyVar--%3B%0AmyVar%20%3D%20myVar%3B%0A%0A You can easily decrement or decrease a variable by one with the -- operator. i--; is the equivalent of i = i - 1; Note The entire line becomes i--; , eliminating the need for the equal sign. Instructions Change the code to use the -- operator on myVar . Sollution : var myVar = 11; // Only change code below this line myVar--; myVar = myVar;

FreeCodeCamp.com - Basic JavaSript - Increment a Number with JavaScript

Link: https://www.freecodecamp.com/challenges/increment-a-number-with-javascript#?solution=%0Avar%20myVar%20%3D%2087%3B%0A%0A%2F%2F%20Only%20change%20code%20below%20this%20line%0AmyVar%2B%2B%3B%0AmyVar%20%3D%2088%3B%0A%0A You can easily increment or add one to a variable with the ++ operator. i++; is the equivalent of i = i + 1; Note The entire line becomes i++; , eliminating the need for the equal sign. Instructions Change the code to use the ++ operator on myVar . Hint Learn more about Arithmetic operators - Increment (++) . Sollution: var myVar = 87; // Only change code below this line myVar++; myVar = 88;