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)}`)
Related
I am new learning the fundamentals. I have looked at many questions on here and youtube, and even on my udemy lecture. But none answer my question.
To be clear, my question is NOT how to use the return operator. I can use it perfectly well. The question is more to do with HOW it works, and what is actually happening in detail.
And please don't say "So in short, when we return something from a function, we are actually returning it from a function." - because this was one of the explainations I got before, and it does not explain anything to me hahaha :)
Here is the example code for this question:
function example(digit1, digit2) {
const sum = digit1 + digit2;
return `${sum}`
}
const invoke = example(1, 2);
console.log(invoke);
I think the best way to answer this question is to give me a step by step list of the journey that 'sum' makes. From the moment it is written, to the end of the whole code.
The return operator is clearly moving 'sum', as the word 'return' can only mean this, by definition.
When I read this code I see that 'sum' is inside the curly braces off the function, and then directly after this 'sum' is then RETURNED (to the place which it started). Now as 'sum' has not gone anywhere, returning it (to the place which it started) is REDUNDANT.
when the function is invoked there must be some kind of journey happening which I do not understand.
Thank you for your time :)
When I read this code I see that 'sum' is inside the curly braces off the function, and then directly after this 'sum' is then RETURNED (to the place which it started). Now as 'sum' has not gone anywhere, returning it (to the place which it started) is REDUNDANT.
Nope. You're misinterpreting what's "returning" and where it's being returned to.
The function is returning the value contained in sum to whatever called the function, not to "the place where it (sum) started".
function example(digit1, digit2) {
const sum = digit1 + digit2;
return `${sum}`
}
const invoke = example(1, 2);
console.log(invoke);
The function example receives two values which it places in the variables digit1 and digit2, then creates a new variable sum which contains the result of adding digit1 and digit2. (The variables digit1, digit2, and sum are all scoped to the function itself; they do not exist outside of that function.) It then returns the value contained in sum -- not the variable itself -- to the thing that called the function.
Which in this case, is this line:
const invoke = example(1, 2)
The function example receives the values 1 and 2, and returns the value "3". Which means that outside the function, the returned value takes the place of the function call itself, resulting in, effectively,
const invoke = "3"
The code outside the function "calls" the function. The function "returns" a value -- not a variable, a value! -- to the code outside the function. You can think of a function as a box with inputs and an output: you call it with inputs, and it returns to you an output value.
(Incidentally, the return statement you've used unnecessarily coerces the result into a string, where you probably want a number: just return sum would likely be preferable.)
return will put whats being returned (sum in this case) at the place where the function is invoked (in this case, in front of invoke).
so invoke = sum (sum is returned/ put on the place where the function is invoked)
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;
although it is a very simple code, I would like to get a full understanding of what is happening in my condition:
let getFreqOn = function(string){
//set a variable for object
let object = {}
for (let key = 0; key < string.length; key++){
// if (object.hasOwnProperty(string[key])) {
// if (object[string[key]]) {
// if (object[string[key]] !== undefined) {
if (string[key] in object) {
object[string[key]]++
}
else{
object[string[key]] = 1
}
}
return object
}
My main concern would be the first condition, I understand what it is they do but I cant put in to plain English how it is working. For example if (string[key] in object) is basically telling my that if a specific property is in the empty object I defined, then I will set then it will be set as the property and incremented. But what I'm trying to wrap my head around is that the object is empty, so how can the property be in the object?
Hoping someone can enlighten me on the conditions that I commented out as well. Sorry for the noob question.
First, the in operator returns a boolean result. It checks whether the string on the left is present as a property name in the object on the right.
Thus
if (string[key] in object)
asks whether that single character of the string is in use as a property name in the object. As you observed, the very first time through the loop that cannot possibly be true, because the object starts off empty.
Thus the if test is false, so the else part runs. There, the code still refers to object[string[key]], but it's a simple assignment. An assignment to an object property works whether or not the property name is already there; when it isn't, a new object property is implicitly created.
The key difference is right there in the two different statements from the two parts of the if - else:
object[string[key]]++; // only works when property exists
object[string[key]] = 1; // works always
I am looking at the Mozilla Developers website on the concept of the delete operator. In the last sub section of the page referring to “Deleting array elements” two similar scripts are shown, but the only difference in the scripts is how they modified the array.
In the first script, I quite don’t understand why “if” statement does not run. My current understanding is that delete operator “removes the element of the array”. If I were to type trees[3] in the console, it would return undefined in the console.
var trees = ["redwood","bay","cedar","oak","maple"];
delete trees[3];
if (3 in trees) {
// this does not get executed
}
The second script seems to "mimic" the delete, but not literally. Undefined is assigned to trees[3]. It doesn’t make sense to me how the “if” block runs in this script, but the first example does not. Can anyone help me understand this JavaScript behavior?
var trees = ["redwood","bay","cedar","oak","maple"];
trees[3] = undefined;
if (3 in trees) {
// this gets executed
}
There is a huge difference between the two methods you are trying:
Method 1:
You are deleting, destroying, completely removing the key 3 in your array called tree, hence there is no 3 in tree left, and the if check returns false.
Method 2:
You are assigning a new value to the key 3, which is undefined, there is still 3 in tree, and the if check returns true.
In your second example the key 3 still exists. It just holds a value that happens to be undefined. It IS confusing, but that's just the way Javascript is.
The in operator just checks if the key exists, not if the value is defined.
If you were to output the whole arrays after each of your "deletions" the first example would display something like this:
["redwood", "bay", "cedar", 4: "maple"]
Whilst the second example would print out something like this:
["redwood", "bay", "cedar", undefined, "maple"]
So as you can see, in your first example the key is completely missing and it continues with the next key which is 4. In the second example the key still exists, but it's value is set to undefined.
There is a difference between undefined which is set by the user and undefined which the javascript engine returns once something is actually undefined, meaning doesn't exist.
javascript can tell the difference between the two.
So in your example, when you do this:
var trees = ["redwood","bay","cedar","oak","maple"];
trees[3] = undefined;
if (3 in trees) {
console.log("hi");
}
javascript can tell that property 3 exists, but it was set to undefined by the user.
to prove so you have the following:
if (5 in trees) {
console.log("hi");
}
the property 5 of the array was never created, javascript knows it's undefined
by lack of creation and regards it as a property which doesn't exist, and therefore doesn't display the "hi"
if(3 in tree) {
//Stuff that won't get executed
}
is in fact correct, the thing is that in operator in Javascript does not work like in python, it simply checks if an object has a proprety. An array in javascript has a proprety 0, just like a string has a proprety 2 with the value someString[2].
the difference between delete object[prop]; and object[prop] = undefined; can be seen through object.hasOwnProperty(prop); or iterating through values or props of the object.
I am relatively new to Javascript and am working through ch. 5 of Eloquent Javascript. I came across some code that I don't quite understand. I know HOW it works (the general method and steps), but I don't understand WHY it works.
The code is here:
function filter(array, test) {
var passed = [];
for (var i = 0; i < array.length; i++) {
if (test(array[i]))
passed.push(array[i]);
}
return passed;
}
Basically the function takes the element the 'for loop is iterating over' from the array, and compares it to the test parameter.
I am wondering how/why this works:
if (test(array[i]))
There is no || && or other 'comparison operators'. How does it compare values with only using parenthesis?
How is test compared to the array[i] value with no operators?
Link to file: http://eloquentjavascript.net/05_higher_order.html
go to 'Filtering an Array' exercise
Thanks!
Whatever is inside the parentheses of an if statement will be evaluated. If the result is falsy (false, 0, "", NaN, null, undefined) it fails and if the result is truthy (everything else) it passes. So if your if statement contains a function call if (test(something)) {}, then the if statement just says if the result of the function call is truthy then pass.
Also, && and || are not comparison operators, they are boolean operators. They just connect the result of two statements, like true || false which evaluates to true.
I am not quite sure, but I think this is a custom function. Most likely there is some comparison there and the result of the function is True/False. If you give us the whole code we could explain it better to you.
This code is accepting a test parameter that is what is called a "predicate function" i.e. a function that given an element will return true or false.
It's going to be used for example with
var big_numbers = filter(numbers, function(x){ return x > 100; });
i.e. the expected parameter test is actually code.
In Javascript passing code is very common and idiomatic. It's something that is more annoying in other languages that don't support the concept of "closure" and of "nested function", forcing all code to live at the top level, being given a name and to have no context (e.g. the C language).
'test' here is a function, not a value. In Javascript, each function is an object and can be passed as parameter. In this case, test is a function that take one parameter and return true or false base on the parameter value.
So in the for loop, test function is called with each array element and if the result is true, it will be store in another array. Eventually, passed elements would be return to the function caller.