javascript: Error passing back object - javascript

I get an error passing back an object from function to calling function.
What am I doing wrong?
function stStartProcessing()
{
var returnValue = {};
returnValue = srGetNextRecord(); // returnValue is undefined
}
function srGetNextRecord()
{
var returnValue = {};
returnValue.addressToArray = "AAA";
returnValue.sequence = "111";
console.log(returnValue); // this works
return returnValue;
}

There must be a different problem in your code, since what you posted works fine.
The modified code below shows 111. See this DEMO
function stStartProcessing()
{
var returnValue = {};
returnValue = srGetNextRecord(); // returnValue is undefined -- no, it's not
console.log(returnValue.sequence); //shows 111
}
function srGetNextRecord()
{
var returnValue = {};
returnValue.addressToArray = "AAA";
returnValue.sequence = "111";
console.log(returnValue); // this works
return returnValue;
}
stStartProcessing();
On a separate note, when writing JavaScript, please get into the habit of putting your opening braces on the same line—always. For what you have above it won't make a difference, but if you ever do this:
function foo()
{
return
{
x: 1,
y: 2
};
}
horrible things will happen—a semicolon will be inserted after the word return, thereby killing your return value, and causing a script error.

Related

JSONP parsing in javascript/node.js

If I have an string containing a JSONP response, for example"jsonp([1,2,3])", and I want to retrieve the 3rd parameter 3, how could I write a function that do that for me? I want to avoid using eval. My code (below) works fine on the debug line, but return undefined for some reason.
function unwrap(jsonp) {
function unwrapper(param) {
console.log(param[2]); // This works!
return param[2];
}
var f = new Function("jsonp", jsonp);
return f(unwrapper);
}
var j = 'jsonp([1,2,3]);'
console.log(unwrap(j)); // Return undefined
More info: I'm running this in a node.js scraper, using request library.
Here's a jsfiddle https://jsfiddle.net/bortao/3nc967wd/
Just slice the string to remove the jsonp( and );, and then you can JSON.parse it:
function unwrap(jsonp) {
return JSON.parse(jsonp.slice(6, jsonp.length - 2));
}
var j = 'jsonp([1,2,3]);'
console.log(unwrap(j)); // returns the whole array
console.log(unwrap(j)[2]); // returns the third item in the array
Note that new Function is just as bad as eval.
Just a little changes and it'll work fine:
function unwrap(jsonp) {
var f = new Function("jsonp", `return ${jsonp}`);
console.log(f.toString())
return f(unwrapper);
}
function unwrapper(param) {
console.log(param[2]); // This works!
return param[2];
}
var j = 'jsonp([1,2,3]);'
console.log(unwrap(j)); // Return undefined
without return your anonymous function is like this :
function anonymous(jsonp) {
jsonp([1,2,3]);
}
because this function doesn't return so the output will be undefined.

Jasmine Spy to return different values based on argument

I am spying a JS method. I want to return different things based on actual argument to the method. I tried callFake and tried to access arguments using arguments[0] but it says arguments[0] is undefined.
Here is the code -
spyOn(testService, 'testParam').and.callFake(function() {
var rValue = {};
if(arguments[0].indexOf("foo") !== -1){
return rValue;
}
else{
return {1};
}
})
This is suggested here - Any way to modify Jasmine spies based on arguments?
But it does not work for me.
Use of arguments should work just fine. Also on a side note could you paste your entire object under test- though that's not the source of the issue.
Here is how I used it. See it in action here
var testObj = {
'sample': "This is a sample string",
'methodUnderTest': function(param) {
console.log(param);
return param;
}
};
testObj.methodUnderTest("You'll notice this string on console");
describe('dummy Test Suite', function() {
it('test param passed in', function() {
spyOn(testObj, 'methodUnderTest').and.callFake(function() {
var param = arguments[0];
if (param === 5) {
return "five";
}
return param;
});
var val = testObj.methodUnderTest(5);
expect(val).toEqual('five');
var message = "This string is not printed on console";
val = testObj.methodUnderTest(message);
expect(val).toEqual(message);
});
});

Is is bad practice to pass an empty callback in Javascript?

I have a long running function that I don't really care about handling properly. Is it bad practice to just hand it off to the event loop along with an empty callback and move on. Something like this:
var takeSomeTime = function(callback) {
var count = 0,
max = 1000,
interval;
interval = setInterval(function() {
count++;
if (count === max) {
interval.clearInterval();
return callback();
}
}, 1000);
};
var go = function(callback) {
// do some stuff
takeSomeTime(function(err) {
if (err) {
console.error(err)
}
// take all the time you need
// I'm moving on to to do other things.
});
return callback();
};
go(function(){
// all done...
});
I don't know how your question is related to memory leaks, but one could certainly think of useful applications of passing empty function around in general. You basically could pass an empty function to third party code, that expects a function and doesn't check if it actually got one. Just like in your example, or this small logging library:
// Javascript enum pattern, snatched from TypeScript
var LogLevel;
(function (LogLevel) {
LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
LogLevel[LogLevel["WARN"] = 1] = "WARN";
LogLevel[LogLevel["ERROR"] = 2] = "ERROR";
LogLevel[LogLevel["FATAL"] = 3] = "FATAL";
})(LogLevel || (LogLevel = {}));
// end enum pattern
var noLog = function() {}; // The empty callback
function getLogger(level) {
var result = {
debug: noLog,
warn: noLog,
error: noLog
};
switch(level) {
case LogLevel.DEBUG:
result.debug = console.debug.bind(console);
case LogLevel.WARN:
result.warn = console.warn.bind(console);
case LogLevel.ERROR:
result.error = console.error.bind(console);
}
return result;
}
var log1 = LogFactory.getLogger(LogLevel.DEBUG);
var log2 = LogFactory.getLogger(LogLevel.ERROR);
log1.debug('debug test');// calls console.debug and actually displays the
// the correct place in the code from where it was called.
log2.debug('debug test');// calls noLog
log2.error('error test');// calls console.error
You basically return the empty function noLog back to the consumer of our library in order to disable logging for a particular log level, yet it can be called with any number of arguments without raising errors.

Passing JavaScript to Closure in JavaScript

I'm learning how to actually use JavaScript. I've run into a situation where I'm getting an error. The error is: TypeError: 'undefined' is not an object (evaluating 'this.flagged'). I've narrowed down my code to where its happening. My code looks like this:
var flagged = false;
var intervals = [];
return {
flagged: flagged,
intervals: intervals,
createInterval : function (options) {
var defer = $q.defer();
if (this.throwsError) {
defer.reject('There was an error creating the interval.');
} else {
this.intervals.push(
$interval(function() {
console.log('here 1');
console.log(this.flagged);
},
1000
));
}
}
};
The error gets thrown at the: console.log(this.flagged); I'm guessing it has to do with the fact that "this" isn't visible. Yet, if "this" isn't visible, I'm not sure how to get the value for flagged. Can someone please explain to me what I need to do to get the value for flagged?
Thank you!
When you are using this inside $interval it won't be pointing to your original object, however, you can do this:
var flagged = false;
var intervals = [];
return {
flagged: flagged,
intervals: intervals,
createInterval : function (options) {
var defer = $q.defer(),
self = this;
if (this.throwsError) {
defer.reject('There was an error creating the interval.');
} else {
this.intervals.push(
$interval(function() {
console.log('here 1');
console.log(self.flagged);
},
1000
));
}
}
};
notice var self = this;
In JavaScript,
var flagged
will be a scoped variable, i think what you need here is a global scope variable for that, simply remove var from behind it.
flagged = false;
that should do the trick.

How to properly return an empty function?

I'm using a run-time assignment of functions to account for browser differences. However for un-supported browsers, I want to return an empty function so that a JavaScript error is not thrown.
But, jslint complains about empty functions. What is the jslint happy way to do this?
Empty block.
$R.functionNull = function () {
// events not supported;
};
$R.Constructor.prototype.createEvent = (function () {
if (doc.createEvent) {
return function (type) {
var event = doc.createEvent("HTMLEvents");
event.initEvent(type, true, false);
$NS.eachKey(this, function (val) {
val.dispatchEvent(event);
});
};
}
if (doc.createEventObject) {
return function (type) {
var event = doc.createEventObject();
event.eventType = type;
$NS.eachKey(this, function (val) {
val.fireEvent('on' + type, event);
});
};
}
return $R.functionNull;
}());
You can add a body to your function and have it return undefined:
$R.functionNull = function() {
// Events not supported.
return undefined;
};
This keeps the same semantics as a "truly empty" function, and should satisfy JSLint.
Use the lambda expression:
$R.functionNull = () => void 0;
For me this works best:
emptyFunction = Function();
console.log(emptyFunction); // logs 'ƒ anonymous() {}'
console.log(emptyFunction()); // logs 'undefined'
It's so short that I wouldn't even assign it to a variable (of course you can also use a constant-like variable "EF" or so, that's even shorter and doesn't need the additioal "()" brackets). Just use "Function()" anywhere you need a truly empty function, that doesn't even have a name, not even when you assign it to a variable, and that's the small behaviour difference between my solution and Frédéric's:
// --- Frédéric ---
emptyFunction = function() {
return undefined;
}
console.log(emptyFunction.name); // logs '"emptyFunction"'
// --- me ---
emptyFunction = Function();
console.log(emptyFunction.name); // logs '""' (or '"anonymous"' in chrome, to be fair)
What about returning
return () => undefined;
instead of
return $R.functionNull;

Categories

Resources