The first thing that many people learn when approaching a new programming language is how to build a** “Hello World”** app.

If you’re learning plain JavaScript, without using HTML, the way you can print messages and other types of information is through the browser’s console

console.log("Hello, World!");

One of the most common things to do when JavaScript isn’t running the way we think it should, is to add log statements at various points in your app so you can understand what is really happening.

If all you know about console was that it could log things, you will probably be very successful, but:

Image for post

What if I told you can do other things with console besides logging?

Yes, that’s right.

The _console_ object has more methods than just _log_ and can help you bring your JavaScript debugging skills to a new level.

Though each browser can have its own unique features, there are some common methods available on all browsers.

I thought I would share my favorite one’s here, but for a more complete list, check out MDN

.assert()

The things with console.log is that the only way to conditionally log something is to put it in a if-block statement.

This is where console.assert comes to helping us.

console.assert only logs if the first item passed in is false, otherwise, it doesn’t log anything.

Here is an example of its usage:

console.assert(user.name === > "John", user); 
//Assertion failed: {name:"John Doe", age:15}

As you can see I am choosing to log the user object only if the user’s name is “John”, otherwise nothing is logged.

Here is another example:

const errorMsg = 'the number given is not even';

	for (let number = 2; number <= 5; number += 1) {
	    console.log('the number given is ' + number);
	    console.assert(number % 2 === 0, {number: number, errorMsg: errorMsg});
	    // or, using ES2015 object property shorthand:
	    // console.assert(number % 2 === 0, {number, errorMsg});
	}

	// output:
	// the # is 2
	// the # is 3
	// Assertion failed: {number: 3, errorMsg: "the number given is not even"}
	// the # is 4
	// the # is 5
	// Assertion failed: {number: 5, errorMsg: "the number given is not even"}

Just like console.log you can pass as many arguments to it and it will log all of them.

The only difference is that the first item passed will not be logged, it will only be evaluated as either true or false.

#web-development #angular #programming #javascript #react

Useful hidden features in JavaScript Console
2.65 GEEK