Reputation: 3253
I may be asking a basic question but I don't know how to clear such a confusion through google search
this below code works fine and count words, so I was trying to understand further
var words = chunk.trim().split(' ');
var counts = {};
// Count words
words.forEach(function (word) {
word = word.trim();
if (word.length) {
if (!counts[word]) {
counts[word] = 0;
}
counts[word]++;
}
});
then why not this below gives me 1,2
. I am expecting 1,2
and its giving me 2,2
var a = function(){
var a, b;
var obj = {}
obj[a]=1;
obj[b]=2;
console.log(obj[a]);
console.log(obj[b]);
}
var res = a();
Upvotes: 2
Views: 110
Reputation: 8632
Because you're only declaring (not assigning) both a and b, and in javascript a not assigned variable is implicitely undefined
.
you're essentially referring to obj[undefined]
twice
var a,b; //here both the variables are undefined
obj[a]=1;
obj[b]=2; //you're overriding the variable
console.log(obj[a]); //2
console.log(obj[b]); //2
Upvotes: 6
Reputation: 16787
Why doesn't this give me
1,2
? I am expecting1,2
and it's giving me2,2
This is happening because a == b
; they are both undefined
because you never assigned them values on the line var a, b
. When you omit the =
assignment in var
declarations, the default value of undefined
is used instead, meaning that your line becomes var a = undefined, b = undefined
.
Thus, the second property assignment (obj[b] = 2
) is actually overwriting the first (obj[a] = 1
). Your obj
only contains a single key, and after running your code its overall structure looks like:
{
'undefined': 2
}
var a = function () {
var a, b
var obj = {}
obj[a] = 1
obj[b] = 2
console.log(obj)
}
var res = a()
If you want the results you expected, you need to use distinct keys, like the strings 'a'
and 'b'
:
var a = function() {
var a = 'a', b = 'b'
var obj = {}
obj[a] = 1
obj[b] = 2
console.log(obj)
console.log(obj[a], obj[b])
}
var res = a()
Upvotes: 1
Reputation: 2672
When you say obj[a], javascript tries to create a property on obj with the value in a. Since value in a is undefined, the string representation is "undefined" and hence a property undefined is created on obj. Since b also happens to have undefined value, you are essentially writing 2 onto the same property undefined.
Hence you get 2 both the times. Actually if you log obj and see the value in console, you would see:
Object {undefined: 2}
undefined:2
Upvotes: 1