Is it possible to flush the console (make it print immediately)? - javascript

I use Firefox + Firebug for some Javascripting. The text I'm trying to log with console.log does not immediately appear in Firebug's console. It seems like it piles up in a buffer somewhere, and then gets flushed to console in chunks. I have a function that makes a few log calls. Sometimes I get just the first line, sometimes - nothing. I do, however, see the whole bunch of lines when I refresh the page.
Can I flush the console log manually?

The short answer is no. There is no flush. You could clear the console
console.clear();
But I don't think that's what you want. This is most likely from the code. If we can see it, I can revise my answer with better feedback.
If you want to see all the available methods under console, execute this in the command line:
for(var i in console) {
console.log(i);
}
or have a look at the wiki page of the console API.

It's not a Firefox problem, It's a JavaScript problem because execution is delayed and variables are updated so you can see only the last value.
To see immediately the output you need to convert your object in string so it will not change also if object will be updated.
I wrote this easy function :
function printLog(s) {
if (typeof(s) === 'object') {
console.log( JSON.stringify(s) );
} else {
console.log(s);
}
}
The printed output is a string (so you can't interact with it) but it contains the real dynamic object that you want to see at the print time instant.

Related

Javascript - Why does a function work on the last call only?

Just started learning how to code. The first lesson taught how functions are used. For the below add function, whenever I call the function more than once, the output is displayed only for the last one. Does a function have to be written separately for each time I call?
function add(first, second) {
return first + second;
}
add(1,2);
add(7,9);
add(3,5);
Output: 8
How can I get an output to all three?
Your add function returns the computation, it does not print anything. So once you call it, all the work will be done and returned, and if you want to see what is returned, all you need is to console them in order to appear in the developer panel
function add(first, second) {
return first + second;
}
console.log(add(1,2)); // <- HERE
console.log(add(7,9);
console.log(add(3,5));
i think you are trying this on developer console. if you run this code as a file, you even doesn't get any output.
The developer console typically logs out the output from the codeblock. once the execution is done.
use console.log() in order to see all outputs.
console.log(add(1,2));
console.log(add(7,9));
console.log(add(3,5));

Why the JSON's are different in Javascript?

I have written some code and I am printing to console . A very strange thing is happening .Below the screenshot attached :
There are two screenshot attached and in both the screenshots the attribute canvasWidth is showing some strange values. When it is unexpanded it is showing 287(expected) and when it is expanded it is showing 5.
But when I am adding the debug points then it is showing the correct value . Does anyone have any idea why it is showing this strange behaviour ???
Thanks
Chrome's debugging tools will re-evaluate the object when you click to expand, so the expanded version shows what the object looks like at the time of the click, not at the time of the console.log. Apparently, the value changed in between when the console.log happened and when the click happened.
You are probably changing this object in your code, the first log is done instantly, right when you call console.log, but your object was mutated before you had the time to expand it.
To make sure the object logged is not mutated you can copy it before the log:
// not sure of your actual log code but:
console.log('==>', index, {...object})
// instead of just
console.log('==>', index, object)
Check this example:
const obj = { cnt: 0 };
console.log(obj);
(function loop() {
obj.cnt++;
setTimeout(loop, 50);
})();
It may be useful to understand what just happend:
It is worth to remember that JavaScript is asynchronous.

JavaScript: Can't access array in object

I'm experiencing extremely strange behavior when accessing a property of an object.
Running this code:
console.log(myObj);
console.log(myObj.items);
console.log(myObj);
I get this output in the console:
How could this possibly happen?
console.log, during execution, outputs a string representation of the value in the console. Depending on Chrome's mood, it might show something [object Object] or something like Object {}. That doesn't matter.
Now note the little blue i beside it. What it means is that the object has been modified between the time it was logged and the time you expanded it in the console, and it now shows the current value (with the 2 items), not the value during console.log's execution (no items). You can actually hover on the blue i to get the explanation.
To replicate the issue, open the console and run this snippet:
var obj = {arr: []};
console.log(obj);
console.log(obj.arr);
console.log(obj);
// by this time, you see 2 object logs, 1 empty array
// (representation differs from time to time)
// > Object
// []
// > Object
obj.arr.push(1,2);
// when you try to expand the objects, an array of 2 items magically appear
// but you still see the empty array ([]) in the log.
This behavior differs across browsers. As far as I remember, Firebug outputs a serialized version when console.log executes, hence this doesn't happen there.
Debugging the code
To debug this kind of code, you have several options:
The quickest way is to log the stringified version of the object using JSON.stringify, like console.log(JSON.stringify(obj));
The best way is to add a breakpoint via the Sources tab. Browse to your file in the Sources tab of the Dev Tools, and add a breakpoint in that position. Run your code, and it will pause at that point. Use the Scope panel to inspect the variables.
If you can't reach the code using a breakpoint (probably run using eval or injected in the console), you can use the debugger; statement. Just put it in the code at that position. Run the code and it will pause when it reaches the statement. Use the Scope panel in Sources tab to inspect.
You could look at the JSON representation of the object to check, you can do that with:
console.log(JSON.stringify(myObj, null, 2));
With so little information, I can only assume you're dynamically populating the items property, making it empty when the 2nd console log runs.
Now you're wondering why it is there in the 1st console log: the console doesn't show the object properties that were there at the time the object was logged, but rather at the time the object entry was expanded in the console, so it could be that the items were populated after your 2nd console log and before you expanded the 1st one. Try logging the object as a string or a JSON to see its actual state at the time the console log was run.
Bottom line: object properties in the dev console get updated only when you expand the object entry (when you click the arrow) so you're not seeing the actual representation of the object from the time it was logged.
Here's a simple demonstration - see how it can even turn from an array into a string:
var obj = {p: []}
console.log(obj);
setTimeout(function(){
obj.p = "I'm not even an array!";
}, 1000);

Replicating/overriding javascript's console.log function

OK, so here's what I'm trying to do:
I'm building a Javascript->Cocoa/Objective-C bridge (a tiny test actually), which means that I'm able to call an Objective-C function from my JavaScript code.
One of the issues faced is that messages/errors/logs/etc from console.log are not visible, so they are to be forwarded to the corresponding Cocoa function (i created one like - (void)log:(NSString*)msg which simply takes a parameter as string and prints it out in the Xcode's console window.
Now, the thing is how do I replicate 100% what console.log does + forward the message to my own log function?
This is what I've done so far:
Javascript
console.log = function(text) {
API.log_(text);
}
Objective-C
- (void)log:(NSString*)msg
{
NSLog(#"Logging from JS : %#", msg);
}
If "text" is a simple text string when calling console.log("something"), then it works fine. If I pass the console.log function an object, then it's not working as expected (e.g. in Chrome's Javascript console window).
How would you go about it?
Is it possible to get the string output of what console.log would normally print out?
P.S. I tried playing with JSON.stringify(obj, null, 4) a bit, but it still doesn't seem right. Any ideas?
It sounds like you want the original functionality to persist whilst also capturing the input and passing it to your API. That could be achieved by something like (JSFiddle):
var original = console.log,
API = {
log_: function() {
// Your API functionality
}
};
console.log = function() {
original.apply(console, arguments);
API.log_(arguments);
};
A couple of things to point out. Firstly, the native console.log can receive any number of parameters, so we use arguments to handle this. We have to use .apply() to call the original method in the context of console and it also allows us to pass the arguments exactly as they were on the original call.

Create shortcut to console.log() in Chrome

Because I'm lazy, I created a function log that basically is just an abbreviation of console.log:
function log() {
console.log.apply(console, arguments);
}
Whenever I call this, I see the logged item in Google Chrome's Developer Tools, with on the right hand side the line number where the item was logged. However, this line number is always the same, because the actual console.log call is located at one specific place in the code (namely where I declare the log function as above).
What I also tried is just:
var log = console.log;
but this always throws an error: Illegal invocation. Weird, but I guess that's not a possibility.
How can I make a shortcut to console.log, with Developer Tools showing the line number where log was called, rather than where the actual console.log call is located?
When I reported it, it was refused but the answer was simple - create the shortcut like this:
var log = console.log.bind(console);
This doesn't leave out the line number, whilst you can call it like log(...).
I just created a module to do that.
Check out: https://github.com/ahlechandre/consl
Install
npm install consl --save-dev
Usage
const { cl } = require('consl');
cl('Outputs a message on the Console using a quick');
In my case I've set up an AutoHotKey shortcut with Ctrl + Alt + L as below:
^!l::Send console.log();{Left}{Left}
The good thing is it brings the cursor back inside the brackets for quick typing.
Tried a few things, but I don't think you can do this. As soon as you wrap console.log, the line nr will be the line where this wrap is to be found in the code. I suppose we have to live with that then?

Categories