Get help on our basic JavaScript and Algorithms Challenges. If you are posting code that is large use Gist - https://gist.github.com/ paste the link here.
result = thing.thinger;
return result;
return thing.thinger;
switch (val) {
case 1:
if (val === "a") {
answer = "apple";
}
break;
case 2:
if (val === "b") {
answer = "bird";
}
break;
case 3:
if (val === "c") {
answer = "cat";
}
break;
default:
answer = "stuff";
}
function slasher(arr, howMany) {
var holderArray = [];
var count = 0;
for (i = count; i === 0; i++) {
holderArray.splice(arr.slice(arr[0], howMany));
}
return holderArray;
}
slasher([1, 2, 3], 2);
//or for (i=count;i = arr.length, i++)
I'm doing the slasher flick bonfire in basic algorithm scripting. I think the middle paremeter to my 4 loop keeps it from running. Amfunction slasher(arr, howMany) {
arr.slice(0, howMany);
return arr;
}
slasher([1, 2, 3], 2);
return arr.slice(0, howMany);
instead of just arr
?
function slasher(arr, howMany) {
// arr.slice(0);
// arr= arr.splice()
return arr.slice(0, howMany);//returns 1,2 not 3
}
slasher([1, 2, 3], 2);
function slasher(arr, howMany) {
arr.slice(0);
arr= arr.splice(howMany);
return arr
;
}
slasher([1, 2, 3], 2);
Haha thanks @Skidle @revisualize @sjames1958gm I was tweaking with the code and this suprised my by working. So let me get this right. So the use of slice dictated that I would cut off the first part of the array, then I reassigned what was left to redifine arr with the howMany argument. Did I butcher that?
cdomiano sends brownie points to @skidle and @revisualize and @sjames1958gm :sparkles: :thumbsup: :sparkles:
:cookie: 259 | @skidle |http://www.freecodecamp.com/skidle
:star2: 4479 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
:star2: 2406 | @revisualize |http://www.freecodecamp.com/revisualize
function convertToF(celsius) {
var fahrenheit;
// Only change code below this line
// Only change code above this line
return fahrenheit;
}
// Change the inputs below to test your code
convertToF(30);
document.querySelector(".quotebox").textContent = Quotation[whichQuotation]
marioecg sends brownie points to @johnnybizzel :sparkles: :thumbsup: :sparkles:
:cookie: 848 | @johnnybizzel |http://www.freecodecamp.com/johnnybizzel
@JohnnyBizzel so i have this:
<div>
<h3 class = quotebox>
quote
</h3>
</div>
marioecg sends brownie points to @lbg232 :sparkles: :thumbsup: :sparkles:
:cookie: 255 | @lbg232 |http://www.freecodecamp.com/lbg232
function checkObj(checkProp) {
// Your Code Here
if ( checkProp !== true ) {
return "Not Found";
} else {
return myObj[checkProp][0];
}
}
emmalee113 sends brownie points to @ylu01 :sparkles: :thumbsup: :sparkles:
:warning: could not find receiver for ylu01
$("#g").on("mousedown", function() {
$("#g").toggleClass('fullGreen');
}).on("mouseup", function() {
$(this).toggleClass('n-green');
});
green
// Set the number of snowflakes (more than 30 - 40 not recommended)
var snowmax=35
// Set the colors for the snow. Add as many colors as you like
var snowcolor=new Array("#aaaacc","#ddddFF","#ccccDD")
// Set the fonts, that create the snowflakes. Add as many fonts as you like
var snowtype=new Array("Arial Black","Arial Narrow","Times","Comic Sans MS")
// Set the letter that creates your snowflake (recommended:*)
var snowletter="*"
// Set the speed of sinking (recommended values range from 0.3 to 2)
var sinkspeed=0.6
// Set the maximal-size of your snowflaxes
var snowmaxsize=22
// Set the minimal-size of your snowflaxes
var snowminsize=8
// Set the snowing-zone
// Set 1 for all-over-snowing, set 2 for left-side-snowing
// Set 3 for center-snowing, set 4 for right-side-snowing
var snowingzone=3
///////////////////////////////////////////////////////////////////////////
// CONFIGURATION ENDS HERE
///////////////////////////////////////////////////////////////////////////
// Do not edit below this line
var snow=new Array()
var marginbottom
var marginright
var timer
var i_snow=0
var x_mv=new Array();
var crds=new Array();
var lftrght=new Array();
var browserinfos=navigator.userAgent
var ie5=document.all&&document.getElementById&&!browserinfos.match(/Opera/)
var ns6=document.getElementById&&!document.all
var opera=browserinfos.match(/Opera/)
var browserok=ie5||ns6||opera
function randommaker(range) {
rand=Math.floor(range*Math.random())
return rand
}
function initsnow() {
if (ie5 || opera) {
marginbottom = document.body.clientHeight
marginright = document.body.clientWidth
}
else if (ns6) {
marginbottom = window.innerHeight
marginright = window.innerWidth
}
var snowsizerange=snowmaxsize-snowminsize
for (i=0;i<=snowmax;i++) {
crds[i] = 0;
lftrght[i] = Math.random()*15;
x_mv[i] = 0.03 + Math.random()/10;
snow[i]=document.getElementById("s"+i)
snow[i].style.fontFamily=snowtype[randommaker(snowtype.length)]
snow[i].size=randommaker(snowsizerange)+snowminsize
snow[i].style.fontSize=snow[i].size
snow[i].style.color=snowcolor[randommaker(snowcolor.length)]
snow[i].sink=sinkspeed*snow[i].size/5
if (snowingzone==1) {snow[i].posx=randommaker(marginright-snow[i].size)}
if (snowingzone==2) {snow[i].posx=randommaker(marginright/2-snow[i].size)}
if (snowingzone==3) {snow[i].posx=randommaker(marginright/2-snow[i].size)+marginright/4}
if (snowingzone==4) {snow[i].posx=randommaker(marginright/2-snow[i].size)+marginright/2}
snow[i].posy=randommaker(2*marginbottom-marginbottom-2*snow[i].size)
snow[i].style.left=snow[i].posx
snow[i].style.top=snow[i].posy
}
movesnow()
}
function movesnow() {
for (i=0;i<=snowmax;i++) {
crds[i] += x_mv[i];
snow[i].posy+=snow[i].sink
snow[i].style.left=snow[i].posx+lftrght[i]*Math.sin(crds[i]);
snow[i].style.top=snow[i].posy
if (snow[i].posy>=marginbottom-2*snow[i].size || parseInt(snow[i].style.left)>(marginright-3*lftrght[i])){
if (snowingzone==1) {snow[i].posx=randommaker(marginright-snow[i].size)}
if (snowingzone==2) {snow[i].posx=randommaker(marginright/2-snow[i].size)}
if (snowingzone==3) {snow[i].posx=randommaker(marginright/2-snow[i].size)+marginright/4}
if (snowingzone==4) {snow[i].posx=randommaker(marginright/2-snow[i].size)+marginright/2}
snow[i].posy=0
}
}
var timer=setTimeout("movesnow()",50)
}
for (i=0;i<=snowmax;i++) {
document.write("<span id='s"+i+"' style='position:absolute;top:-"+snowmaxsize+"'>"+snowletter+"</span>")
}
if (browserok) {
window.onload=initsnow
}
function truthCheck(collection, pre) {
// Is everyone being true?
for (var element in collection) {
if (!collection[element].hasOwnProperty(pre)) {
return false;
}
if (collection[element].pre === undefined) {
return false;
}
}
return true;
}
truthCheck([{"single": "yes"}], "single");
// Setup
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};
function checkObj(checkProp) {
// Your Code Here
myObj.hasOwnPropery(checkProp);
if (true){
return
} else {
return "Not Found";
}
}
// Test your code by modifying these values
checkObj("gift");
function largestOfFour(arr) {
// You can do this!
var array= [];
for(i = 0; i < arr.length; i ++){
for(j = 0; j < arr[i].length; j ++){
array.push(Math.max.apply(Math,arr[j]));
}
}
return array;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
collection[element].pre === undefined)
brennanglynn sends brownie points to @walidashri :sparkles: :thumbsup: :sparkles:
:cookie: 672 | @walidashri |http://www.freecodecamp.com/walidashri
myObj.hasOwnProperty(checkProp)
inside the if statement.
:bulb: to format code use backticks! ``` more info
```function palindrome(str) {
// Good luck!
// strip all non alphanumeric chars
var regex = new RegExp('/[^0-9A-Za-z]','g');
str = str.replace(regex,'');
// downcase
str = str.toLowerCase();
// split into array
var currentStringArray = str.split('');
// join into string
var oldString = currentStringArray.join('');
// reverse and join into string
var reversed = currentStringArray.reverse().join('');
// check if array and reversed array are equal
return oldString == reversed;
}
palindrome("eye"); ```
function palindrome(str) {
// Good luck!
// strip all non alphanumeric chars
var regex = new RegExp('/[^0-9A-Za-z]','g');
str = str.replace(regex,'');
// downcase
str = str.toLowerCase();
// split into array
var currentStringArray = str.split('');
// join into string
var oldString = currentStringArray.join('');
// reverse and join into string
var reversed = currentStringArray.reverse().join('');
// check if array and reversed array are equal
return oldString == reversed;
}
palindrome("eye");
[1,2,3].map(n=>{num: n})
antiaccess sends brownie points to @djcase001 :sparkles: :thumbsup: :sparkles:
:cookie: 332 | @djcase001 |http://www.freecodecamp.com/djcase001
[1,2,3].map(n=>{num: n})
this returns an array of undefined
lowcities sends brownie points to @walidashri :sparkles: :thumbsup: :sparkles:
:cookie: 673 | @walidashri |http://www.freecodecamp.com/walidashri
function whatIsInAName(collection, source) {
// What's in a name?
var arr = [];
// Only change code below this line
var hold = (Object.keys(source));// this is creates array of the property names from source
console.log(hold);
console.log(source[hold]);//this can show the values of the object propertys
for (i=0;i<collection.length;i++) {
console.log(collection[i][hold]);//logs value of
if ( collection[i].hasOwnProperty(hold) && collection[i][hold]==source[hold]){
arr.push(collection[i]);
} else {
console.log(false);
}
}
// Only change code above this line
return arr;
}
whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 });
Math.max.apply()
:warning: antiaccess already gave djcase001 points
antiaccess sends brownie points to @djcase001 :sparkles: :thumbsup: :sparkles:
lowcities sends brownie points to @monag1 :sparkles: :thumbsup: :sparkles:
:cookie: 354 | @monag1 |http://www.freecodecamp.com/monag1
[1,2,3].map(n=>{return{'num': n}})
osakastarbux sends brownie points to @coffeebeanzz :sparkles: :thumbsup: :sparkles:
:star2: 1303 | @coffeebeanzz |http://www.freecodecamp.com/coffeebeanzz
osakastarbux sends brownie points to @lowcities :sparkles: :thumbsup: :sparkles:
:cookie: 244 | @lowcities |http://www.freecodecamp.com/lowcities
// Setup
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};
function checkObj(checkProp) {
// Your Code Here
if (myObj.hasOwnProperty(checkProp) === true){
return myObj[checkProp][];
} else {
return "Not Found";
}
}
// Test your code by modifying these values
checkObj("guf");
joehesse sends brownie points to @coymeetsworld :sparkles: :thumbsup: :sparkles:
:star2: 1561 | @coymeetsworld |http://www.freecodecamp.com/coymeetsworld
function checkObj(checkProp) {
// Your Code Here
if (myObj.hasOwnProperty(checkProp) === true){
return myObj[checkProp];
} else {
return "Not Found";
}
}
newlinebackslash
SecondLinebackslashcarriage-return
ThirdLine
var hi = ‘hello!’;
document.addEventListener(‘input’, function() {
debugger; // why I don’t have access to hi here?
console.log(hi); // but this works fine?
});
let boo = [];
function chunkArrayInGroups(arr, size) {
// Break it up.
if (arr.length === 0) {
return boo;
}
else if (arr.length < size) {
boo.push(arr.slice(0,size));
return boo;
}
boo.push(arr.slice(0,size));
return chunkArrayInGroups(arr.splice(size),size);
}
‘input’
‘hello!’;
function findLongestWord(str) {
var strArray = str.split(' ');
var longest = strArray.reduce(function(accu, curr){
if(curr.length >= accu.length){
return curr;
} else{
return accu;
}
});
return longest.length;
}
curr.length >= accu.length ? curr : accu
I'm having a hard time understanding the mechanics of ===-1 and what it is doing.Can anyone eli5 this for me? Sorry and thanks!
function destroyer(arr) {
var args = Array.prototype.slice.call(arguments);
args.splice(0, 1);
return arr.filter(function(element) {
return args.indexOf(element) === -1;
});
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
"
or '
'jshint esversion:6'
as 1st line in ur code
chazztizer sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 4480 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
walidashri sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
return str.split(' ').reduce((accu, curr) => accu > curr.length ? accu : curr.length, 0);
:star2: 4481 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
function findLongestWord(str) {
const longest = str.split(' ').reduce( (accu, curr) => curr.length >= accu.length ? curr : accu);
return longest.length;
}
return str.split(" ").sort().shift().length;
.sort((a,b)=>a.length-b.length)
/*jshint esversion: 6 */
destroyinglight sends brownie points to @walidashri :sparkles: :thumbsup: :sparkles:
:cookie: 674 | @walidashri |http://www.freecodecamp.com/walidashri
const findLongestWord = str => Math.max(...str.split(' ').map(w => w.length))
//
. Come and join us at the lazy table. :smile:
c0d0er sends brownie points to @walidashri :sparkles: :thumbsup: :sparkles:
:cookie: 675 | @walidashri |http://www.freecodecamp.com/walidashri
function findElement(arr, func) {
var num = 4;
return func;
}
findElement([1, 2, 3, 4], function(num){ return num % 2 === 0; });
var count = 0;
function cc(card) {
// Only change code below this line
count = 0;
var answer = "" ;
switch (card) {
case 2:
case 3:
case 4:
case 5:
case 6:
answer = count++ + " Bet";
break;
case 7:
case 8:
case 9:
answer = count + " Hold";
break;
case 10:
case "J":
case "Q":
case "K":
case "A":
answer = count-- + " Hold";
break;
}
return count;
// Only change code above this line
}
// Add/remove calls to test your function.
// Note: Only the last will display
cc(2); cc(3); cc(7); cc('K'); cc('A');
if(card >= 2 && card <= 6){
// your logic
}
count ++;
count--;
answer = count + string
chhuang sends brownie points to @walidashri :sparkles: :thumbsup: :sparkles:
:cookie: 676 | @walidashri |http://www.freecodecamp.com/walidashri
@cdomiano Here is the code that you posted:
function slasher(arr, howMany) {
arr.slice(0);
arr= arr.splice(howMany);
return arr
;
}
Let's evaluate
function slasher(arr, howMany) {
arr.slice(0); // this does nothing. So, it isn't needed.
arr= arr.splice(howMany);
// assigning a thinger to a thing just to return the thing is pointless.
return arr
;
}
So, we can refactor all of that to...
function slasher(arr, howMany) {
return arr.splice(howMany);
}
But, that's just my thoughts. I could be wrong.const slasher = (a, h) => a.splice(h);
https://gist.github.com/revisualize/ced4a3a6611c6c74bcab34a07eaa4ebf
Parameters are variables that represent the values that get passed into your function from the function call.
https://cs.wellesley.edu/~cs110/lectures/L16/images/function-anatomy.png
Notice how the variables level
and score
in the function definition addScore
are called parameters.
However, when we invoke the function like in:addScore(3, 10)
or addScore(6, 20)
the values are called arguments. Here is an important lesson:
You define a function with parameters, you call a function with arguments.
Another example of this:
function hello(fName, uName) {
return "Hello " + fName + " " + uName + ", How is your day?";
}
hello("Joseph", "@revisualize"); // "Hello Joseph @revisualize, How is your day?"
hello("Bella", "@bellaknoti"); // "Hello Bella @bellaknoti, How is your day?"
hello("Andy", "@dirn"); // "Hello Andy @dirn, How is your day?"
You can use the fName
and uName
parameters just like a variable inside of your function.
Other important things to remember:
* A function can have zero parameters. You still have to use the parentheses to define it.
* A function might have no return statements. In this case we say that the function returns undefined.
....
var name = function() { return "Joseph"; }
The push()
method adds one or more elements to the end of an array and returns the new length of the array.
The pop()
method removes the last element from an array and returns that element.
The shift()
method removes the first element from an array and returns that element.
The unshift()
method adds one or more elements to the beginning of an array and returns the new length of the array.
function nextInLine(arr, item) {
// Your code here
arr.push();
item.shift();
return item; // Change this line
}
// Test Setup
var testArr = [1,2,3,4,5];
// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));
arr
) and a number (item
).
item = arr.shift()
function nextInLine(arr, item) {
// Your code here
arr.shift();
arr.push();
return item; // Change this line
}
// Test Setup
var testArr = [1,2,3,4,5];
// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));
function nextInLine(arr, item) {
// Your code here
item = arr.push();
item = arr.shift();
return item; // Change this line
}
// Test Setup
var testArr = [1,2,3,4,5];
// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));
item
?
function nextInLine(arr, item) {
// Your code here
arr.push();
item = arr.shift();
return item; // Change this line
}
// Test Setup
var testArr = [1,2,3,4,5];
// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));
function nextInLine(arr, item) {
// Your code here
arr.push();
arr.shift();
return item; // Change this line
}
// Test Setup
var testArr = [1,2,3,4,5];
// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));
function nextInLine(arr, item) {
arr.push(item);
return arr.shift();
}
// Change this line
The push()
method adds one or more elements to the end of an array and returns the new length of the array.
The shift()
method removes the first element from an array and returns that element.
var name = function() { return "Joseph"; }
function nextInLine(arr, item) {
// Your code here
arr.push(item);
var removed = arr.shift();
return removed;
}
I just added an extra variable so mine was a little less efficient lol
@revisualize
nextInLine([], 1) should return 1
nextInLine([2], 1) should return 2
nextInLine([5,6,7,8,9], 1) should return 5
How you gonna return 1, 2 or 5 if you don't overwrite the item argument
krystinet sends brownie points to @revisualize :sparkles: :thumbsup: :sparkles:
:star2: 2407 | @revisualize |http://www.freecodecamp.com/revisualize
krystinet sends brownie points to @djcase001 and @revisualize :sparkles: :thumbsup: :sparkles:
:warning: krystinet already gave revisualize points
:cookie: 333 | @djcase001 |http://www.freecodecamp.com/djcase001
Instructions
Declare a local variable myVar inside myLocalScope. Run the tests and then follow the instructions commented out in the editor.
Hint
Refreshing the page may help if you get stuck.
No global myVar variable
code-
unction myLocalScope() {
var myVar = "use strict";
console.log(myVar);
}
myLocalScope();
// Run and check the console
// myVar is not defined outside of myLocalScope
console.log(myVar);
// Now remove the console log line to pass the test
var api="api.openweathermap.org/data/2.5/weather?lat=" + la + "&lon=" + lo + "&APPID=da3ecbc1d1d3735a28ee453521d25614"
$("#g").on("mousedown", function() {
$("#g").toggleClass('fullGreen');
}).on("mouseup", function() {
$("#g").toggleClass('n-green');
});
function updateRecords(id, prop, value) {
var newArray = [];
if ( prop === "artist" && value !== "") {
collection[id].artist = value;
}
else if ( prop === "tracks" && value !== "" ){
collection[id].tracks = newArray;
collection[id].tracks[0] = value;
}
return collection;
}
function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) {
var result = "";
// Your code below this line
myNoun=wordBlanks[0];
myAdjective=wordBlanks[1];
myVerb=wordBlanks[2];
myAdverb=wordBlanks[3];
result="My "+myNoun+" is "+myAdjective+" and "+myVerb+" so "+myAdverb;
// Your code above this line
return result;
}
// Change the words here to test your function
wordBlanks("dog", "big", "ran", "quickly");
// Setup
var collection = {
"2548": {
"album": "Slippery When Wet",
"artist": "Bon Jovi",
"tracks": [
"Let It Rock",
"You Give Love a Bad Name"
]
},
"2468": {
"album": "1999",
"artist": "Prince",
"tracks": [
"1999",
"Little Red Corvette"
]
},
"1245": {
"artist": "Robert Palmer",
"tracks": [ ]
},
"5439": {
"album": "ABBA Gold"
}
};
// Keep a copy of the collection for tests
var collectionCopy = JSON.parse(JSON.stringify(collection));
// Only change code below this line
function updateRecords(id, prop, value) {
var newArray = [];
if ( prop === "artist" && value !== "") {
collection[id].artist = value;
}
else if ( prop === "tracks" && value !== "" ){
collection[id].tracks = newArray;
collection[id].tracks[0] = value;
}
return collection;
}
// Alter values below to test your code
updateRecords(5439, "artist", "ABBA");
updateRecords(2548, "artist", "");
updateRecords(5439, "tracks", "Take a Chance on Me");
updateRecords(2548, "tracks", "");
updateRecords(1245, "tracks", "Addicted to Love");
n-green
class, so just toggle the fullGreen
class on both mousedown and mouseup
myNoun
myAdjective
myVery
and myAdverb
are parameters for the function. While dog
big
ran
and quickly
are arguments to the wordBlanks function. You use the parameters as placeholders. So if you were to simply print out myNoun
the parameter, it would print out "dog" in this instance. You don't access them via an array of the function.
antiaccess sends brownie points to @toianw :sparkles: :thumbsup: :sparkles:
:cookie: 428 | @toianw |http://www.freecodecamp.com/toianw
value === ""
where you should delete a property.
ankitnau25 sends brownie points to @monag1 :sparkles: :thumbsup: :sparkles:
:cookie: 355 | @monag1 |http://www.freecodecamp.com/monag1
wordBlanks[0]
, etc - wordBlanks
is the function name, you can directly access the variables (which are the function parameters) myNoun
, myAdjective
, etc. in the code without the actions that you are taking to try and assign values to them. Their values are assigned by the function call.
wordBlanks
is not an array.. It is a function
ankitnau25 sends brownie points to @monag1 :sparkles: :thumbsup: :sparkles:
:warning: ankitnau25 already gave monag1 points
prop === "tracks"
and the opposite of that - an if
and an else
. Also you have to be careful how you handle the tracks property and value associated with it - it is an array or should be one. If you already have an array there, you just want to add to it. Other times you don't have the array and you need to create it.
.hasOwnProperty()
is just the ticket!
.hasOwnPropery()
returns either true or false.
Here's my code:
function findLongestWord(str) {
var words = str.split(' ');
var maxLength = 0;
for(var i = 0; i < words.length; i++) {
if(words[i].length > maxLength) {
maxLength = words[i].lenght;
}
}
return maxLength;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
maxLength = words[i].lenght;
check length
spelling on that line
is there anything wrong with my code function caseInSwitch(val) {
var answer = "";
// Only change code below this line
switch (val){
case "1":
console.log("alpha");
break;
case "2":
console.log("beta");
break;
case "3":
console.log("gamma");
break;
case "4":
console.log("delta");
break;
}
// Only change code above this line
return answer;
}
// Change this value to test
caseInSwitch(2);
alpha
beta
and so on so you have to set answer equal to alpha
and so on for it to return answer
Anyone PLEASE help me with the Mad Libs "WORD BLANKS" game......WHAT SHOULD BE THE CODE BETWEEN COMMENTS BLOCK?????\
function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) {
var result = "";
// Your code below this line
// Your code above this line
return result;
}
// Change the words here to test your function
wordBlanks("dog", "big", "ran", "quickly");
gandledorf sends brownie points to @heroiczero :sparkles: :thumbsup: :sparkles:
:cookie: 417 | @heroiczero |http://www.freecodecamp.com/heroiczero
variables
provided by the function wordBlanks(myNoun, myAdjective, myVerb, myAdverb)
and then set it equal to result
:cookie: 418 | @heroiczero |http://www.freecodecamp.com/heroiczero
kingisaac95 sends brownie points to @heroiczero :sparkles: :thumbsup: :sparkles:
if ( collection[id].hasOwnProperty("tracks") === false ){
collection[id].tracks = newArray;
collection[id].tracks.push(value);
}
if (collection[id].hasOwnProperty("tracks") === false){ collection[id].tracks = []; } collection[id].tracks.push(value);
if
statement automagically checks for truthy
value
function mutation(arr) {
valid = true;
for (var i = 0; i < arr[1][0].length; i++) {
if (arr[0].toLowerCase().indexOf(arr1.charAt(i).toLowerCase()) == -1) {
valid = false;
}
return valid;
}
}
mutation(["hello", "hey"]);
truthy
!
operator :D
if ( !truthy )
myObj.hasOwnProperty(checkProp) !=
if (!myObj.hasOwnProperty(checkProp))
...
if ( !collection[id].hasOwnProperty("tracks") ){
collection[id].tracks = [];
}
collection[id].tracks.push(value);
else {
}
```js [shift + enter for newline]
<code here>
``` [ctrl + enter to post]
hello guys! need help.
Modify the function checkObj to test myObj for checkProp. If the property is found, return that property's value. If not, return "Not Found".
my code:
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};
function checkObj(checkProp) {
if (true) {
myObj.hasOwnProperty(checkProp);
return myObj.checkProp;
}
return "Change Me!";
}
checkObj("gift");
the function doesn't work, console displays nothing. why?
true
.
checkProp
.
function checkObj(checkProp) {
if (myObj.hasOwnProperty[checkProp]) {
return myObj[checkProp];
}
return "Change Me!";
}
...hasOwnProperty(...)
<- parens here, it is a method.
var cat={clothes:"pants", "lives left":3}; cat.clothes; //returns "pants"
. Bracket notation works with keys that can be arbitrary strings cat["lives left"]; //returns 3
, variables var key="clothes"; cat[key]; //returns "pants"
, or expressions cat["lives"+" "+"left"]; //returns 3
.
erselnordlys sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:star2: 2982 | @masd925 |http://www.freecodecamp.com/masd925
Boolean("Do I just go to middle school and they build me one? Is it one of those situations where I get an AK and they get a good grade?"); // true
checkProp
is the function parameter (a variable in the function execution context that holds the passed key). The passed key is a string.
erselnordlys sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:warning: erselnordlys already gave masd925 points
@erselnordlys that goes into a lot of detail, but this is the important bit
An identifier must start with $, _, or any character in the Unicode categories “Uppercase letter (Lu)”, “Lowercase letter (Ll)”, “Titlecase letter (Lt)”, “Modifier letter (Lm)”, “Other letter (Lo)”, or “Letter number (Nl)”.
Parameters are variables that represent the values that get passed into your function from the function call.
https://cs.wellesley.edu/~cs110/lectures/L16/images/function-anatomy.png
Notice how the variables level
and score
in the function definition addScore
are called parameters.
However, when we invoke the function like in:addScore(3, 10)
or addScore(6, 20)
the values are called arguments. Here is an important lesson:
You define a function with parameters, you call a function with arguments.
Another example of this:
function hello(fName, uName) {
return "Hello " + fName + " " + uName + ", How is your day?";
}
hello("Joseph", "@revisualize"); // "Hello Joseph @revisualize, How is your day?"
hello("Bella", "@bellaknoti"); // "Hello Bella @bellaknoti, How is your day?"
hello("Andy", "@dirn"); // "Hello Andy @dirn, How is your day?"
You can use the fName
and uName
parameters just like a variable inside of your function.
Other important things to remember:
* A function can have zero parameters. You still have to use the parentheses to define it.
* A function might have no return statements. In this case we say that the function returns undefined.
var π = Math.PI;
var ಠ_ಠ = "ahem";
var λ = function() {};
checkProp
is a parameter.
kirbyedy sends brownie points to @revisualize :sparkles: :thumbsup: :sparkles:
:star2: 2409 | @revisualize |http://www.freecodecamp.com/revisualize
var Hͫ̆̒̐ͣ̊̄ͯ͗͏̵̗̻̰̠̬͝ͅE̴̷̬͎̱̘͇͍̾ͦ͊͒͊̓̓̐_̫̠̱̩̭̤͈̑̎̋ͮͩ̒͑̾͋͘Ç̳͕̯̭̱̲̣̠̜͋̍O̴̦̗̯̹̼ͭ̐ͨ̊̈͘͠M̶̝̠̭̭̤̻͓͑̓̊ͣͤ̎͟͠E̢̞̮̹͍̞̳̣ͣͪ͐̈T̡̯̳̭̜̠͕͌̈́̽̿ͤ̿̅̑Ḧ̱̱̺̰̳̹̘̰́̏ͪ̂̽͂̀͠ = 'Zalgo';
@erselnordlys
var name = function() { return "Joseph"; }
What do you think the value of the variable name
is?
arguments
key word. And what it allows you to do.
[Function name]
;)
var name
is assigned to a function. But that function is not called. So the value of name will be a function.
let remainder = 11%3;
erselnordlys sends brownie points to @revisualize and @dancouper :sparkles: :thumbsup: :sparkles:
:cookie: 359 | @dancouper |http://www.freecodecamp.com/dancouper
:star2: 2410 | @revisualize |http://www.freecodecamp.com/revisualize
function getName() { return "Joseph" }
var name = getName();
console.log(name);
revisualize sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:star2: 2983 | @masd925 |http://www.freecodecamp.com/masd925
masd925 sends brownie points to @abhisekp :sparkles: :thumbsup: :sparkles:
:star2: 3192 | @abhisekp |http://www.freecodecamp.com/abhisekp
samuel-mumo sends brownie points to @kyauhen :sparkles: :thumbsup: :sparkles:
:warning: could not find receiver for kyauhen
simon game
and I'm having all of the notes play at the same time despite a time interval. I think I'm using it wrong. Can anyone confirm: for (var i = 0; i < simonArr.length; i++){
setTimeout(output(simonArr[i], 1000));
}
var phoneticLookup= {
// Only change code below this line
"alpha": "Adams",
"bravo": "Boston",
"charlie":"Chicago",
"delta": "Denver",
"echo": "Easy",
"foxtrot": "Frank"
// Only change code above this line
};
// Change this value to test
phoneticLookup("charlie");
commaArraySort =commaArray.sort(function (a, b) { return a - b; });
var commaArraySort = [1,453,2,3,55,1];
commaArraySort =commaArraySort.sort(function (a, b) { return a - b; }); // [ 1, 1, 2, 3, 55, 453 ]
commaArraySort.sort...
is enough.
[1,453,2,3,55,1].sort(function (a, b) { return a - b; });
is enough
[1,453,2,3,55,1].sort(function (a, b) { return a - b; });
is enough
lawfets sends brownie points to @dagman and @masd925 and @liuyueweilan :sparkles: :thumbsup: :sparkles:
:cookie: 2 | @liuyueweilan |http://www.freecodecamp.com/liuyueweilan
:star2: 2984 | @masd925 |http://www.freecodecamp.com/masd925
:cookie: 639 | @dagman |http://www.freecodecamp.com/dagman
input array = [ [ 1, 'Hair Pin' ],
[ 2, 'Hair Pin' ],
[ 21, 'Bowling Ball' ],
[ 67, 'Bowling Ball' ] ]
result = [ [ 3, 'Hair Pin' ],
[ 88, 'Bowling Ball' ],
]
filter
as well.
@rledford I tried something like this:
arraysOfDuplicate.filter(function(arrayofDupEl) {
arraysOfDuplicate.filter(function(arrayofDupOneMoreTime) {
if (arrayofDupEl[1] === arrayofDupOneMoreTime[1]) {
sum += arrayofDupOneMoreTime[0];
}
});
console.log('...', arrayofDupEl);
});
console.log(sum);
But my output is: 182 :(
[ [ 1, 'Hair Pin' ],
[ 2, 'Hair Pin' ],
[ 21, 'Bowling Ball' ],
[ 67, 'Bowling Ball' ] ]
... [ 1, 'Hair Pin' ]
... [ 2, 'Hair Pin' ]
... [ 21, 'Bowling Ball' ]
... [ 67, 'Bowling Ball' ]
182
Array#sort
were not a mutator method.
var arr1 = [1,2,[1,[3]]];
link = arr1[2][1];
return link[0]; //would like to return 3
array.filter(function(arr){ if (arr[0] === someValue) reurn newArr;});
it will be something like that your are trying to get the result you specified above. also where newArr
is a local variable inside the filter function defined. sry for my formatting. on mobile.
dirkra sends brownie points to @revisualize :sparkles: :thumbsup: :sparkles:
:star2: 2411 | @revisualize |http://www.freecodecamp.com/revisualize
```function a() {
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=Albert%20Einstein&origin=*&format=json&utf8=",
dataType: 'json',
type: 'POST',
headers: {
'Api-User-Agent': 'josephine monica'
},
}).done(function(data) {
$("#data").html(JSON.stringify(data));
})
};```
function a() {
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=Albert%20Einstein&origin=*&format=json&utf8=",
dataType: 'json',
type: 'POST',
headers: {
'Api-User-Agent': 'josephine monica'
},
}).done(function(data) {
$("#data").html(JSON.stringify(data));
})
};
function a() {
$.ajax({
url: "https://en.wikipedia.org/w/api.php?origin=*",
dataType: 'json',
type: 'POST',
headers: {
'Api-User-Agent': 'josephine monica'
},
context: {
"action": "query",
"list": "search",
"srsearch": "Albert Einstein",
// "origin":"*",
"format": "json",
"utf8": ""
}
}).done(function(data) {
$("#data").html(JSON.stringify(data));
})
};
var array = [ [ 1, 'Hair Pin' ],
[ 2, 'Hair Pin' ],
[ 21, 'Bowling Ball' ],
[ 67, 'Bowling Ball' ] ];
array.reduce(function(acc,curr,index){
if (index>0 && curr[1]===acc[acc.length-1][1]) acc[acc.length-1][0]+=curr[0];
else acc.push(curr);
return acc;
},[]); // [ [ 3, 'Hair Pin' ], [ 88, 'Bowling Ball' ] ]
@rledford ok, so far I have samoething like this, better then before :smile:
var newArrHP = [];
var newArrBB = [];
var array = [
[ 1, 'Hair Pin' ],
[ 2, 'Hair Pin' ],
[ 21, 'Bowling Ball' ],
[ 67, 'Bowling Ball' ]
];
array.filter(function(arr) {
console.log(arr[0]);
console.log(arr[1]);
if (arr[1] === 'Hair Pin') {
newArrHP.push(arr[0]);
}
if (arr[1] === 'Bowling Ball') {
newArrBB.push(arr[0]);
}
return 99999;
});
console.log('newArrHP', newArrHP);
console.log('newArrBB', newArrBB);
OUTPUT:
1
Hair Pin
2
Hair Pin
21
Bowling Ball
67
Bowling Ball
newArrHP [ 1, 2 ]
newArrBB [ 21, 67 ]
arr[arr.length-1]
is always the last element of an array arr
.
sentence
. You got a
instead of e
esgameco sends brownie points to @xeho91 :sparkles: :thumbsup: :sparkles:
:cookie: 307 | @xeho91 |http://www.freecodecamp.com/xeho91
function bouncer(arr) {
// Don't show a false ID to this bouncer.
var boolean = "";
for (var i = 0; i < arr.length; i++) {
boolean = Boolean(arr[i]);
if (arr[i] !== false && arr[i] !== null && arr[i] !== 0 && arr[i] !== "" && arr[i] !== undefined && !isNaN(arr[i])) {
return boolean;
}
}
}
bouncer([7, "ate", "", false, 9]);
isNaN
is not a test for value NaN
.
isNaN("cat"); // true
skidle sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:star2: 2985 | @masd925 |http://www.freecodecamp.com/masd925
arr[i] !== NaN
?
NaN===NaN
is false.
val===val
skidle sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:warning: skidle already gave masd925 points
NaN
so much so that they invented Number.isNaN
method
Number.isNaN = function isNaN(value) {
return value !== value;
}
array.filter();
I already checked out the documentation and some exampes but I still don't get it
Boolean();
) which returns true
or false
?
Boolean
, not Boolean()
which would be the return value when you call it without arguments.
skidle sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:warning: skidle already gave masd925 points
var count = 0;
function cc(card) {
// Only change code below this line
var count = 0;
switch (card){
case 2:
case 3:
case 4:
case 5:
case 6:
count++;
break;
case 7:
case 8:
case 9:
break;
case 10:
case 'A':
case 'J':
case 'K':
case 'Q':
count--;
break;
}
if(count > 0){
return "Bet";
}
else if (count <= 0){
return "Hold";
}
return "Change Me";
// Only change code above this line
}
// Add/remove calls to test your function.
// Note: Only the last will display
cc(2); cc(3); cc(7); cc('K'); cc('A');
This is what I've written and it doesn't seemed to work. Please help :0
count++
for example.
count + " Bet"
etc.
@Mozar10 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.
count + " Bet"
etc.
function convertToF(celsius) {
var fahrenheit;
// Only change code below this line
fahrenheit=30*1.8+32;
// Only change code above this line
return fahrenheit;
}
// Change the inputs below to test your code
convertToF(30);
celsius
, not fixed value 30
celsius
) will receive the value 30 for that function call.
count + " Bet"
(note that extra space, as there should be one between the number and the word) in your if-else (which does not need a second if).
@DevD01 Remember what I said about the space?
@DevD01 You should however return
count + " Bet"
(note that extra space, as there should be one between the number and the word) in your if-else (which does not need a second if).
convertToF(30)
, its first parameter will receive the value 30. That parameter is named celsius
, and behaves about like a pre-initialized variable, initialized to that value 30. Name is arbitrary, but that's how you can access the argument passed to your function.function greet(name) {
console.log("Hello, " + name);
}
greet("Blauelf"); // prints Hello, Blauelf
name
in my function, which I can use to access the string.
arr
How can I fix this, please?
function bouncer(arr) {
// Don't show a false ID to this bouncer.
var newArr = [];
for (var i = 0; i < arr.length; i++) {
Boolean(arr[i]);
if (Boolean(arr[i]) === false) {
newArr = arr.filter(Boolean);
} else
newArr = arr;
}
return newArr;
}
bouncer([7, "ate", "", false, 9]);
i only put in 30 at the bottom to define celsius so why is solving all the others as well?
function convertToF(celsius) {
var fahrenheit;
// Only change code below this line
fahrenheit=celsius*1.8+32;
// Only change code above this line
return fahrenheit;
}
// Change the inputs below to test your code
convertToF(30);
jkilgore07 sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:star2: 2987 | @blauelf |http://www.freecodecamp.com/blauelf
I'm on a "Falsy Bouncer" challenge now and this code works for everything but that particular arr
How can I fix this, please?
function bouncer(arr) {
// Don't show a false ID to this bouncer.
var newArr = [];
for (var i = 0; i < arr.length; i++) {
Boolean(arr[i]);
if (Boolean(arr[i]) === false) {
newArr = arr.filter(Boolean);
} else
newArr = arr;
}
return newArr;
}
bouncer([7, "ate", "", false, 9]);
Do I need another if condition maybe?
""
skidle sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:star2: 2988 | @blauelf |http://www.freecodecamp.com/blauelf
jkilgore07 sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:warning: jkilgore07 already gave blauelf points
~~~// Setup
function phoneticLookup(val) {
var result = "";
// Only change code below this line
var lookup={
alpha: "Adams",
bravo : "Boston",
charlie: "Chicago",
delta: "Denver",
echo: "Easy",
foxtrot: "Frank"
};
// Only change code above this line
return result;
}
// Change this value to test
phoneticLookup("charlie");
~~~
skidle sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:warning: skidle already gave blauelf points
@Skidle filter iterates an array, so you don't need to. So those two are about equivalent:
var newArr = arr.filter(Boolean);
and
var newArr = [];
for (var i = 0; i < arr.length; i++) {
if (Boolean(arr[i])) {
newArr.push(arr[i]);
}
}
but as if does its own conversion to boolean (just for evaluation), this would work, too:
var newArr = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i]) {
newArr.push(arr[i]);
}
}
and filter works the same, does not rely on true/false but truthy/falsy:
var newArr = arr.filter(function(x){ return x; });
skidle sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:warning: skidle already gave blauelf points
table.selectAll("tbody .table-row").each(function(trData) {
var needed = trData.value.attribute;
$(this).on("click", function(e) {
document.location = "tesst.html#" + needed; // how do i get "needed" in here?
}
}
needed
inside the callback is actually the needed
from the scope it was defined in. So whatever value trData.value.attribute
had at that time.
wait
or time delay function? I'm using setTimeout
but it isn't working the way I want
@Blauelf
table.selectAll("tbody .table-row").each(function(trData) {
$(this).on("click", function(e) {
document.location = "tesst.html#" + trData.value.attribute;
}
}
ok, now i know how it works. though i don't want to change document location but open a modal with a table that contains more information about that data set :)
darkflikk sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:star2: 2989 | @blauelf |http://www.freecodecamp.com/blauelf
trData.value.attribute
of the definition time. If you use it directly, and trData
has been changed in the meantime (probably not relevant here), you might get other values.
:star2: 2985 | @masd925 |http://www.freecodecamp.com/masd925
arr.slice()
, your array arr
does not have a property "slice". It is found on the prototype chain on Array.prototype
, so you essentially call Array.prototype.slice
, and set the this
to arr
, all that happens in a convenient arr.slice()
.
trData
. Building a statistic site with graphs using dc.js
new Array()
(or an implicit version of that), the created object will have Array
set as the constructor and Array.prototype
installed in its prototype chain.
https://codepen.io/antiaccess/pen/wogRwp
darkflikk sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:star2: 2986 | @masd925 |http://www.freecodecamp.com/masd925
waingor sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:star2: 2990 | @blauelf |http://www.freecodecamp.com/blauelf
```function reverseString(str) {
str.split("");
str.reverse();
str.join();
return str;
}
reverseString("hello");```
``` function reverseString(str) {
str.split("");
str.reverse();
str.join();
return str;
}
reverseString("hello");
var collection = {
"2548": {
"album": "Slippery When Wet",
"artist": "Bon Jovi",
"tracks": [
"Let It Rock",
"You Give Love a Bad Name"
]
},
"5439": {
"album": "ABBA Gold"
}
};
// Keep a copy of the collection for tests
var collectionCopy = JSON.parse(JSON.stringify(collection));
// Only change code below this line
function updateRecords(id, prop, value) {
//myObj.hasOwnProperty(checkProp)
if(prop=="artist"&&value!==""){
collection[id].artist = value;
} else if (prop==="artist"&&value===""){
delete collection[id].artist;
} else if (prop==="tracks"&&value!==""){
delete collection[id].artist;
} else if (prop==="tracks"&&value===""){
delete collection[id].tracks;
} else if (prop==="tracks"&&value!==""){
collection[id].tracks.push(value);
} else if (prop==="tracks"&&value!==""&&collection[id].hasOwnProperty(prop)){
collection[id].tracks.push(value);
} else if (prop==="tracks"&&value!==""&&collection[id].hasOwnProperty(prop)===false){
var tracks = [value];
collection[id] = tracks;
}
return collection;
}
var count=0;
function cc(card) {
// Only change code below this line
switch (card) {
case 2,3,4,5,6:
count=count+1;
break;
case 7,8,9:
break;
case 10,"J","Q","K","A":
count=-1;
break;
}
if(count>0){
return count;
}else {
return count;
}
return "Change Me";
// Only change code above this line
}
// Add/remove calls to test your function.
// Note: Only the last will display
cc(2);
cc(7);
cc(9);
cc(7);
cc(8);