It’s good to use a mixture, you learn more that way. Probably best to mainly use a text editor like Atom and then run in the browser if you’re scripting JavaScript within HTML
I think a lot of very experienced developers who learnt JavaScript before let and const were introduced still use var out of habit. I started learning with ES6 and so I guess it’s been easier just to learn and use let and const right from the start.
function min (a ,b){
if ( a < b) return a;
else return b;
}
function evenNo (x) {
if (x == 0) return true;
else if (x == 1) return false;
else if (x < 0) return evenNo(-x);
else return evenNo (x - 2);
}
function countChar(string, ch) {
let counted = 0;
for (let i = 0; i < string.length; i++) {
if (string[i] == ch) {
counted += 1;
}
}
return counted;
}
function countBs(string) {
return countChar(string, "B");
}
having a hard time with all of these :frowning:
function countBs(string){
let num_Bs = 0;
for(let counter=0; counter<string.length; counter++){
if(string[counter]== "B"){
num_Bs++;}}
return num_Bs;
}
var numBs = countBs("Be kind But Be cautious");
alert(numBs);
3
I don’t really understand the second half of the question regarding char?
Re-creating Math.min
Here is the function which I call in the console:
function minimum (first, second){
if (first<second){console.log(first)}
else if (first>second){console.log (second)}
else {console.log ("Please enter different numbers")}
}
Recursion:
function isEven(number_in){
number_in = Math.abs(number_in)
if (number_in == 1){
console.log(“odd”)}
else if (number_in == 0){
console.log(“even”)}
else {isEven(number_in - 2)}
}
Bean counting:
function countBs(word,letter){
let numberofBs = 0;
for (let count = 0; count < word.length ; count++){
if (word[count] == letter){numberofBs++}
}
console.log(numberofBs);
}
let min = function(x,y){
if (x<y){
return x
} else return y
}
problem 2.
var isEven = function (x){
if (x % 2 ==0){
return true;
}
else if (x % 2 == 1) {
return false;
}
else if (x%2 < 0 ) {
x = x + 2;
}
else {
x = x - 2;
}
return is even(x);
}
Problem 3.
var charlength = function(word,letter){
var length = word.length;
var numpos = 0;
var chartarget = 0;
for (counter = 0; counter < length; counter++){
if (word[numpos] !== letter){
chartarget = chartarget;
} else {
chartarget = chartarget + 1;
}
numpos = numpos + 1;
}
if (chartarget < 2){
console.log(chartarget + letter);
}else{ console.log( chartarget + " " + letter + “'s”)}
}
The point here was to build a function that has the same functionality as Math.min() without using it. Have another go!
Hint you need to use conditional execution in the function body.
It works
Now let’s improve it…
return true, and return false, are currently superfluous i.e. they don’t do anything. That’s because whatever follows return (here: true/false) is returned from the function to wherever the function was called ( here: isEven() ). However, because you are not logging isEven() to the console, nothing is done with the true/false you are returning. See if you can change that.
I like your additional sentences written to the HTML document. Can you now make each sentence appear on a separate line? That way the text will look clearer on page.
The final part of the task was to add functionality to be able to handle negative numbers. At the moment your function throws an error with the function call isEven(-1). Can you fix that?
I found your use of the string methods .charAt() and .substr() very interesting. You’ve come up with a very creative and innovative solution
Unfortunately, because of a tiny slip you made in the spelling of one of the function names, your code doesn’t execute Can you see what the problem is?
Just one other thing: .substring() should now be used instead of .substr() because it may be removed in the future. What’s the problem with that? Well, if the program was actually going to be deployed on a web page, then it may become incompatible sooner rather than later. How do we know that? A good habit to get into, is checking anything new we use, or learn about, in the documentation. One resource I use (although I’m sure you could find others) is MDN web docs. I find them really helpful. Here’s a link to the page with the documentation about .substr() which tells you right at the beginning what I’ve told you above: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr
Do that!.. Review…review…review! You can never do it enough! … sure way to consolidate and remember what you’re learning
// Chapter 3
// Ex1: Minimum
console.log(Math.min(100, -100));
console.log(Math.min(-200, -500));
//Ex2: Recursion
function isEven(positive) {
if (positive == 0) {
return true;
} else if (positive == 1) {
return false;
} else {
return isEven(Math.abs(positive - 2));
}
}
console.log(isEven(50))
console.log(isEven(75))
console.log(isEven(-2))
//Ex3: Bean Counting
function cons(string, chr) {
var count = 0;
for (var N = 0; N <= string.length; N++) {
if (string[N] == chr) {
count += 1;
}
}
return count;
}
function countBs(string) {
return cons(string, "B");
}
console.log(cons("ArindAAAAAAm", "A"))
console.log(countBs("BallingB"))
I had to take the help of the form to complete Ex 3, Thank you. Can someone in detail please explain to me your understanding of Ex3 because I am confused why is it that when i use:
for (var N = 0; N = string.length-1; N++) {
I get the wrong output for
console.log(countBs("BallingB"))
I get the wrong character count. I am just confused at that part.
Thank you in advance!!!
Your solution works, but you haven’t used recursion. The idea is to use recursion to generate the same functionality as num % 2 but without using it. Have a look again at the exercise, and if you don’t understand where to start, then have a look at the hints (which you can display in the online course book by clicking below the exercise instructions). If you still don’t get it, have a look at other students’ solutions posted here. Then if you’re still stuck let us know and we’ll help you out!
The idea in the second part, is to introduce functionality that can handle a count of any character in a string (not just upper case Bs). In order to do this you need to write a new function countChar that is very similar to the countBs that you already have working, but with an additional parameter char (which “receives” any character). So you’ll need to consider what other changes you need to make to the function for this additional parameter.
Once you’ve done that, you need to test it with a function call with 2 arguments: (1) any string, and (2) any character. Try different string/character combinations to make sure it’s working correctly.
The final step is to return to your original countBs function and decide how you can now slim that down so that in the function body it calls countChar with 2 arguments: (1) the same string passed to the countBs function as the only argument, and (2) "B" (which remains fixed because this function only ever counts the character B).
Then to test this, you need to call countBs with a single argument (any string), which in turn will automatically call countChar, which proceeds to count the number of Bs in the string.
Again, have a look at the hints if you still don’t understand, or need some further help. If that doesn’t help, then scan students’ posts in this forum discussion, and as a last resort ask us for some more help.
For it to work you just need to correct a spelling mistake with the recursive function call. Can you see it?
Ensuring your code is always clearly formatted helps a lot to avoid these kinds of errors. Before you type in your code to post it here in the forum, you can click on the </> icon in the menu at the top of this forum text-editor. That will give you 2 sets of 3 back ticks…
```
```
If you now input your code between these, you will end up with it nicely formatted, which is then also easier for you to organise with the correct spacing, indentation, nesting and brackets etc.
% 2 is not needed after x in each of the if / else if statements. The code executes successfully without it.
Exercise 3
Your code works well, and you have introduced some nice additional functionality
In terms of improvement, you can make the code more concise, as follows:
Remove the variable numpos as counter can do the same job;
By amending the operator !== to === you can remove another 2 lines of code.
Have a look, and think about why you can make these amendments, and see if you can implement them. Another challenge for you!
The idea with Ex.1 is to create a function that has the same functionality as Math.min() but without using it
Have a go, and if you’re not sure where to start, or need some further help, have a look at the hints (which you can display in the online course book by clicking below the exercise instructions). If you still don’t get it, have a look at other students’ solutions posted here. Then if you’re still stuck let us know and we’ll help you out!
Exercise 3
Your current for loop condition N <= string.length actually performs one additional unnecessary iteration, because string.length counts the 1st letter as 1, whereas the counter starts at 0. However, this doesn’t matter because I think the extra iteration checks to see if the letter it’s counting for exists “after” the word has already been iterated through in its entirety. This will always add 0 to the letter count, and so will never have any impact.
I think you’ve mistyped this, because if you use the = operator in the condition, then the function won’t work at all.
N <= string.length - 1
…will give you the correct output (and the correct number of iterations, because there is one less than in your current code), but…
N < string.length - 1
…will give you the wrong output if the last letter is the letter being counted, because the iteration will stop one letter before the last letter
Function min
var min = function (a,b){
if (a>b){
return b;
}
else if (a<b){
return a}
else { return “numbers are equal”}
document.write()
}
Function isEven
function isEven (N){
if(N>=0){
while(N>=2){
N=N-2;
}
if (N==0){
return “even”;}
else if (N==1){
return “Odd”}
}
else
while(N<=-2){
N=N+2;
}
if (N==0){
return “even”;}
else if (N==-1){
return “Odd”}
}
document.write();
Function CountChar
function CountChar(word){
let N=0;
let Bcount=0;
let Char=word[1];
if (isNaN(word)){
while(N<=word.length){
if(word[N]==Char){
Bcount++;
}
N++;
}
return Bcount;
}
else { return “Not a number”;
}
console.log();
}
Some great coding here, @AidanH!
On the whole, you’ve also used indentation very well
Here are some points for you to consider…
Minimum
Your final console.log() logs undefined to the console. This is because you haven’t included return statements in your function, which means it doesn’t return a value to the function call. You could leave the console.log()s in the function body and just remove the one wrapped around the function call, but even though it is often useful to print to the console while testing your code, we would normally want to remove them from our final version. So, I suggest your code should look like this:
// Please try to format each answer's code all together like this...
function answer(a, b) {
if (a < b) {
return a;
else {
return b;
}
}
console.log(answer(4, 3)); // => 3
Recursion
Again, the code is “cleaner” if you remove the console.log()s from within the function body.
You don’t need to return a variable, just the value (here, a string) i.e.
return "This is even";
Bean Counting
There is an additional step to this exercise. Now you have the second function countChar, which has 2 parameters, can you slim down countBs() so that it still only has one parameter, but calls countChar within its function body in order to count and return the number of B’s?
Hi @Matoshi!
There is some good code here, but overall it seems like you’ve found it difficult to understand how to approach exercises 2 and 3.
Here are some points for you to think about…
Minimum
This line doesn’t do anything. Did you mean to display the string on the web page, instead of logging it to the console? It’s not too clear as you haven’t included any function calls, or a console.log() , so I’m not too sure what you were trying to achieve in terms of displaying your output.
Also, I can’t remember if I’ve already explained to you how to format your code when you post it here in the forum. Before you type your code, you can click on the </> icon in the menu at the top of this forum text-editor. That will give you 2 sets of 3 back ticks…
```
```
If you now input your code between these, you will end up with it nicely formatted, which is then also easier for you to organise with the correct spacing, indentation, nesting and brackets etc. Your code for this first exercise should end up looking something like this:
var min = function(a, b) {
if (a > b) {
return b;
}
else if (a < b) {
return a;
}
else {
return "numbers are equal";
}
}
console.log(min(0, -20)); // => -20
Recursion
While your code nearly works (you just have a set of curly brackets missing), you haven’t actually used recursion. Recursion is when a function calls itself in order to create the repetition. Instead you’ve used loops. Have a look again at the course book to see how to code recursion, and how this is different from using a loop. You will see that by using recursion instead of loops for this exercise, we can achieve a simpler, clearer and more concise solution… although maybe you’ll disagree, which is fine… but it’s a good exercise to practise using recursion anyway
Bean Counting
Your code counts the 2nd letter in whatever word is passed to the function. Is that what you’re trying to do?
What the second part of the exercise asks for is a function that has 2 parameters: a word, and any letter. Then it asks for you to change the original countBs function (which only counts B’s) so that it calls the countChar function to count the number of B’s. I think you’ve tried to adapt the countChar function to count B’s (2nd letter in BBC?) but as a stand-alone function i.e. without it being called by CountBs — is that right?
I would go back and look at the exercise again. If you don’t want to spend a lot more time trying to work it out on your own, you could have a look at the hints (which you can display in the online course book by clicking below the exercise instructions). If you still don’t get it, have a look at other students’ solutions posted here, and also the model answer in the course book. Then if you’re still stuck let us know and we’ll help you out!