Why is console.log() considered better than alert()?
alert()
is blockingalert()
cannot be easily suppressed in non-debug environmentconsole
typically formats your objects nicely and allows to traverse them- logging statements often have an interactive pointer to code which issued logging statement
- you cannot look at more than one
alert()
message at a time console
s can have different logging levels with intuitive formatting
Javascripts commands: window.alert vs console.log
console.log
is allowed to do "whatever the browser developer tools wish to do". As a result, console.log
is only suitable for live debugging and behaves differently in Firefox, Chrome and IE (in IE it will display the same text as the alert).
Now, alert
works consistently because it treats the input as a string and applies the [[ToString]]
conversion as required. On a DOM element - which uses toString()
for the conversion - this is not very exciting, and ends up as the string "[Object blahblah]" as noticed. (I believe the exact text may vary by browser.)
It's easy to get the same behavior with console.log
by forcing the element to a string manually:
console.log("" + document.getElementById("errorMessage"))
However, the inverse is not true and, while it could be somewhat emulated by showing the "outer HTML" in the alert, the console.log
behavior result is simply (wonderful) magic in certain developer tools.
This magic is what allows Chrome to provide "live inspection" of objects (including DOM elements) that are supplied to console.log. However, as mentioned above, IE's console.log (at least up to IE10) also forces the value to a string.. which is not so magical and quite much like the alert.
While alert can be used for "quick debugging", I'd recommend using debugger
, console.log
, and the break-point/exception support provided by the appropriate developer tools as they are much more suited to the task at hand.
why did alert return different from console.log
Maybe you got confused because you log your array twice. I hope the snippet below clarifies this a bit:
var a = [3, 1, 2];console.log('before', a);a.sort();console.log('after', a);
Why does console.log display array different than alert?
When constructing an object and printing that object to the console, console.log()
will output the object's own properties and their values. If you console.log()
the object using the object's .toString()
method you will receive [object Object]
in the console. This is the exact result you see in the alert of the object:
const obj = {};
obj['test'] = 'this is a test';
console.log(obj);
console.log(obj.toString());
alert(obj);
JavaScript: console.log() gives different results than alert()
As I said in the comments console.log(obj)
does not log a string representation, it logs a reference to the actual javascript object in the memory. So any changes made to the object will get reflected in the logged instance.
If you want to trace the progressive changes made, then convert the object to a string and print to like console.log(JSON.stringify(params))
.
Also you are not using params
as an array, you are using it as an map. so change params
to an object var params = {}
Change params
to an object and use JSON.stringify
to log it
var params = {};
var tmp = new Array('apple', 'banana', 'cat');
for (var i=0; i < tmp.length; i++) {
params[tmp[i]] = [];
}
console.log(JSON.stringify(params));
/*
SHOWS IN CONSOLE:
- []
+ apple ["jan", "feb", "mar", "apr"]
+ banana ["jan", "feb", "mar", "apr"]
+ apple ["jan", "feb", "mar", "apr"]
*/
alert( print_arr(params) );
/*
ALERT BOX TEXT:
[apple]:
[banana]:
[cat]:
*/
console.log('===========================================');
var tmp2 = new Array('jan', 'feb', 'mar', 'apr');
for (var i=0; i < tmp.length; i++) {
for (var j=0; j < tmp2.length; j++) {
params[tmp[i]].push(tmp2[j]);
}
}
console.log(JSON.stringify(params));
/*
SHOWS IN CONSOLE:
- []
+ apple ["jan", "feb", "mar", "apr"]
+ banana ["jan", "feb", "mar", "apr"]
+ apple ["jan", "feb", "mar", "apr"]
*/
alert( print_arr(params) );
/*
ALERT BOX TEXT:
[apple]:jan,feb,mar,apr
[banana]:jan,feb,mar,apr
[cat]:jan,feb,mar,apr
*/
function print_arr(arr) {
var str = '';
for (var k in arr) {
str += '[' + k + ']:' + arr[k].toString() + "\n";
}
return str;
}
Demo: Fiddle
What is console.log?
It's not a jQuery feature but a feature for debugging purposes. You can for instance log something to the console when something happens. For instance:
$('#someButton').click(function() {
console.log('#someButton was clicked');
// do something
});
You'd then see #someButton was clicked
in Firebug’s “Console” tab (or another tool’s console — e.g. Chrome’s Web Inspector) when you would click the button.
For some reasons, the console object could be unavailable. Then you could check if it is - this is useful as you don't have to remove your debugging code when you deploy to production:
if (window.console && window.console.log) {
// console is available
}
Javascript: Why sometimes alert() does not work but console.log() does?
This is a very common problem, and everyone has faced this problem atleast once.
The reason alert() does not work is because previously you have checked "prevent this page from creating additional dialoug" checkbox.
lets take a look at this code.
<script type="text/javascript">
var js_name = ['elem1', 'elem2']
for (var i = 0; i < js_name.length; i++) {
alert(js_name[i]);
};
</script>
There will be two alert boxes if you run the code. If you check the "prevent this page from creating additional dialoug" checkbox and then refresh the page again you won't get alert box ever again.
Solution is you need to close that webpage and reopen again in the browser(don't need to close the entire browser).
I am assuming you are using chrome.
Internet Explorer or FireFox doesn't have this checkbox feature.
Related Topics
Check If an Array Is Empty or Exists
How Does the (Function() {})() Construct Work and Why Do People Use It
How to Decide When to Use Node.Js
Get All Attributes of an Element Using Jquery
Sorting in JavaScript: Should Every Compare Function Have a "Return 0" Statement
Pretty Printing Xml with JavaScript
Window.Onbeforeunload Ajax Request in Chrome
Best Cross-Browser Method to Capture Ctrl+S with Jquery
Named Capturing Groups in JavaScript Regex
React-Router Scroll to Top on Every Transition
How to Convert the "Arguments" Object to an Array in JavaScript
How to Break a String Across More Than One Line of Code in JavaScript
How to Guarantee That My Enums Definition Doesn't Change in JavaScript
How to Return Values from Async Functions Using Async-Await from Function
How to Get the Destination Url for the Onbeforeunload Event
New Es6 Syntax for Importing Commonjs/Amd Modules I.E. 'Import Foo = Require('Foo')'