Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: console.log() gives different results than alert()

Tags:

javascript

Is console.log() supposed to print out the value of a variable at the time it's called in your JavaScript? That was my assumption but when I run the code below in either Firefox (using Firebug) or Google Chrome (and use the built-in dev tools), I seem to get the "final" value of an array rather than the value of the array at that time. If I use alert() statements they print out what I would expect - the value of an array at the time the alert() statement is called.

var params = new Array();
var tmp = new Array('apple', 'banana', 'cat');

for (var i=0; i < tmp.length; i++) {
    params[tmp[i]] = [];
}

console.log(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(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;
}
like image 672
Bill Avatar asked Mar 20 '13 15:03

Bill


People also ask

Is alert and console log the same?

The big explanation More specifically, the log() method is a method on the console object that logs whatever text it takes in to whatever console JS is running on. The alert() method however is not a method on the console, but is a method on the window.

Why alert is not working in JavaScript?

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. There will be two alert boxes if you run the code.

What is the difference between console log and return in JavaScript?

console. log is the equivalent of print in other languages. return is used for returning values from a function.

What is the difference between console log and console warn?

log method, and its friends console. warn and console. error , lets you dump objects in the console. The only difference between these functions is their “type” classification, which looks slightly different and can be filtered when viewing the console output.


1 Answers

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

like image 199
Arun P Johny Avatar answered Oct 19 '22 01:10

Arun P Johny