Properties of an empty array - javascript

I am a novice in nodejs and javascript .I am learning nodejs. I have a doubt here . I came across a node js code , which I was unable to understand :
jumble = {} ;
jumble.debug = false;
jumble.start = function (guid, callback) {
}
I am still wondering , what does jumble.start do when its just an empty array, any help /links would be appreciated Please

There are no arrays here.
jumble = {} ; creates a object and assigns it to jumble
jumble.debug = false creates a property called debug on the object and assigns the value false to it.
jumble.start = function (guid, callback) {} creates a property called start on the object and assigns a function to it.
You could call that function with jumble.start(1,2), but it wouldn't do anything since the function doesn't have anything between { and }.

I don't know node.js but, I know it is similar to javascript.
So, first of all, jumble is an object and not an array, as you think it is.
debug is a property of jumble object which has been assigned the value of false.
start is a function of jumble object which is obviously empty as it does nothing when called by doing jumble.start(3,4).

Related

Javascript: why do functions treat array() and array[] differently?

In class, teacher couldn't explain why tweets(i) failed and tweets[i] works:
var tweets=["hi","who","when","where","bye"];
alert("start");
for (var i=0; i < tweets.length; i++) {
alert(tweets[i]);
}
alert("finish");
Brackets are used for functions, so array() would be a function called array. Square brackets are used for arrays, so array[] would be an array. array[0] is the first entry in an array, array(1) would send 1 as an argument to a function called array.
And stop going to classes where the teacher can't explain something this simple. They clearly aren't a programmer.
The reason tweets(i) fails in this code snippet is because, when you say tweets(i), javascript looks at it and says "oh, the code wants me to go find a function named tweets and execute it with a parameter named i."
When javascript sees tweets[i], it says "oh, this isn't a function. The code wants me to find the number-i place in an array and give it back the value stored there.
In short, The reason tweets(i) doesn't work is because you're telling it to alert a function that you haven't defined.
The () is a method invocation operator and the [x] is an member access operator. As array is not a function (e.g. typeof array !== 'function'), so you can only use member access operator on the array.
Note:
I don't know the specification name of the above operators, will need expert explanation on them.
A function is an object so you can use both operators on it
e.g.
var func = function() { return 'hello'; };
func.world = 'earth'
console.log(func());
console.log(func['world'])
console.log(func.world)

How does the Javascript closure with function works?

Hi i have been exploring closures and javascript core concepts i couldn't understand why does the console.log(factory[i]) outputs undefined i have pushed my function inside there right? And if i call temp outside the loop it says undefined whereas if i call inside the loop it returns am bit confused can anyone explain me?Here is my code
var fruits=["apple","orange"];
var factory=[];
for(var i=0;i<fruits.length;i++)
{
var temp=function()
{
console.log(fruits[i]);
}
factory.push(temp());
}
temp();
console.log(factory);
for(var i=0;i<factory.length;i++)
{
temp(i);
console.log(factory[i]);
}
https://jsfiddle.net/kh3okLca/
You are not passing function but the result of the executed function temp() as it don't return anything its undefined. change factory.push(temp()); to factory.push(temp);
The temp() outside return undefined because by that time loop has executed and the value of i is 2 check this following piece of code which logs value of i.
var fruits=["apple","orange"];
var factory=[];
for(var i=0;i<fruits.length;i++)
{
var temp=function()
{
console.log(fruits[i],"console",i);
}
factory.push(temp);
}
temp();
console.log(factory,"factory");
for(var i=0;i<factory.length;i++)
{
temp(i); //i resets to 0 here in same scope
console.log(factory[i](i),"factoryi"); //this doesnt return anything so its undefined but statements are executed
}
Here is the output you have.
//next two executed due to factory.push(temp()) in first if loop
& there is a console.log there inside the function
apple
orange
//here i++ in first loop will be 3, but array have only two element, so it is undefined
undefined
// due to console.log(factory)
// temp function is actually returning undefined,
[undefined, undefined]
// due to temp(i) in second if block
apple
// but factory array is stil empty so factory[i] will be undefined
undefined
from temp orange
undefined
Closure are nothing but function with preserve data. Till now a function is treated as peace of code which takes input and produces some output ,for every function call this code remain same, but closure gives you opportunity to save some data with the function which can be changed so that for each function call it will react differently, keep that in mind everything will be easy .
Suppose you have a function that finds rate of interest , but this functions is used by three teams whose interest rates are different, So in general what we do we pass the team name with the principle amount , each and everytime we have to pass the team name , So by using closure we can three instance of a function for each team (team name as a preserve data ) and now only send the principle amount and get the interest calculated according to the team, I a moment i will add example also,

Add Javascript Method

Is there way to create a new global method where I can have variable.myMethod() and it return true or false? Basically, I want to check to see if the variable is undefined and instead of using typeof(variable) == 'undefined' or specifying a function, is it possible to do something like variable.isUndefined() and it would return true or false?
I'm going to go ahead and post this as an answer, so I can go into a bit more detail.
As I mentioned in my comment, you have to be extremely careful about the terms that you use here, as undeclared and undefined mean two very different things.
If a variable is "undeclared", it doesn't exist, thus you cannot attempt to call any methods that might exist on it if it were declared.
If a variable is "undefined", it exists, but it doesn't have a value assigned to it. When this is the case, you can attempt to call methods that may exist on it, however the chances are that they'll fail, since variable doesn't have any value.
Every type in JavaScript is a child of the Object type, therefore you add a method to them, like follows:
Object.prototype.myMethod = function() {
console.log("This is my method");
};
So, in theory, you could create a method to check to see if a value exists, and return a true/false value.
Similarly to what StackOverflow user Barmar pointed out, undefined and null are not children of the Object type, thus your method will not exist.
As other comments have stated, you're probably better of sticking with something like follows:
if (!myVariable) {
// myVariable doesn't have a value
}
I'd like to point out that most of my explanation was unnecessary, as user Barmar pointed out, there is no practical difference between undeclared and undefined.
If a variable is undeclared, it's "value" is essentially read as undefined, thus your method will not exist.
this is a paradox. you can never have a method inside an undefined object because and undefined object does not have anything at all. to make it clear imagine this object
var a = {};
a.b is undefined here, so trying to call a.b.isDefined() can not work because you dont even have b. to make it work you need b defined like this
var a = {b:1,isUndefined:function(){return false}}
so you have to make a generic function that takes objects. This will do the trick
function isUndefined(obj,stringLink){
var arrayLink = stringLink.split(".");
var current = obj[arrayLink[0]];
if(!current)return false;
for(var i =1;i< arrayLink.length;i++){
current = current[arrayLink[i]];
if (!current)return false;
}
return true;
}
it will more or less check for nested object until it reach the target.
if you have
var a = {b:{c:{d:{e:{f:1}}}}}
//this function will do a["b"]["c"]["d"]["e"]["f"]
isUndefined(a,"a.b.c.d.e.f") //gives true
//or you can use
if(a&&a.b&&a.b.c&&a.b.c.d&&a.b.c.d.e&&a.b.c.d.e.f)//lots of work here

Why is `s.len` undefined (and not 4) while `s` has the value `test`? - JavaScript

I am puzzled with this one. I have the following code.
var s = "test";
s.len = 4;
var t = s.len;
The question is why the variable t has a value of undefined.
If you check the s.len after that code it is undefined.
If you check s the value is test. Not sure what is going on here. I am sure there is an explanation, but can't get my head around that and don't know how to search that.
For those who consider to vote down. This is a question we got in a course, and we are expected to prepare for the next session with this riddle.
I am not new to programming, but I fail to research how JavaScripts treats this code. It is valid code really, execute it in your Dev Tools and you will see.
I define a property for the string s called len assign to it the value 4. This property is, I believe created, but undefined. I would like to now why is it ? Is it specific to strings in JavaScript ?
but I fail to research how JavaScripts treats this code.
That is easy: strings are primitive types in JS, which means they don't have properties by themselves.
For . operator to work with them (e.g. for .length call) javascript defines such a thing called "wrapper objects".
So when you try to access a property of a primitive object - a temporary wrapper object is created that does behave as an object, hence you can access and assign properties to it.
The problem is that the wrapper object is temporary, so after it's used to access a property the object is discarded with all its state.
That's why when you assign a .len property you cannot access it on the next line: it's lost.
So a pseudo code for what actually happens behind the scenes for your code is
var s = "test";
(new String(s)).len = 4; // here you add an attribute for a new object
// and `s` is left untouched
var t = s.len;
The question is why the variable t has a value of undefined.
Because you have defined s as a string not as an object. so s.len should be undefined!
I am not sure what are you trying to do. But if you want to get the length of s then t = s.length will simply work.
I define a property for the string s called len assign to it the value 4. This property is, I believe created, but undefined. I would like to now why is it ? Is it specific to strings in JavaScript ?
You can find the answer from this question
run :
var s1 = "test";
console.log(typeof s1)//string
var s2 = {}
console.log(typeof s2)//object
s1.len = 4;
s2.len = 4;
console.log(s1.len);//undefine
console.log(s2.len);//4

Perform omit on the original object

I am very new to underscore js, I am trying to omit a certain property on an Object. What I did was
myObj = _.omit(myObj,name)
console.log(myObj);
Still the myObj seems to have the property name. Although if I do this it seemes to work
newMyObj= _.omit(myObj,name)
console.log (newMyObj)
it seemed to work fine. What am I doing wrong, can someone help? Ok, so myObj looks like this
Angola: "4.134137685",Brunei: "2.532726835",Countries: "2004",Croatia: "1.717672961", keys: Array[11]
I am trying to omit "keys" which again is an array of objects
Thanks
There are these things called "debuggers". If you don't know what they are, then stop everything you're doing and learn about them now. Search Google for "Chrome devtools", for instance. Stop your code (put a breakpoint) at the point before the call to _.omit. In the console, type in myObj to see exactly what it contains, then also name. Or, you could use the 'Scope Variables" section of devtools to check the value of these variables. Now, make a single step (F10). See if or how the variables have changed, or type myObj again into the console to check its value.
In your particular case, you report that the deletion of the property occurs properly when you do
newMyObj= _.omit(myObj,name)
but not with
myObj= _.omit(myObj,name)
In and of itself, that behavior is completely unexplainable. So there's something else going on that you're not telling us about. My guess is that you are doing something like this:
myObj = { keys: [] };
name = "keys";
delete_property();
console.log(myObj.keys); // []
function delete_property(myObj) {
myObj = _.omit (myObj, name);
}
However, this does not do what you might think. The assignment to myObj within the function does nothing; it just reassigns the value of the function argument. It has no effect on the myObj outside the function.
To be sure, we'd need to see more of your actual code, but this is just a regular old debugging problem of the sort you will encounter thousands of times in your programming career, so you're better off learning to solve it yourself.
I interpreted this question to mean you simply want to remove a property from an object using omit(). Note that omit() returns a copy of the object sans the specified property to remove. The method does not alter the object in place.
Given this premise, the code below, which matches what you have, works just fine:
var copy,
obj = {
Angola: "4.134137685",
Brunei: "2.532726835",
Countries: "2004",
Croatia: "1.717672961",
keys: Array[11]
},
check = function (o) {
_.each(o, function (value, key) {
console.log("key: " + key + " value: " + value);
});
};
copy = _.omit(obj, "keys");
check(copy);
obj = _.omit(obj, "keys");
check(obj);
You will get the same result whether you are using a new variable or the existing one.

Categories

Resources