Javascript: Delete operator - javascript

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.

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)}`)

Can someone please explain in plain english what is going on in a particular part of my code for objects?

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

Setting Variable Assignments with property display

I'm still a novice when it comes to JavaScript and was trying to make my code more cleaner and was wondering why the top scenario works but the bottom doesn't? Am I missing something?
var partner = document.getElementById('partner');
var providedBy = document.getElementById('providedBy');
partner.style.display = "none";
providedBy.style.display = "none";
But this does not?
var partner = document.getElementById('partner');
var providedBy = document.getElementById('providedBy');
collection = partner + providedBy;
collection.style.display = "none";
In the console it gives me error saying Cannot set Property 'display' of undefined. Am I supposed to define it somewhere first? I console logged the new variable and it returned both div elements.
collection is of type string as the + operator automatically call for both their toString() function.
Now what you are trying is to access a property of collection.style which does not exist because you are operating on a string. That's the reason for the error message you are getting.
You could do something like:
var collection = [];
collection.push(document.getElementById('partner'));
collection.push(document.getElementById('providedBy'));
collection.forEach(function(element) {
element.style.display = 'none';
}
which would be something I think you are trying to archive.
just to complement the accepted answer, I think you should understand why you get this error.
For what i understand from your code, you are trying to set the css of both variables partner and providedBy to display : none.
Your first piece of code works because you do this separately, while in your second code you try to add with the (+) operator both nodes, which evaluates to the string "[object HTMLDivElement][object HTMLInputElement]".
Then you try to call .style on that string which evaluates to undefined, and then you try to call display on that undefined value, this is where you get the error.
You could leave your code just like that since there are not too many variables, but if you wanted to do something that worked on multiple variables you could
create an array
push your objects into the array
create a function that loops over the elements of the array and set their style.display = "none" to individually.
In JavaScript you have to declare all of your variables. Secondly, you can't point to two objects at once by using the + operator. JavaScript interprets this as trying to concatenate the two objects, which it can't do in this way. It will return the string [object Object][object Object]
In order to affect two Objects at the same time you would need to create a function or use an existing method.

How does this "if" without operators work?

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.

Javascript function programming — receiving elaborate parameters

I'm writing a Javascript function that would manipulate an array written on-the-fly and sent as a parameter.
The function is written as follows:
function returnJourney(animation,clean){
var properties = {};
// loads of other inane stuff
for(i in animation[0]) properties[animation[0][i]] = animation[0].i;
// heaps more inane stuff
}
The animation in question is a set of parameters for a jQuery animation. Typically it takes the format of ({key:value,key:value},speedAsInteger,modifierAsString).
So to kick off initial debugging I call it with:
returnJouney(({'foo':'bar'},3000),1);
And straight off the bat things are way off. As far as I see it this would have returnJourney acknowledge clean === 1, and animation being an array with an object as its first child and the number 3000 as its second.
Firebug tells me animation evaluates as the number 3000. What am I doing wrong?
properties[animation[0][i]] = animation[0].i;
should be
properties[animation[0][i]] = animation[0][i];
.i is the property literally called 'i'. As that (probably) doesn't exist, you'll be assigning undefined to each property.
returnJouney(({'foo':'bar'},3000),1);
also makes little sense — do you mean an array?:
returnJourney([{'foo':'bar'},3000],1);
(there is no ‘tuple’ type in JavaScript.)
Also, use var i in rather than the (typo) in in. Forgetting var gives you an accidental global, with potentially annoying-to-debug side-effects.
There's no tuple type in JavaScript. All you have is either object {} or array []. Both of them can understand any mixture of types. So you can either pass your animation parameter as array ([{'foo':'bar'},3000]), which looks like exactly what you wanted.
Or, as it usually done in JavaScript, use object instead:
returnJourney({props: {foo: "bar"}, speed: 3000}, 1);
function returnJourney(animation, clean) {
var props = animation.props;
var speed = animation.speed;
}
Note that object notation let you ignore things you don't want to pass and makes it very clear what value means what.
As for why your animation resolves as 3000, it is really simple, this is how , operator works. It returns the last thing in braces. So (10, 20, 30) would evaluate to 30, so will (f(1000), "hello", 30). Only last value matters, others just ignored (but run anyway, so any side effects will be there).
It's treating ({'foo':'bar'},3000) as an expression using the comma operator, which returns the right operand as its result. Perhaps you meant [{'foo':'bar'},3000].

Categories