What is console.log and how do I use it? [duplicate] - javascript

What is the use of console.log?
Please explain how to use it in JavaScript, with a code example.

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
}

Places you can view the console! Just to have them all in one answer.
Firefox
http://getfirebug.com/
(you can also now use Firefox's built in developer tools Ctrl+Shift+J (Tools > Web Developer > Error Console), but Firebug is much better; use Firebug)
Safari and Chrome
Basically the same.
https://developers.google.com/chrome-developer-tools/docs/overview
https://developer.apple.com/technologies/safari/developer-tools.html
Internet Explorer
Don't forget you can use compatibility modes to debug IE7 and IE8 in IE9 or IE10
http://msdn.microsoft.com/en-us/library/ie/gg589507(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/dd565628(v=vs.85).aspx
If you must access the console in IE6 for IE7 use the Firebug Lite bookmarklet
http://getfirebug.com/firebuglite/ look for stable bookmarklet
http://en.wikipedia.org/wiki/Bookmarklet
Opera
http://www.opera.com/dragonfly/
iOS
Works for all iPhones, iPod touch and iPads.
http://developer.apple.com/library/ios/ipad/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/DebuggingSafarioniPhoneContent/DebuggingSafarioniPhoneContent.html
Now with iOS 6 you can view the console through Safari in OS X if you plug in your device. Or you can do so with the emulator, simply open a Safari browser window and go to the "Develop" tab. There you will find options to get the Safari inspector to communicate with your device.
Windows Phone, Android
Both of these have no console built in and no bookmarklet ability. So we use
http://jsconsole.com/ type :listen and it will give you a script tag to place in your HTML. From then on you can view your console inside the jsconsole website.
iOS and Android
You can also use http://html.adobe.com/edge/inspect/ to access web inspector tools and the console on any device using their convenient browser plugin.
Older browser problems
Lastly older versions of IE will crash if you use console.log in your code and not have the developer tools open at the same time. Luckily it's an easy fix. Use the below code snippet at the top of your code:
if(!window.console){ window.console = {log: function(){} }; }
This checks to see if the console is present, and if not it sets it to an object with a blank function called log. This way window.console and window.console.log is never truly undefined.

You can view any messages logged to the console if you use a tool such as Firebug to inspect your code. Let's say you do this:
console.log('Testing console');
When you access the console in Firebug (or whichever tool you decide to use to inspect your code), you will see whatever message you told the function to log. This is particularly useful when you want to see if a function is executing, or if a variable is being passed/assigned properly. It's actually rather valuable for figuring out just what went wrong with your code.

It will post a log message to the browser's javascript console, e.g. Firebug or Developer Tools (Chrome / Safari) and will show the line and file where it was executed from.
Moreover, when you output a jQuery Object it will include a reference to that element in the DOM, and clicking it will go to that in the Elements/HTML tab.
You can use various methods, but beware that for it to work in Firefox, you must have Firebug open, otherwise the whole page will crash. Whether what you're logging is a variable, array, object or DOM element, it will give you a full breakdown including the prototype for the object as well (always interesting to have a poke around). You can also include as many arguments as you want, and they will be replaced by spaces.
console.log( myvar, "Logged!");
console.info( myvar, "Logged!");
console.warn( myvar, "Logged!");
console.debug(myvar, "Logged!");
console.error(myvar, "Logged!");
These show up with different logos for each command.
You can also use console.profile(profileName); to start profiling a function, script etc. And then end it with console.profileEnd(profileName); and it will show up in you Profiles tab in Chrome (don't know with FF).
For a complete reference go to http://getfirebug.com/logging and I suggest you read it. (Traces, groups, profiling, object inspection).
Hope this helps!

There is nothing to do with jQuery and if you want to use it I advice you to do
if (window.console) {
console.log("your message")
}
So you don't break your code when it is not available.
As suggested in the comment, you can also execute that in one place and then use console.log as normal
if (!window.console) { window.console = { log: function(){} }; }

console.log has nothing to do with jQuery. It is a common object/method provided by debuggers (including the Chrome debugger and Firebug) that allows a script to log data (or objects in most cases) to the JavaScript console.

console.log logs debug information to the console on some browsers (Firefox with Firebug installed, Chrome, IE8, anything with Firebug Lite installed). On Firefox it is a very powerful tool, allowing you to inspect objects or examine the layout or other properties of HTML elements. It isn't related to jQuery, but there are two things that are commonly done when using it with jQuery:
install the FireQuery extension for Firebug. This, amongst other advantages, makes the logging of jQuery objects look nicer.
create a wrapper that is more in line with jQuery's chaining code conventions.
This means usually something like this:
$.fn.log = function() {
if (window.console && console.log) {
console.log(this);
}
return this;
}
which you can then invoke like
$('foo.bar').find(':baz').log().hide();
to easily check inside jQuery chains.

console.log has nothing to do with jQuery.
It logs a message to a debugging console, such as Firebug.

A point of confusion sometimes is that to log a text message along with the contents of one of your objects using console.log, you have to pass each one of the two as a different argument. This means that you have to separate them by commas because if you were to use the + operator to concatenate the outputs, this would implicitly call the .toString() method of your object. This in most cases is not explicitly overriden and the default implementation inherited by Object doesn't provide any useful information.
Example to try in console:
>>> var myObj = {foo: 'bar'}
undefined
>>> console.log('myObj is: ', myObj);
myObj is: Object { foo= "bar"}
whereas if you tried to concatenate the informative text message along with the object's contents you'd get:
>>> console.log('myObj is: ' + myObj);
myObj is: [object Object]
So keep in mind that console.log in fact takes as many arguments as you like.

Use console.log to add debugging information to your page.
Many people use alert(hasNinjas) for this purpose but console.log(hasNinjas) is easier to work with. Using an alert pop-ups up a modal dialog box that blocks the user interface.
Edit: I agree with Baptiste Pernet and Jan Hančič that it is a very good idea to check if window.console is defined first so that your code doesn't break if there is no console available.

An example - suppose you want to know which line of code you were able to run your program (before it broke!), simply type in
console.log("You made it to line 26. But then something went very, very wrong.")

You use it to debug JavaScript code with either Firebug for Firefox, or JavaScript console in WebKit browsers.
var variable;
console.log(variable);
It will display the contents of the variable, even if it is a array or object.
It is similar to print_r($var); for PHP.

Beware: leaving calls to console in your production code will cause your site to break in Internet Explorer. Never keep it unwrapped. See: https://web.archive.org/web/20150908041020/blog.patspam.com/2009/the-curse-of-consolelog

In early days JS debugging was performed through alert() function - now it is an obsolete practice.
The console.log() is a function that writes a message to log on the debugging console, such as Webkit or Firebug. In a browser you will not see anything on the screen. It logs a message to a debugging console. It is only available in Firefox with Firebug and in Webkit based browsers (Chrome and Safari). It does not work well in all IE releases.
The console object is an extension to the DOM.
The console.log() should be used in code only during development and debugging.
It’s considered bad practice that someone leaves console.log() in the javascript file on the production server.

If your browser supports debugging, you can use the console.log() method to display JavaScript values.
Activate debugging in your browser with F12, and select "Console" in the debugger menu.
Console in JavaScript. Try to fix, or "debug," a non-functioning JavaScript program, and practice using the console.log() command. There are shortcuts that is going to help you to access to the JavaScript console, based on the browser that you are using:
Chrome Console Keyboard Shortcuts
Windows: Ctrl + Shift + J
Mac: Cmd + Option + J
Firefox Console Keyboard Shortcuts
Windows: Ctrl + Shift + K
Mac: Cmd + Option + K
Internet Explorer Console Keyboard Shortcuts
F12 key
Safari Console Keyboard Shortcuts
Cmd + Option + C

console.log specifically is a method for developers to write code to inconspicuously inform the developers what the code is doing. It can be used to alert you that there's an issue, but shouldn't take the place of an interactive debugger when it comes time to debug the code. Its asynchronous nature means that the logged values don't necessarily represent the value when the method was called.
In short: log errors with console.log (if available), then fix the errors using your debugger of choice: Firebug, WebKit Developer Tools (built-in to Safari and Chrome), IE Developer Tools or Visual Studio.

I really feel web programming easy when i start console.log for debugging.
var i;
If i want to check value of i runtime..
console.log(i);
you can check current value of i in firebug's console tab. It is specially used for debugging.

It is used to log (anything you pass it) to the Firebug console. The main usage would be to debug your JavaScript code.

Apart from the usages mentioned above, console.log can also print to the terminal in node.js. A server created with express (for eg.) can use console.log to write to the output logger file.

This is nothing to deal with the jQuery. The console.log() is referencing to the console object's log function, which provides methods for logging information to the browser's console. These methods are intended for debugging purposes only and should not be relied on for presenting information to end users.

In java scripts there is no input and output functions. So to debug the code console.log() method is used.It is a method for logging. It will be printed under console log (development tools).
Its is not present in IE8 and under until you open IE development tool.

Quoting MDN Docs here
console — contains many methods that you can call to perform
rudimentary debugging tasks, generally focused around logging various
values to the browser's Web Console.
By far the most commonly-used method is console.log, which is used
to log the current value contained inside a specific variable.
How to use in Javascript?
let myString = 'Hello World';
console.log(myString);
Also remember console is a part of global window object in the web browser. Thus the following is also technically correct but isn't used in practical scenario.
let myString = 'Hello World';
window.console.log(myString);

I try to explain in easy way:
Why Useable:
The console.log() method writes a message to the console and display it.
~very useful for testing purposes.
~Use them under/inside script tags.
How To See:
=>Press F12
Syntax:
console.log(message you want to display);
~Accepts a parameter and display it.
Working With Array:
var myArray = ["Ali", "John", "Shahrukh"];
console.log(myArray);
Working With Objects:
var myObject = { firstname : "Ali", lastname : "Rana" };
console.log(myObject);
Working With Text:[method 1]:
console.log("Hello StackOverflow");
Working With Text:[method 2]
var str = "Hello StackOverflow";
console.log(str);
Working With Numbers:
var myvar = '2';
console.log(myvar);
Working With Function:
function myfunction() { return (5 * 19); }
console.log(function());
Display Message With Argument:
var a = 2;
console.log("The value of a is " + a);
Hope, It May Helps.

The console.log() is a function in JavaScript which is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user.
EG CODE:
function func() { return (5 * 18); }
console.log(func());
IMG:
OUTPUT:

console.log() : This method is well known and most common which can output anything of any type. Pass string, number, object or even html elements as a parameter and it will print same for you.
Ex.
console.log('Your print statements here!');
console.log('2nd parameter is type object', {type: 'object'});
console.log('can print with multiple parameters', 100001, {type: 'object'});
Find more about console with examples from here: console

console.log() is for a developer to generally logging output information.
You also have other console methods as shown below
console.assert()
//Log a message and stack trace to console if the first argument is false.
console.clear()
// Clear the console.
console.count()
// Log the number of times this line has been called with the given label.
console.countReset()
// Resets the value of the counter with the given label.
console.debug()
// Outputs a message to the console with the log level debug.
console.dir()
// Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects.
console.dirxml()
// Displays an XML/HTML Element representation of the specified object if possible or the JavaScript Object view if it is not possible.
console.error()
// Outputs an error message. You may use string substitution and additional arguments with this method.
console.exception()
// Non-Standard
// An alias for error().
console.group()
// Creates a new inline group, indenting all following output by another level. To move back out a level, call groupEnd().
console.groupCollapsed()
// Creates a new inline group, indenting all following output by another level. However, unlike group() this starts with the inline group collapsed requiring the use of a disclosure button to expand it. To move back out a level, call groupEnd().
console.groupEnd()
// Exits the current inline group.
console.info()
// Informative logging of information. You may use string substitution and additional arguments with this method.
console.log()
// For general output of logging information. You may use string substitution and additional arguments with this method.
console.profile()
// Non-Standard
// Starts the browser's built-in profiler (for example, the Firefox performance tool). You can specify an optional name for the profile.
console.profileEnd()
// Non-Standard
// Stops the profiler. You can see the resulting profile in the browser's performance tool (for example, the Firefox performance tool).
console.table()
// Displays tabular data as a table.
console.time()
// Starts a timer with a name specified as an input parameter. Up to 10,000 simultaneous timers can run on a given page.
console.timeEnd()
// Stops the specified timer and logs the elapsed time in milliseconds since it started.
console.timeLog()
// Logs the value of the specified timer to the console.
console.timeStamp()
// Non-Standard
// Adds a marker to the browser's Timeline or Waterfall tool.
console.trace()
// Outputs a stack trace.
console.warn()

Related

Is there a way to get the browser console output without using the console?

I'm in a unique situation where my production code is being used does not allow for the browser debugger to open. So bringing up the browser console is not an option. This causes issues when it comes to debugging and finding out what errors come up.
Is there a way to get the console output (errors and warnings) through JavaScript, a library, or API?
I've looked into console API but so far it looks like just different ways to display data within the console.
I can't say for all web browsers, but I just tested this on the browser I am using right now, Edge.
What you can do is you can set console.log to a custom function, like (You should backup the standard console.log before calling this)
console.log = function (data) {
alert(data);
}
or
var logBackup = console.log;
console.log = function(str) {
// do you analysis/processing on str
analytics(str);
// then call the old log
logBackup(str);
});
In your custom (JavaScript) function, you can analyze the output to the log
Try this
Run this command in cmd or powershell
node inspect file_name.js
You can debug in console . But node js must be installed in your system.

should I use a js function other than console.log(message)?

I would like to use console.log(message) to write out some information to the browser console. However, I came across this url which seems to recommend against it:
https://developer.mozilla.org/en-US/docs/Web/API/Console/log
Are you currently choosing to use console.log(message) as part of your js code? If not then have you identified an alternative?
I agree with Mike C above-- console is generally available in most browsers, but you should probably remove console logs before a site gets pushed to production.
Additionally, some older browser might not have the console, and if you did accidentally leave in a console log, it would fire an error when it attempted to interact with with something that wasn't defined. As an extra failsafe, you can declare console and console.log in the global namespace if they are not detected, just in case:
if (!console) {
console = {
log: function () { //noop }
};
}
should I use a js function other than console.log(message)?
simple answer is yes, But also the console.log(message) is usaually used for testing purposes and for other relevant intentions like letting other developers interract with your js source code in some sort.
However.
You should not use it to log very important messages as this could be a hole your application presumably.
Hope it helps.
While the console object is not defined in the official Javascript standard, it is specified in:
Google Chrome
Mozilla Firefox
Internet Explorer 9+
Opera
Safari
Node.js
PhantomJS (since it uses V8 like Chrome and Node.js)
and more, I'm sure. As long as you're debugging in any of the environments which supports it, you're fine. You should be removing your logging statements before pushing to production anyway so as long as it works for debugging, it's nothing to worry about.

What are the rights ways of debugging javascript?

I made a function called test() in javascript file.Placed a simple alert into it.
In html file, called the method on click of a button. But,it was not being invoked.
Problem was in the 11th function, nowhere related to mine !!!! But, how can a person making his first javascript function suppose to find that out ???
I am looking for best ways to debug javascript.
You can debug javascript using many modern browsers. See this question for details on how to debug in Google Chrome:
How do you launch the JavaScript debugger in Google Chrome?
Furthermore, you shouldn't use alert() for debugging as this can give different results to a production version due to alert() causing a pause in the script.
It is best practice to use console.log() and view the output in the browsers Console.
You can also put debugger in your javascript code to force a breakpoint. However I prefer not to use this as forgetting to remove this before deployment will cause your script to pause, which can be quite embarrassing!
You should use the debug console provided by the browser.
Chrome has it inbuilt, press CTRL + SHIFT + j. In Firefox, install Firebug plugin.
In your code, add alert() to show flow and get values of variables.
Also, use console.log() which will only output to the debug console.
Depending on your browser choice there are debugging options - I tend to use Firefox, so Firebug in my case. There is a question that list options for other browsers - What is console.log and how do I use it?
Unless the project you're working on has already adopted a mechanism for debugging, console.log() tends to be a simple and useful option when tracking down a problem.
Whilst debugging you could take the approach to log out a line when entering a function, like so:
var myFunc = function(el) {
console.log('Inside myFunc');
// Existing code
};
This will enable you to see which functions have been called and give you a rough idea of the order of execution.
You can also use console.log() to show the contents of variables - console.log(el);
Be mindful to remove/disable console.log() calls once you're done as it will likely cause some issues in production.
To answer your question within question,
how can a person making his first javascript function suppose to find that out ???
Well, when something is wrong in JavaScript, for example, you made a syntax error - the script will stop working from there. However, this won't stop HTML from rendering on, so it might look as if everything is correct (especially if your JS is not changing the look of the page) but all the functionality of JS will be dead.
That's why we use the debug tools (listed in the other answers here) to see what's wrong, and in cases like this, it's very easy to notice which function has errors and is causing the whole script to break. This would probably have save a few minutes to your seniors as well.
The best approach would be to test frequently so that whenever you run into errors, you can fix them right away.

Get attributes in javascript

I get an element by id, and I would like to know all attributes of the object.
I've using alerts for all this kind of stuff, is that the way its done in javascript? In AS3 or whatever, I would place a break point, and investigate the object in the variables panel.
Second, if that is the way its done, how can I show ALL attributes, if I don't know what they are in advance, and show them in alert boxes? Using jquery 1.5. Thanks
If by "attributes", you mean the "properties" of the DOM node, then use...
console.dir(element);
...in Chrome's developer tools, or Firebug for Firefox.
This will allow you to expand the Object and fully inspect all of its properties, including the .attributes property.
Debugging with alerts will slowly drain your soul out through your nose. Luckily, there is a better way.
The Javascript console in a modern browser (like Chrome or Safari, or with the Firefox extension Firebug) is awesome.
You can also set breakpoints in the script tab, or from the code via the debugger statement. You can inspect globals and local variables in the scripts tab as well. It's seriously awesome.
Checkout the chrome dev tools videos for way more awesome: http://code.google.com/chrome/devtools/docs/videos.html
You have a few options:
console.log(domElement);
That'll let you log statements and view the item as it exists after your script runs. Note though that Firebug treats the object as live, so changes to the object reflect in your log statement (you'll see the actual object in your log, not just a bunch of strings) at least, it did the last time I used it).
debugger;
That'll let you pause execution and analyze your object via watch window in Firebug or Chrome dev tools, or even in IE9's developer tools.

What is console.log?

What is the use of console.log?
Please explain how to use it in JavaScript, with a code example.
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
}
Places you can view the console! Just to have them all in one answer.
Firefox
http://getfirebug.com/
(you can also now use Firefox's built in developer tools Ctrl+Shift+J (Tools > Web Developer > Error Console), but Firebug is much better; use Firebug)
Safari and Chrome
Basically the same.
https://developers.google.com/chrome-developer-tools/docs/overview
https://developer.apple.com/technologies/safari/developer-tools.html
Internet Explorer
Don't forget you can use compatibility modes to debug IE7 and IE8 in IE9 or IE10
http://msdn.microsoft.com/en-us/library/ie/gg589507(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/dd565628(v=vs.85).aspx
If you must access the console in IE6 for IE7 use the Firebug Lite bookmarklet
http://getfirebug.com/firebuglite/ look for stable bookmarklet
http://en.wikipedia.org/wiki/Bookmarklet
Opera
http://www.opera.com/dragonfly/
iOS
Works for all iPhones, iPod touch and iPads.
http://developer.apple.com/library/ios/ipad/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/DebuggingSafarioniPhoneContent/DebuggingSafarioniPhoneContent.html
Now with iOS 6 you can view the console through Safari in OS X if you plug in your device. Or you can do so with the emulator, simply open a Safari browser window and go to the "Develop" tab. There you will find options to get the Safari inspector to communicate with your device.
Windows Phone, Android
Both of these have no console built in and no bookmarklet ability. So we use
http://jsconsole.com/ type :listen and it will give you a script tag to place in your HTML. From then on you can view your console inside the jsconsole website.
iOS and Android
You can also use http://html.adobe.com/edge/inspect/ to access web inspector tools and the console on any device using their convenient browser plugin.
Older browser problems
Lastly older versions of IE will crash if you use console.log in your code and not have the developer tools open at the same time. Luckily it's an easy fix. Use the below code snippet at the top of your code:
if(!window.console){ window.console = {log: function(){} }; }
This checks to see if the console is present, and if not it sets it to an object with a blank function called log. This way window.console and window.console.log is never truly undefined.
You can view any messages logged to the console if you use a tool such as Firebug to inspect your code. Let's say you do this:
console.log('Testing console');
When you access the console in Firebug (or whichever tool you decide to use to inspect your code), you will see whatever message you told the function to log. This is particularly useful when you want to see if a function is executing, or if a variable is being passed/assigned properly. It's actually rather valuable for figuring out just what went wrong with your code.
It will post a log message to the browser's javascript console, e.g. Firebug or Developer Tools (Chrome / Safari) and will show the line and file where it was executed from.
Moreover, when you output a jQuery Object it will include a reference to that element in the DOM, and clicking it will go to that in the Elements/HTML tab.
You can use various methods, but beware that for it to work in Firefox, you must have Firebug open, otherwise the whole page will crash. Whether what you're logging is a variable, array, object or DOM element, it will give you a full breakdown including the prototype for the object as well (always interesting to have a poke around). You can also include as many arguments as you want, and they will be replaced by spaces.
console.log( myvar, "Logged!");
console.info( myvar, "Logged!");
console.warn( myvar, "Logged!");
console.debug(myvar, "Logged!");
console.error(myvar, "Logged!");
These show up with different logos for each command.
You can also use console.profile(profileName); to start profiling a function, script etc. And then end it with console.profileEnd(profileName); and it will show up in you Profiles tab in Chrome (don't know with FF).
For a complete reference go to http://getfirebug.com/logging and I suggest you read it. (Traces, groups, profiling, object inspection).
Hope this helps!
There is nothing to do with jQuery and if you want to use it I advice you to do
if (window.console) {
console.log("your message")
}
So you don't break your code when it is not available.
As suggested in the comment, you can also execute that in one place and then use console.log as normal
if (!window.console) { window.console = { log: function(){} }; }
console.log has nothing to do with jQuery. It is a common object/method provided by debuggers (including the Chrome debugger and Firebug) that allows a script to log data (or objects in most cases) to the JavaScript console.
console.log logs debug information to the console on some browsers (Firefox with Firebug installed, Chrome, IE8, anything with Firebug Lite installed). On Firefox it is a very powerful tool, allowing you to inspect objects or examine the layout or other properties of HTML elements. It isn't related to jQuery, but there are two things that are commonly done when using it with jQuery:
install the FireQuery extension for Firebug. This, amongst other advantages, makes the logging of jQuery objects look nicer.
create a wrapper that is more in line with jQuery's chaining code conventions.
This means usually something like this:
$.fn.log = function() {
if (window.console && console.log) {
console.log(this);
}
return this;
}
which you can then invoke like
$('foo.bar').find(':baz').log().hide();
to easily check inside jQuery chains.
console.log has nothing to do with jQuery.
It logs a message to a debugging console, such as Firebug.
A point of confusion sometimes is that to log a text message along with the contents of one of your objects using console.log, you have to pass each one of the two as a different argument. This means that you have to separate them by commas because if you were to use the + operator to concatenate the outputs, this would implicitly call the .toString() method of your object. This in most cases is not explicitly overriden and the default implementation inherited by Object doesn't provide any useful information.
Example to try in console:
>>> var myObj = {foo: 'bar'}
undefined
>>> console.log('myObj is: ', myObj);
myObj is: Object { foo= "bar"}
whereas if you tried to concatenate the informative text message along with the object's contents you'd get:
>>> console.log('myObj is: ' + myObj);
myObj is: [object Object]
So keep in mind that console.log in fact takes as many arguments as you like.
Use console.log to add debugging information to your page.
Many people use alert(hasNinjas) for this purpose but console.log(hasNinjas) is easier to work with. Using an alert pop-ups up a modal dialog box that blocks the user interface.
Edit: I agree with Baptiste Pernet and Jan Hančič that it is a very good idea to check if window.console is defined first so that your code doesn't break if there is no console available.
An example - suppose you want to know which line of code you were able to run your program (before it broke!), simply type in
console.log("You made it to line 26. But then something went very, very wrong.")
You use it to debug JavaScript code with either Firebug for Firefox, or JavaScript console in WebKit browsers.
var variable;
console.log(variable);
It will display the contents of the variable, even if it is a array or object.
It is similar to print_r($var); for PHP.
Beware: leaving calls to console in your production code will cause your site to break in Internet Explorer. Never keep it unwrapped. See: https://web.archive.org/web/20150908041020/blog.patspam.com/2009/the-curse-of-consolelog
In early days JS debugging was performed through alert() function - now it is an obsolete practice.
The console.log() is a function that writes a message to log on the debugging console, such as Webkit or Firebug. In a browser you will not see anything on the screen. It logs a message to a debugging console. It is only available in Firefox with Firebug and in Webkit based browsers (Chrome and Safari). It does not work well in all IE releases.
The console object is an extension to the DOM.
The console.log() should be used in code only during development and debugging.
It’s considered bad practice that someone leaves console.log() in the javascript file on the production server.
If your browser supports debugging, you can use the console.log() method to display JavaScript values.
Activate debugging in your browser with F12, and select "Console" in the debugger menu.
Console in JavaScript. Try to fix, or "debug," a non-functioning JavaScript program, and practice using the console.log() command. There are shortcuts that is going to help you to access to the JavaScript console, based on the browser that you are using:
Chrome Console Keyboard Shortcuts
Windows: Ctrl + Shift + J
Mac: Cmd + Option + J
Firefox Console Keyboard Shortcuts
Windows: Ctrl + Shift + K
Mac: Cmd + Option + K
Internet Explorer Console Keyboard Shortcuts
F12 key
Safari Console Keyboard Shortcuts
Cmd + Option + C
console.log specifically is a method for developers to write code to inconspicuously inform the developers what the code is doing. It can be used to alert you that there's an issue, but shouldn't take the place of an interactive debugger when it comes time to debug the code. Its asynchronous nature means that the logged values don't necessarily represent the value when the method was called.
In short: log errors with console.log (if available), then fix the errors using your debugger of choice: Firebug, WebKit Developer Tools (built-in to Safari and Chrome), IE Developer Tools or Visual Studio.
I really feel web programming easy when i start console.log for debugging.
var i;
If i want to check value of i runtime..
console.log(i);
you can check current value of i in firebug's console tab. It is specially used for debugging.
It is used to log (anything you pass it) to the Firebug console. The main usage would be to debug your JavaScript code.
Apart from the usages mentioned above, console.log can also print to the terminal in node.js. A server created with express (for eg.) can use console.log to write to the output logger file.
This is nothing to deal with the jQuery. The console.log() is referencing to the console object's log function, which provides methods for logging information to the browser's console. These methods are intended for debugging purposes only and should not be relied on for presenting information to end users.
In java scripts there is no input and output functions. So to debug the code console.log() method is used.It is a method for logging. It will be printed under console log (development tools).
Its is not present in IE8 and under until you open IE development tool.
Quoting MDN Docs here
console — contains many methods that you can call to perform
rudimentary debugging tasks, generally focused around logging various
values to the browser's Web Console.
By far the most commonly-used method is console.log, which is used
to log the current value contained inside a specific variable.
How to use in Javascript?
let myString = 'Hello World';
console.log(myString);
Also remember console is a part of global window object in the web browser. Thus the following is also technically correct but isn't used in practical scenario.
let myString = 'Hello World';
window.console.log(myString);
I try to explain in easy way:
Why Useable:
The console.log() method writes a message to the console and display it.
~very useful for testing purposes.
~Use them under/inside script tags.
How To See:
=>Press F12
Syntax:
console.log(message you want to display);
~Accepts a parameter and display it.
Working With Array:
var myArray = ["Ali", "John", "Shahrukh"];
console.log(myArray);
Working With Objects:
var myObject = { firstname : "Ali", lastname : "Rana" };
console.log(myObject);
Working With Text:[method 1]:
console.log("Hello StackOverflow");
Working With Text:[method 2]
var str = "Hello StackOverflow";
console.log(str);
Working With Numbers:
var myvar = '2';
console.log(myvar);
Working With Function:
function myfunction() { return (5 * 19); }
console.log(function());
Display Message With Argument:
var a = 2;
console.log("The value of a is " + a);
Hope, It May Helps.
The console.log() is a function in JavaScript which is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user.
EG CODE:
function func() { return (5 * 18); }
console.log(func());
IMG:
OUTPUT:
console.log() : This method is well known and most common which can output anything of any type. Pass string, number, object or even html elements as a parameter and it will print same for you.
Ex.
console.log('Your print statements here!');
console.log('2nd parameter is type object', {type: 'object'});
console.log('can print with multiple parameters', 100001, {type: 'object'});
Find more about console with examples from here: console
console.log() is for a developer to generally logging output information.
You also have other console methods as shown below
console.assert()
//Log a message and stack trace to console if the first argument is false.
console.clear()
// Clear the console.
console.count()
// Log the number of times this line has been called with the given label.
console.countReset()
// Resets the value of the counter with the given label.
console.debug()
// Outputs a message to the console with the log level debug.
console.dir()
// Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects.
console.dirxml()
// Displays an XML/HTML Element representation of the specified object if possible or the JavaScript Object view if it is not possible.
console.error()
// Outputs an error message. You may use string substitution and additional arguments with this method.
console.exception()
// Non-Standard
// An alias for error().
console.group()
// Creates a new inline group, indenting all following output by another level. To move back out a level, call groupEnd().
console.groupCollapsed()
// Creates a new inline group, indenting all following output by another level. However, unlike group() this starts with the inline group collapsed requiring the use of a disclosure button to expand it. To move back out a level, call groupEnd().
console.groupEnd()
// Exits the current inline group.
console.info()
// Informative logging of information. You may use string substitution and additional arguments with this method.
console.log()
// For general output of logging information. You may use string substitution and additional arguments with this method.
console.profile()
// Non-Standard
// Starts the browser's built-in profiler (for example, the Firefox performance tool). You can specify an optional name for the profile.
console.profileEnd()
// Non-Standard
// Stops the profiler. You can see the resulting profile in the browser's performance tool (for example, the Firefox performance tool).
console.table()
// Displays tabular data as a table.
console.time()
// Starts a timer with a name specified as an input parameter. Up to 10,000 simultaneous timers can run on a given page.
console.timeEnd()
// Stops the specified timer and logs the elapsed time in milliseconds since it started.
console.timeLog()
// Logs the value of the specified timer to the console.
console.timeStamp()
// Non-Standard
// Adds a marker to the browser's Timeline or Waterfall tool.
console.trace()
// Outputs a stack trace.
console.warn()

Categories