Stuck. New to JS. Trying to figure this out since hours - javascript

I can't solve exercise three and four. I would be very pleased to get some help. Thank you in advance!
function exerciseThree(str){
// In this exercise, you will be given a variable, it will be called: str
// On the next line create a variable called 'length' and using the length property assign the new variable to the length of str
// Please write your answer in the line above.
return length;
}
function exerciseFour(num1){
// In this exercise, you will be given a variable, it will be called: num1
// On the next line create a variable called 'rounded'. Call the Math global object's round method, passing it num1, and assign it to the rounded variable.
var num1 = rounded;
math.round (num1);
// Please write your answer in the line above.
return rounded;
}

These exercises are trying to teach you how to declare variables and how to assign values to them.
Variables are like little containers that hold values for you. For example, I can make a little container to hold your name. And since one of the ways to declare a variable in JavaScript is to use the var keyword, I could write something as following:
var name = "Sevr";
I made a container with var keyword and named it name. This name container now holds your name which is Sevr. Instead of typing Sevr over and over again you can now type Name over and over. But, this doesn't make much difference. Sevr and name both contain same number of characters. It makes more sense to have your variables contain information that you don't want to type over and over again.
So exercise three wants you to declare a variable named length and make it hold the length of any string that it is provided with.
function exerciseThree(str) {
var length = str.length
return length;
}
This function above takes a string, you make a variable named length that contains the length of that string.
Now if we pass it any string it will tell us what length they are. If we pass it your name Sevr and name and we will see that they both return 4:
exerciseThree("name") // 4
exerciseThree("Sevr") // 4
On the fourth exercise, the concept is the same. The exercise wants to teach you that you can make a simple variable name that can hold on to some complex value for you. This time it wants you to declare variable named rounded that holds on to the rounded value of a number.
function exerciseFour(num1) {
var rounded = Math.round(num1)
return rounded;
}
And, now if you pass a number with decimals to this function it will round it for you.
exerciseFour(4.5) // 5

These exercises are worded in a really confusing way. Where you getting them from?
Anyway, here're the answers, hope they help:
function exerciseThree(str){
// In this exercise, you will be given a variable, it will be called: str
// On the next line create a variable called 'length' and using the length property assign the new variable to the length of str
var length = str.length
// Please write your answer in the line above.
return length;
}
function exerciseFour(num1){
// In this exercise, you will be given a variable, it will be called: num1
// On the next line create a variable called 'rounded'. Call the Math global object's round method, passing it num1, and assign it to the rounded variable.
var rounded = Math.round(num1)
// Please write your answer in the line above.
return rounded;
}

Related

When do I need to create a new variable within a function?

I'm a new learner of JavaScript, and when I get to learn the way of using a function. It sometime confuses me on why we should declare a new variable and add the variable to the action we want to execute. Let's look into the code.
function reverse(word){
Array.from(word);
let reverseWord='';
for(i = word.length-1; i >= 0; i--) {
reverseWord += word[i];
}
return reverseWord;
}
I'm sure you know this one of the way of reversing string in javascript, my question is:
Why do we need to declare a new variable within the function, when should we declare it?
Why can't I just type console.log(word[i]);?
What does it mean by wordLength+=word[i];?
Why should we return the new variable(wordLength), instead of the function(reverse) after the loop?
Why do we need to declare a new variable within the function...
Because you need a place to store the reversed word as you build it. (Note: wordLength isn't a good name for that variable. It doesn't contain the word's length. It contains the characters of the reversed word.)
...when should we declare it?
Any time before you first need it.
Why can't I just type console.log(word[i]);?
Because the goal of the exercise is to build a string containing the reversed word, not just to output it. (And because console.log writes a new line each time you call it.)
What does it mean by wordLength+=word[i];?
That adds the character in word[i] to the end of wordLength. For instance, if the word is "start", wordLength starts out with "", then gets "t" added to it to make it "t", then gets "r" added to it to make "tr", and so on.
(+= is a shorthand way to write wordLength = wordLength + word[i];. There are several of these compound assignment operators, most of them for math: -=, *=, etc.)
Side note: The Array.from call in your code isn't doing anything useful. It's creating an array, but then throwing that array away because nothing uses the return value. The rest of the code is using the string you receive in word.
Why do we need to declare a new variable within the function, when should we declare it?
Vars is a place to store data. If your algorithm requires keeping some data to use it later you need vars. Also well named variables is a good way to create easy-to-understand code
Why can't I just type console.log(word[i]);?
You can, but it will do nothing useful. Your goal is to build a string and return it. Usage of your function will be something like
const word = getSomeText()
const reversedText = reverse(word)
doSomeStuff(reversedText) // whatever, send it online, or render it on screen some fancy way, not in the console.
So you need to return actual string, not to solve a puzzle and show the answer whatever way you like
Why should we return the new variable(wordLength), instead of the function(reverse) after the loop?
Because it contains reversed word and you function supposed to return it. there is rare complicated occasions when a function returning itself is useful, but it has nothing in common with your task
Why do we need to declare a new variable within the function, when should we declare it?
Variable is required to store the data value that can be changed later on. In your case wordLength variable is required to store the reverse string.
It's best to declare variables when you first use them to ensure that they are always initialized to some valid value.
Why can't I just type console.log(word[i])
console.log() is used just to print the output but will not use if you want to return something and as per your statement it will just print the word[i] not a whole reverse string.
What does it mean by wordLength+=word[i]
It means you are concatenating the each iteration word[i] into a wordLength variable.
wordLength+=word[i] is a shorthand for wordLength = wordLength + word[i]. If the left hand side of the + operator is a string, JavaScript will coerce the right hand side to a string.
Why should we return the new variable(wordLength), instead of the function(reverse) after the loop ?
Because this is what you expected from the function. It returns the reversed string and function should return it.

Simple question, new student doing practice coursework. (JavaScript)

In the previous lesson, I'm working with let, const, var as well as some comparison operators. Now I get the not equal to, but how would I write out the greater than for the question below?
Thank you!
/ In this exercise, you will be given a variable, it will be called: value
// On the next line create a variable called 'greaterThan' and using a comparison operator, check to see if value is greater than 5.
// Assign the results of that to 'greaterThan'
// Please write your answer in the line above.
return greaterThan;
}
const greaterThan = value > 5;

creating variable names from parameters in javascript

I was wondering if it is possible to create variable names from parameters passed to a function in javascript. Something like this:
function createVar(number) {
var "number" + number;
}
createVar(1)
I'm new to Stack Overflow and programming, so any help would be appreciated.
You could attach this to the window object, but note it will be global. For example:
function createVar(varName, value) {
window[varName] = value;
}
createVar("test", "Hello World");
alert(test); // Outputs "Hello World".
It is possible to interpret Object as associative array where you specify index and get value by name of index ( hash ):
var x = Array();
x[number] = value;
Single variable name is for programmer, and the code would be hard to maintain and understand when you set variable dynamically in code.
Honestly, I don't see why this would ever be useful, because every time you want to use the variable you'd have to search for it with your number argument.
However, you can do it, albeit not the exact way you had described:
function createVar(number){
eval("var number" + number.toString() + ";");
}
however, this variable will only be accessible within the function, to make it global assign to the window object:
function createVar(number){
window["number" + number] = 15; // creates "global" variable
}
As I've stated before, however, I don't see this being useful, [i]ever[/i], if you want to stratify values by numbers you'd be much better off with an array.

Javascript: Why do some variables go in ( ) and some go before keywords?

One thing I don't understand is why sometimes you put variables inside of ( ) and sometimes you put them before a keyword with a period. Is there a rule on this? Does it have a name? How do I know and how do I remember? This is causing some confusion for me. Example below:
var myNumber1 = 1234;
var myNumber2 = myNumber.toString(); //variable is before keyword with a period
var myNumber1 = "1234";
var myNumber2 = Number(myNumber); //variable is after keyword and inside of parenthesis
Those are two different synatxes.
The first one calls a method of myNumber - a function (toString()) that is run on the object.
The second one calls a function (Number) with myNumber as a parameter - that goes in the parentheses.
To learn more about function and method calls, i recommend reading some tutorials. ;) Here's one by MDN. It's somewhat advanced, but pretty good.
Case 1
Number(myNumber);
In short this is just a function, and you are passing in a variable. from the way you asked your question it seems like you understand how this works.
Case 2
myNumber.toString();
In case 2 you are not actually passing in a variable, you are calling a method of that object.
Dot notation is one of the two ways you can call methods.
[ object ] . [method of that object]
In javascript almost everything is an object, because of this (like it or not) you inherit the methods of Number.prototype in all your numbers.
You can think of .toString() as a method of all number "objects".
If you are interested in learning more about this or how to add more methods your self give THIS a read.
myNumber.toString();
converts myNumber to a "string of characters". Like "abcd". Is not a number.
As every string is between "",
"1234" is a string, not a number.
So
var myNumber2 = Number(myNumber);
converts that string to the number 1234 . "Number" is a function to convert that what you passed trought parenthesis into a number.

Why is my jQuery each loop not adding values correctly?

I am trying to get the values of several fields & add them together & in my testing I am having problems. I have this code:
var count;
function calculate() {
// Fix jQuery conflicts
jQuery.noConflict();
count = 0;
jQuery('.calculate').each(function() {
var currentElement = jQuery(this);
var value = currentElement.val();
var count = count + value;
alert(count);
});
}
I enter in the value of "9" in my first field & when the first alert triggers I get "undefined9"; all the other values are currently set to "0"; when it triggers again I always get "undefined0".
Why am I getting the "undefined" bit & why is it only returning the value of the current field & not adding them together?
You are dimensioning the count value inside the loop, essentially setting it to undefined first in each iteration.
You want to remove the var within the loop. This way, it doesn't have scope to the anonymous function and JavaScript will look at the parent function for its declaration.
It may also be a good idea to parseInt(count, 10) the number first, because JavaScript overloads the + operator to mean arithmetic addition and string concatenation, and you wouldn't want count to be "0something".
Finally, count += value is easier to read :)
You're accidentally re-declaring count:
var count = count + value;
should be:
count = count + value;
The count declared in the inner-most scope (that of calculate) will hide the other one (this is called "shadowing" of variables).
The reason you get "undefined9" is because the default value of the newly-declared count variable is undefined; when you add to it, it sees an undefined value on the left, and a number on the right, and decides that string concatenation is the best way to perform the addition, resulting in the string "undefined9".
It has to guess at your intended meaning since + is overloaded to mean both numerical addition and string concatenation; in this case, it guesses wrong.
You're defining count in two different scopes - the calculate function, and then in the function that each is using. You may want to have the second count be named something else, or at least don't redeclare it.

Categories