Problem with Javascript object and accessing property which exists - javascript

I have something like this:
var test = {};
function blah() {
test[2] = 'filled';
}
blah(); // ! Hopefully confusion is now averted..
console.log(test);
//result test -> 2:"filled"
console.log(test[2]);
//result undefined
I don't understand why I'm getting 'undefined' in the second instance when according to the first instance, the property of that object clearly exists!
Does anyone have any ideas?
Thanks
OK, it seems that folk are getting confused as to what context the code exists in, for clarity sake I have now added the call to the blah(). but please refer to the comment under Jeff B's response!
Here is an example of relevant code so to say:
mydb = ..... //gets created here with relevant credentials
var test = {};
mydb.transaction(
function(transaction) {
transaction.executeSql("select * from mytable;", [], function(transaction,result) {
var r = result.rows.item(0);
test[2] = r.title;
}, errorHandler);
});
console.log(test);
//result test -> 2:"the title"
console.log(test[2]);
//result undefined
#Dancrumb
Your mention of the single-threadedness of Javascript gave me an idea, and I tried this:
window.setTimeout(function(){ alert(test[2]); },2000);
and it worked! I got the expected value to alert. Can you suggest how I can get around this without using a 'hack' like that above?

Because you aren't calling blah()?
Also, you want:
var test = [];
or:
var test = new Array();

EDIT
I ran the following code:
mydb = openDatabase('note','','Example',1024);
var test = {};
mydb.transaction(
function(transaction) {
transaction.executeSql("select * from mytable;", [], function(transaction,result) {
var r = result.rows.item(0);
test[2] = r.title;
}, errorHandler);
});
console.log(test);
console.log(test[2]);
in Safari 4.0.5
I got the following:
Object
No Properties
undefined
This is what I would expect to see. The object test does not have any properties assigned to it until the callback from mydb.transaction occurs and, since Javascript is single threaded, this cannot happen before the calls to console.log.
Since you're getting a different outcome, can you outline what browser and what version you are using?

This is pretty clearly an asynchronous issue. The simplest way of getting code to run after you set test[2], is to either put the code right there, or use another callback, and call it after you set test[2].

Related

Test individual line in javascript unit testing

I have a javascript function like this
function formatInput(input) {
//want to test only this immediate statement
var type = input.ipType.toString().toLowerCase().trim();
var afterVormat = someFunction(type);
return afterFormat;
}
I am able to test this function(value of afterFormat) correctly , but is it possible/how to test a specific line in function since I am not returning type.
For example I want to test if var type is as it is expected
Is it possible/how to test a specific line in function?
The immediate answer: no.
The solution
One of the outcomes of adhering to TDD is that it forces you to build code in isolated, testable blocks. This is a direct consequence of the fact that you cannot perform test(s) of the individual lines of a function. In your case the solution is to restructure your code to:
var type = function(){
return input.ipType.toString().toLowercase().trim();
};
function formatInput(input) {
var type2 = type();
var afterVormat = someFunction(type);
return afterFormat;
}
Now you have made type an isolated block that you can test.
If you combine this with use of Sinon.JS you can use a spy to test that an invocation of function formatInput() will also result in the invocation of type() and thereby you know for sure that var type2 has been assigned the intended value.
I’m not aware of any specific and more advanced unit testing method/system for javascript, but you can have a simple assertion function to test individual lines of code for debugging purpose like this:
function assert(condition, message) {
if (!condition) {
message = message || "Assertion failed";
if (typeof Error !== "undefined") {
throw new Error(message);
}
throw message; // Fallback
}
}
(Code taken from TJ Crowder's answer to another question.)
Then you can just use it to check for instance the var type like this:
assert(type == "something expected here and shall throw an error otherwise");
You can use console.log() function for that. As below.
function formatInput(input) {
var type = input.ipType.toString().toLowerCase().trim();
console.log(type);
var afterVormat = someFunction(type);
return afterFormat;
}
Also you can use debugger; also, to debug the code line by line.
function formatInput(input) {
var type = input.ipType.toString().toLowerCase().trim();
debugger;
var afterVormat = someFunction(type);
return afterFormat;
}
and just press F10 key to debug the code and you can check the values in console.

Javascript function undefined return

<script>
var tarih = tarih();
alert(tarih);
function tarih() {
var s=emrah;
return(s);
}
</script>
Bu fonksion neden undefined dönüyor ?
Why "undefined" returns?
The reason it returns undefined, is because of the assigment
var s = emrah
is confusing JS. So, it looks for a var name emrah and doesn't find it. That is the reason, you get undefined. Plus, if you are looking at your console, it would already have given you an error message, that
emrah is not defined
You might want to try: (If that's what you wanted)
var s = 'emrah'
You are calling the method before its defined.
Change the code to something like this.
<script>
function tarih() {
var s='emrah';
return(s);
}
var tarih = tarih();
alert(tarih);
</script>

Returning A Boolean Nested Inside A Plugin

I have a function nested inside a javascript plugin which quite simply checks if something exists inside of an IndexedDB and then ideally I want it to return true or false.
I have assigned the call to the function to a variable (eg var res = $(document).check('name');)
However all I get in the console output if I do a console debug on it is undefined. If I add more console logging into the function it is getting the record correctly and in the right part of the if statement but there is no value being returned.
(function($){
var db, tx, callback, options,
names = {
checkFor: function(name){
//Lightweight copy of above without Thumbs
console.log('In checkfor');
var tx = db.transaction('myDB').objectStore('people').get(name).onsuccess = function(event){
console.debug('res',event);
var res = event.target.result;
if(res.length > 0)
return true;
else
return false;
};
}
}
$.extend($.fn,{
check: function(name){
names.checkFor(name);
});
}(jQuery));
The above is an example, there are many more functions and the plugin is quite lengthily. If anyone could help that would be greatly appreciated!
Thanks!

Windows 8 Javascript insanity - variable undefined

I'm working through some Windows 8 tutorials from the msdn website. Specifically I'm on this one.
Part of my code (copied from the tutorial is blowing my mind why it's erroring. Sample below:
(function () {
"use strict";
var list = getBlogPosts();
var groupedItems = list.createGrouped(
function groupKeySelector(item) { return item.group.key; },
function groupDataSelector(item) { return item.group; }
);
var dataPromises = [];
var blogs;
var blogPosts = new WinJS.Binding.List();
function getFeeds() {
blogs = [
{
key: "blog1",
url: 'http://windowsteamblog.com/windows/b/developers/atom.aspx',
title: 'tbd', updated: 'tbd',
acquireSyndication: acquireSyndication, dataPromise: null
},
// lots more entries ...
];
blogs.forEach(function (feed) {
feed.dataPromise = feed.acquireSyndication(feed.url);
dataPromises.push(feed.dataPromise);
});
return WinJS.Promise.join(dataPromises).then(function () { return blogs });
}
// more code...
})();
At the line dataPromises.push(feed.dataPromise); I get the error JavaScript runtime error: Unable to get property 'push' of undefined or null reference. You can see dataPromises is defined and initialised to an empty array near the top of the file (I've also tried initialising it with new Array();).
What am I doing wrong here??? I'm guessing I've made some stupid screw up... Incidentally, the 3 places dataPromises appears in the snippet above are the only places it appears anywhere in the project.
My first thought was hoisting but unless something magical is going on, I'm not explicitly declaring dataPromises in any local scopes that might be overriding the top function scope.
You are not following the tutorial correctly. The line
var list = getBlogPosts();
replaces the new WinJS.Binding.List() call, which occurs after the line that initializes dataPromises.
The problem is that getBlogPosts() is calling getFeeds(), and getFeeds is trying to push results onto dataPromises but the line var dataPromises = [] hasn't executed yet, so dataPromises is still undefined.
Move the call to getBlogPosts() to after the initialization of the dataPromises variable.
Stepping through the code in the debugger line by line should have exposed this problem in a fairly straightforward manner.

console.log does not print undefined?

I am new to Javascript. I am trying to understand where "this" is bound to using different examples. I am using console.log to print some values as shown below.
function FuncObject(value) {
this.answer = value;
this.get_answer = function () {
return this.answer;
}
};
var f = new FuncObject(42);
var fanswer = f.get_answer;
console.log(fanswer())
console.log prints "function" instead of "undefined". document.writeln seems to print "undefined" which is the right one because this is bound to the window object which does not have answer. Now printing function confuses me. Now I am wondering what i should be using for logging. I am unable to find an explanation for this.
thanks mohan
Just incase you didn't notice, there's a typo in your posted code of
this.get_answer = funcition ()
With that in mind, I'm not entirely sure of your experience level so let me cover all the bases.
function FuncObject(value) {
this.answer = value;
this.get_answer = function () {
return this.answer;
}
};
var f = new FuncObject(42);
var fanswer = f.get_answer;
console.log(fanswer())
You're setting fanswer = f.get_answer where f.get_answer is a function, so as such it sets fanswer to the function equivalent of this.get_answer.
If you want the return value of f.get_answer you need to call f.get_answer(), which returns 42.
With what you put, console.log(fanswer()) does print undefined as expected.
If you simply do console.log(fanswer) it records it as function, also as expected.
I'm not sure why you would receive function as you stated in your question, because I definitely do not, jsbin.

Categories