Simple question, new student doing practice coursework. (JavaScript) - 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;

Related

Can't figure out the answers to this Control Overflow test

I know that this is a very simple Javascript code so I appreciate your patience. Usually I am good with HTML/CSS but Javascript coding is new to me. I am trying to pass an online placement test for school and am having problems with what I know is a very simple test for anyone that knows Javascript. I can not for the life of me figure out the correct comparison operators for the following questions. I think I got #3 correct but the rest of them confuse me. I know the answers are right in front of me but I can't figure it out. I would appreciate any help with this. Thank you
function exerciseOne(value){
// 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'
greaterThan = value !=='5';
// Please write your answer in the line above.
return greaterThan;
}
function exerciseTwo(value){
// In this exercise, you will be given a variable, it will be called: value
// On the next line create a variable called 'lessThan' and using a comparison operator, check to see if value is less than 20.
// Assign the results of that to 'lessThan'
lessThan = value !=='20'
// Please write your answer in the line above.
return lessThan;
}
function exerciseThree(value){
// In this exercise, you will be given a variable, it will be called: value
// On the next line create a variable called 'equalTo' and using a comparison operator, check to see if value is equal to 37.
// Assign the results of that to 'equalTo'
equalTo = value !=='37'
// Please write your answer in the line above.
return equalTo;
}
function exerciseFour(value){
let greaterThanFive = false;
// In this exercise, you will be given a variable, it will be called: value
// You will also be given a variable named: greaterThanFive
// Using an 'if' statement check to see if the value is greater than 5. If it is, re-assign greaterThanFive the boolean true.
If = value !='5'
// Please write your answer in the line above.
return greaterThanFive;
}
function exerciseFive(name){
let isSondra = false;
// In this exercise, you will be given a variable, it will be called: name
// You will also be given a variable named: isSondra
// Using an 'if' statement check to see if the name is equal to the string 'Sondra'. If it is, re-assign isSondra the boolean true.
// Please write your answer in the line above.
return isSondra;**
Welcome to programming. First of all I think you would be able to answer these questions after taking a look at some online javascript documentation. https://developer.mozilla.org/ is a good place to start. You want to look at 'operators' and 'control flow' by the looks of it.
in terms of your question, Q3 is almost right but you'll want to see if it is equal not if it is not equal. equalTo = value == 37
for the others you'll just need to know less than and more than < > etc. but take a look on the Mozilla page and you'll work it out in no time.
Best of luck
I suggest you study the following pages thoroughly so you may understand how comparison operators an if conditional statements are structured and work..
If... else conditional: Mozilla on if... else conditional statements
Operators: W3schools operators
// I have done the hardest one for you to illustrate how the operator and
// if conditional statement works, I think you can figure the rest out
// with the links I and others have provided.
function exerciseFour(value){
let greaterThanFive = false;
// In this exercise, you will be given a variable, it will be called: value
// You will also be given a variable named: greaterThanFive
// Using an 'if' statement check to see if the value is greater than 5. If it is, re-assign greaterThanFive the boolean true.
/* wrap the comparison operator in parenthesis if our value is greater
than 5 which is a basic algebretic style comparison */
if(value > 5)
{
/* code block wrapped in curly brackets "{ }" to run if the statement in the
parenthesis is true. The curly brackets are not required but is considered
it is a good practice to always use block statements */
greaterThanFive = true;
}
// Please write your answer in the line above.
return greaterThanFive;
}
/* variables to use within the console for display purposes only
to illustrate this, simply change the value of the variable v to another number
and run the snippit again to see the difference of the comparison of teh two values*/
let v = 10;
let n = 5;
/* Here we are running the function exerciseFour() and passing the value of 10
into the value variable within the function, so value will actually represent
the number 10 with in the function. We are loging the function in the console.
The expected output will be true as 10 is greater than 5. */
console.log(`Is ${v} greater than ${n}? ${exerciseFour(v)}`)

Difference between p++ and ++p when using that in a for loop Javascript

This could be a very naive dumb question, but what is the difference in the output of the following 2 condition:
for (var p=0; p<3; p++) {console.log(p)}
//outputs:
0
1
2
for (var p=0; p<3; ++p) {console.log(p)}
//outputs:
0
1
2
'p' result into same output regardless whether I increment the value first and then print it or vice vera. also I do understand the diff between (p++) and (++p), but in this case I'm unable to understand whether at this point in looping will it make it any difference if I were I do either of 2 or if it does make difference how would that impact my program.
Can someone please explain.
Thank
If you dont use the values, after using pre- and post-fix, there is absolutely no difference at all. (exept from performance)
Doing something like this would behave differently, as you can see:
var a = 0;
var b = 0;
var arr = [0,1,2];
console.log(arr[++b]);
console.log(arr[b++]);
console.log(arr[b]);
In this case there is no difference whatsoever as you are not using the value of the expression.
Since you're not assigning the expression to anything, there's no difference apart from a slight performance gain in the pre-incrementer (because a temporary variable is created in order to store the multiple values of p with the post-incrementer). JSBEN.CH.
Just so you know the difference between them:
let var1 = 3;
let var2 = 4;
console.log(var1++); //Outputs the value of var1, then increments it
console.log(++var2); //Increments the value of var2, then outputs it
The += syntax is actually better in this case, because it is easier to read, and it is just a compaction of p = p + 1 - literally no difference, performance-wise or otherwise. This means it's actually faster.
If you put the two plus in front or after the variable/number only makes a different for evaluating it.
Because it is only inportant that the counter is incremented after leaving the block. If this is done before or after doesnt matter. At the end of the call the number is incremented equally.
++p first it will count +1 and then return the result
p++ it will return the value and then add +1
p value will be different at the end of each turn in those 2 cases.
In your example there is no difference.
However if you use the increment ++ or decrement -- operators inside a function the positioning is significant. To quote the article
JavaScript Increment ++ and Decrement --
If the operand is after the variable console.log displays a then it is incremented
let a = 1;
console.log(a++); // 1
console.log(a); // 2
If the operand is before the variable a it is incremented then console.log displays it
let a = 1;
console.log(++a); // 2
console.log(a); // 2
Several other languages such as C and C++ have the same behaviour.
However these operators need to be used with care. See the following stackoverflow answer (albeit it refers to JavaScript, but also applies to C etc)
Why avoid increment (“++”) and decrement (“--”) operators in JavaScript?
In this case there is no difference in pre and post increment.
However in some cases like this can be significant:
here n and i are first evaluated and then incremented
var n=0
var i
for(i=0;n<5;n=i++){}
after the loop n and i look like this: n=5, i=6
here n and i are evaluated first, but i is incremented before entering the cycle
var n=0
var i
for(i=0;n<5;n=++i){}
after the loop n and i look like this: n=5, i=5

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

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;
}

Javascript: Why doesn't (p+1)++ work?

Regarding
p = 0;
(p+1)++;
> ReferenceError: Invalid left-hand side expression in postfix operation
and
p = 0;
++(p+4);
> ReferenceError: Invalid left-hand side expression in prefix operation
I just got a bit of a surprise, as I expected postfix/prefix operators to be ok with working on the resolution of the expression (brackets have the highest operator precedence).
Could someone give me with a line or three to explain what is happening here?
Thanks
EDIT: Thanks for the quick responses, first answer marked as the answer. I feel I should also point people to the indepth answer from #thefourtheye below
++ increments the value of a variable, so it is larger than before. Eg:
var x = 3;
x++;
alert(x); // will show 4
For there to be any point for this, the expression to the left of ++ must be accessible and mutable, otherwise the increment would be possible. Eg:
3++
doesn't make any sense, as 3 is a constant and can't be incremented. We don't want this to be possible:
3++;
alert(3); // outputs 4???
This is why your expression doesn't work. Ie:
var p = 2;
(p + 1)++;
has the same problem as above. (p + 1) will evaluate to 3, and ++ can't change the value of the constant 3.
You are trying to increment (), the increment/decrement operator can be apply on variable, try the sample code
(p++) + 1
OR
(++p) + 1
Remember that when you write p++, that actually gets translated to p = p + 1. The operators ++ and -- are convenience notation for incrementing/decrementing a variable for future use. But how is (p+1)++ or ++(p+4) supposed to be translated? Those sort of imply that 1 or 4 are being incremented/decremented for future use, which doesn't make sense.
When you have an expression like this
(expr)++;
These are the operations JavaScript will do internally
Resolve the actual object referenced by expr.
This step is important, because you can even do something like this
var a = {b: 1};
++a.b;
a.b++;
console.log(a.b);
# 3
Now, JavaScript has to resolve the actual object to be incremented. In this case, it will be b in a.
Get the value at the reference and convert that value to a Number.
This step is also very important, because you may even have values like this
var a = {b: '1'};
console.log(++a.b);
# 2
JavaScript will try its best to get a number value, instead of failing immediately.
Increment the number.
Store the new vale in expr. This is step where your expression is failing.
In your case expr is p + 1, when it is resolved the value would be just a numeral, whose value can never be changed. (You can never change the value of 1 to something else). So, after the incrementing part, when the new value has to be stored back, JavaScript doesn't find a valid reference to store it. That is why it throws this error.
ReferenceError: Invalid left-hand side expression in postfix operation
This error message is actually thrown from internal PutValue method. The very first step goes like this
If Type(V) is not Reference, throw a ReferenceError exception.
Reference: ECMA Script 5.1 Standard Specification for Prefix Increment Operator

Javascript: var = var = function

I'm sure this thing is duplicated somewhere but I don't know what to search.
So, I've been looking through a Node.JS Application and found this code and wondered what it does. I have tried searching but I don't know what to search so I was hoping someone would it explain it to me.
init = refresh = function () {
// code here..
};
I understand 1 equals, but why 2? does it make some sort of alias so that function can be run with both init and refresh?
= resolves the right hand side and then assigns the result to the left hand side.
The result of doing this is the same as the result assigned.
So that assigns the function to both init and refresh
Quentin did a very good job telling you what it is doing.
I just wanted to chime in to give an example where you might use this:
Say for instance you have an object:
var obj = {
init: function() {
var x = this.x = [1,2,3];
}
};
What this allows you to do is reference your x variable two different ways (either through x or this.x).
Now why would you do this?
Well two major reasons.
It is faster to access x rather than this.x (but you still need to access it elsewhere)
It produces easier to read code when having to read/write to x lots of times in one function.
This is just another reason why you would use it.
But in most cases it is just aliases, such as: forEach -> each
Here's an explanation using operator associativity and precedence.
So, looking at an operator precedence description from Mozilla, when an expression includes multiple operators of the same precedence, as in
a OP b OP c
, then you check whether that level of precedence uses right-to-left or left-to-right associativity.
a = b = c
The assignment operator in JavaScript is the only operator on its level of precedence.
It has right-to-left associativity
So in a = b = c, b = c is evaluated first, assigning the value of c to b.
Then the expression becomes a = b.

Categories