i am on my first week of learning javascript; i am a bit confused on how to approach these questions. Please note that you are NOT supposed to console log; the code should run exactly as written to check.
Write a function called countCharacters that takes one argument called word, which is a string. When countCharacters is invoked it will return the number of characters is in the word
countCharacters('hello') // => should return 5
countCharacters('cookie monster') // => should return 14
countCharacters('abcdefghijklmnopqrstuvwxyz') // => should return 26
For this question i am stuck on how to write a function that will count the characters in a string..
function odd(myArray) {
for (let i = 0; i < myArray.length; i++) {
if (myArray.length[i] % 2 === 1) {
return myArray);
}
}
}
Write a function called odd that takes one argument called myArray, which is an array of numbers. When odd is invoked it will log to the console all numbers in the array that are odd
odd([1, 4, 6, 7, 3]) // => should log 1, 7, & 3;
odd([3, 4, 1, 7, 13]) // => should log 3, 1, 7, & 13
or this question i have tried
function odd(myArray) {
for (let i = 0; i < myArray.length; i++) {
if (myArray.length[i] % 2 === 1) {
return myArray);
}
}
}
String has a length property. It represents the length of a String.
function countCharacters(input) {
console.log(input.length)
}
countCharacters('hello')
countCharacters('cookie monster')
countCharacters('abcdefghijklmnopqrstuvwxyz')
Array has a filter function. Use this function to filter elements from your Array.
function odd(input) {
console.log(input.filter(v => v % 2))
}
odd([1, 4, 6, 7, 3])
odd([3, 4, 1, 7, 13])
Pro tip
If you want your function to return instead of logging then just write return foo instead of console.log(foo) inside your function body.
Recommendation I also recommend you highly to make some guided course if you want to get into JavaScript without any developing experience. There are many resources out there. One of many to start: Exercism
For counting characters you probably want something other than return someword.length so here is an alternative.
function countCharacters ( aWord ){
let counter = 0 ;
for(const aChar of aWord ) {
counter ++ ; // exactly like (counter = counter + 1 )
}
return counter ;
}
//test results
let myName = 'mynamehas16chars'
console.log('myName contains',countCharacters(myName),'chars');
This code simply increments counter for each character in aWord to count them .