Mastering JavaScript console.log( ) to become a Pro

Mastering JavaScript console.log( ) to become a Pro

For any Web developer console.log () is too familiar to quickly debug some problems in code. Still, using only console.log( ) to debug? Well, there’s a lot more.

Printing messages in the browser console have definitely come to rescue to all the developers out there. c**onsole.log( )** messages are like medicines for most of your diseases while debugging some wired problems in your code. Most of the devs out there are like — Let’s print the message in the browser to know more about this issue. I’m sure that I’m not the only one doing this.

Apart from the most commonly used console.log( ) message to print the message in the browser there are plenty of different ways to make your debugging process a lot easier. Let’s take a look at them one by one with examples.

console.log( ) | info( ) | debug( ) | warn( ) | error( )

These will directly print the raw string with appropriate color based on the type of event that is provided to them.

console log/info/debug/warn/error

Use placeholders

There are different placeholders that can be used as listed below
%o — which takes an object,
%s — which takes a string, and
%d — which is for a decimal or integer

placeholders

Add CSS to console messages

Do all of your console messages look the same? well, it won’t be the same from now on, make your logs look more catchy for what matters the most to you.

Messages with colors

What to color only a specific word from the log message? Here you go

highlighting specific word

console.dir( )

Prints a JSON representation of the specified object.

HTML elements in console

Get the HTML elements in the console just like inspecting elements

HTML Elements

console.table ( )

Want to view JSON in a proper and easily understandable way?

Better visualization of an array of objects huh!

console.group( ) & console.groupEnd( )

It is quite possible to group the messages with the console

Grouping messages

console.count( )

This function logs the number of times that this particular call to count() has been called. This function takes an optional argument label.

If label is supplied, this function logs the number of times count() has been called with that particular label.

If label is omitted, the function logs the number of times count() has been called at this particular line.

counter

console.assert( )

This comes quite handy when you only want to print some selected logs i.e. it will only print the false argument. It does nothing at all if the first argument is true.

Assertion

console.trace( )

This method displays a trace that shows how the code ended up at a certain point.

Trace

console.time( )

A dedicated function for tracking the time taken for actions, console.time() is a better way to track the microtime taken for JavaScript executions.

console.memory( )

Wondering how our JavaScript applications are using browser memory?

Memory

console.clear( )

This one is the last but not the least , To clear all the above console messages which you’ve learned, It’s time to destroy them with clear() command

Here is the gist for all above snippets — Link

// time and time end
console.time("This");
let total = 0;
for (let j = 0; j < 10000; j++) {
  total += j
}
console.log("Result", total);
console.timeEnd("This");

// Memory
console.memory()

// Assertion
const errorMsg = 'Hey! The number is not even';
for (let number = 2; number <= 5; number += 1) {
    console.assert(number % 2 === 0, {number: number, errorMsg: errorMsg});
}

// Count
for (let i = 0; i < 11; i++) {
  console.count();
}

// group & groupEnd
console.group();
  console.log('Test message');
  console.group();
    console.log('Another message');
    console.log('Something else');
  console.groupEnd();
console.groupEnd();


// Table
const items = [
  {
    name: "chair",
    inventory: 5,
    unitPrice: 45.99
  },
  {
    name: "table",
    inventory: 10,
    unitPrice: 123.75
  },
  {
    name: "sofa",
    inventory: 2,
    unitPrice: 399.50
  }
];
console.table(items)

// Clear
console.clear()

// HTML Element
let element = document.getElementsByTagName("BODY")[0];
console.log(element)

// Dir
const userInfo = {"name":"John Miller", "id":2522, "theme":"dark"}
console.dir(userInfo);

// Color
console.log('%cColor of the text is green plus small font size', 'color: green; font-size: x-small');

// pass object, variable
const userDetails = {"name":"John Miller", "id":2522, "theme":"dark"}
console.log("Hey %s, here is your details %o in form of object", "John", userDetails);

// Default 
console.log('console.log');
console.info('console.info');
console.debug('console.debug');
console.warn('console.warn');
console.error('console.error');

Thank you for reading!

I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others.

Block any Event of Browser using Javascript codes

Block any Event of Browser using Javascript codes

In this article, we will go through possible ways to block any event using Javascript codes

In most browsers there are three possible kinds of events triggered when a keyboard key is pressed or released,

  1. keydown
  2. keypress
  3. keyup

You can check which key was pressed or released whenever KeyboardEvent is triggered because that event contains information and based on that event information you can write you custom logic to handle that event.

Note

The implementation will fail if the user disables JavaScript.

Base Code to trace any javascript event,

document.addEventListener("keydown", function(event)  
{  
   console.log(event.which);  
   console.log(event.keyCode);  
   console.log(event.shiftKey);  
   console.log(event.altKey);  
   console.log(event.ctrlKey);  
   console.log(event.metaKey);  
}   

List of Avaibale Javascript Code

We can use the below code to prevent opening of context menu, copy cut paste, or view source code on any page.

Many times we want to disable some existing functionality on a webpage for any security reason.

Eg: prevent images from being downloaded, copy the content, etc...,

Disable context menu on right click,

$("body").on("contextmenu", function (e)
   {
      return false;
   });
});

Or,

document.oncontextmenu = function() {
   return false;
}

Disable right click menu on particular section on page,

$(document).ready(function(){
   $("#youDivSectionId").bind("contextmenu", function(e) {
      return false;
   });
});

Disable Cut, copy, paste,

$(document).ready(function(){
   $('body').bind('cut copy paste', function (e)
   {
      e.preventDefault();
   });
});

Let's Block the same cut, copy, paste events with javascript codes,

$(document).ready(function(){
$(document).keydown(function(event) {
   //event.ctrlKey = check ctrl key is press or not
   //event.which = check for F7
   // event.which =check for v key
   if (event.ctrlKey==true && (event.which == '118' || event.which == '86')) {
      event.preventDefault();
      }
   });
});

Prevent browser Debugger console example,

$(document).keydown(function (event) {
// Prevent F12 -
if (event.keyCode == 123) {
   return false;
}
// Prevent Ctrl+a = disable select all
// Prevent Ctrl+u = disable view page source
// Prevent Ctrl+s = disable save
if (event.ctrlKey && (event.keyCode === 85 || event.keyCode === 83 || event.keyCode ===65 )) {
   return false;
}
// Prevent Ctrl+Shift+I = disabled debugger console using keys open
else if (event.ctrlKey && event.shiftKey && event.keyCode === 73)
{
   return false;
}
});

Thank you for reading ! I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others.

JavaScript Tutorial: if-else Statement in JavaScript

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

Decision Making in programming is similar to decision making in real life. In programming also we face some situations where we want a certain block of code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.

JavaScript’s conditional statements:

  • if
  • if-else
  • nested-if
  • if-else-if

These statements allow you to control the flow of your program’s execution based upon conditions known only during run time.

  • if: if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
    Syntax:
if(condition) 
{
   // Statements to execute if
   // condition is true
}

Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block. For example,

if(condition)
   statement1;
   statement2;

// Here if the condition is true, if block 
// will consider only statement1 to be inside 
// its block.

Flow chart:

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If statement 

var i = 10; 

if (i > 15) 
document.write("10 is less than 15"); 

// This statement will be executed 
// as if considers one statement by default 
document.write("I am Not in if"); 

< /script> 

Output:

I am Not in if
  • if-else: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.
    Syntax:
if (condition)
{
    // Executes this block if
    // condition is true
}
else
{
    // Executes this block if
    // condition is false
}


Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If-else statement 

var i = 10; 

if (i < 15) 
document.write("10 is less than 15"); 
else
document.write("I am Not in if"); 

< /script> 

Output:

i is smaller than 15
  • nested-if A nested if is an if statement that is the target of another if or else. Nested if statements means an if statement inside an if statement. Yes, JavaScript allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.
    Syntax:
if (condition1) 
{
   // Executes when condition1 is true
   if (condition2) 
   {
      // Executes when condition2 is true
   }
}

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate nested-if statement 

var i = 10; 

if (i == 10) { 

// First if statement 
if (i < 15) 
	document.write("i is smaller than 15"); 

// Nested - if statement 
// Will only be executed if statement above 
// it is true 
if (i < 12) 
	document.write("i is smaller than 12 too"); 
else
	document.write("i is greater than 15"); 
} 
< /script> 

Output:

i is smaller than 15
i is smaller than 12 too
  • if-else-if ladder Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
if (condition)
    statement;
else if (condition)
    statement;
.
.
else
    statement;


Example:

<script type = "text/javaScript"> 
// JavaScript program to illustrate nested-if statement 

var i = 20; 

if (i == 10) 
document.wrte("i is 10"); 
else if (i == 15) 
document.wrte("i is 15"); 
else if (i == 20) 
document.wrte("i is 20"); 
else
document.wrte("i is not present"); 
< /script> 

Output:

i is 20

13 Best Visual Studio Code Extensions for Frontend Development

13 Best Visual Studio Code Extensions for Frontend Development

Up your Visual Studio Code Extensions with these helpful tools for frontend development.

Visual Studio Code continues to be a widely popular IDE for developers. I started using it two years ago, and in my opinion, it’s a fantastic code editor. It allows me to customize it just the way I want. VS Code also has a build-in git integration and terminal, so you don’t have to jump from one window to another.

There are tones of plugins and even themes, where everyone can find something that he or she needs. The proper setup of VSC can improve our productivity; also, there are some plugins that will help developers to create better, clean code.

Because there are so many plugins that can be used for Visual Studio Code, it’s easy to get lost and forget about some useful extensions. This is the reason I would like to share with you my favorite extensions for VSC for frontend development.

You may also like: Top 8 Trends and Tools Front-End JavaScript for 2020.

1. HTML Snippets (Visual Studio Code HTML Snippets)

This is an essential extension for every frontend developer. You don’t have to waste more time for writing every HTML tag manually; it’s enough to put only tag name like div and press enter. Or you can even add a few tags which you would like to be nested like ul>li>a and press enter. What’s important, this extension has all HTML5 snippets.

2. JavaScript (ES6) Code Snippets

In the previous section, you could notice that snippets are handy and can help to prevent lots of spelling bugs and can make coding much faster. Each frontend developer works mostly with JavaScript. To speed up my JavaScript coding, I use JavaScript code snippets. It also supports .ts, .tsx, and .jsx files.

Here, it works similarly. For example, to create  export default class ClassName {} code it’s enough to type ecl and press tab. Easy, right? To find out more code shortcuts take a look at the extension documentation.

3. CSS Peek

As we have something for HTML and something for Javascript, something for CSS would be also useful for frontend development. CSS Peek is an extension supporting .html and .js files. It helps to quickly find and check styles applied for selected class or id. It’s beneficial for developers who don’t like to switch between different files or split the screen.

4. Angular, React and Vue

Since we're talking code snippets, it would also be good to mention extensions for each of these widely popular frontend frameworks.

For Angular, there is an extension called** Angular Snippets (Version 8)** because currently, we have Angular 8, but Angular has a new release for every version of the framework. It provides us code snippets for Typescript and HTML.

For React.js, there is an excellent extension,** ES7 React/Redux/GraphQL/React-Native snippets**.It provides code snippets for React and Redux using ES7, and it works in a similar way to JavaScript snippets with tab button.

For Vue.js development, there is a great extension called **Vetur. **It has almost 20 million downloads, and it brings a lot of functionalities like code snippets, linking and errors checking, formatting, debugging or highlighting the syntax. It looks very impressive.

You may also like: Angular vs React vs Vue: Which one will be popular in 2020.

5. ESLint

If you want to create a friendly, readable, clean code, it’s a great idea to install ESLint into your VS Code. This will help you to stick to standard practices like indentation, for example.

6. Prettier – Code Formatter

If we talk about pretty code, it’s worth to install the Prettier extension in your code editor. Prettier is excellent, especially if you are working on the project with other developers. It removes original styling and puts on the consistent code style. Thanks to consistent formatting the code is much more readable.

7. GitLens

As I mentioned at the beginning, Visual Studio Code has a git integration. We can make it even better by installing GitLens extension. It allows users to check who created each line of code when it was created. It also allows us to go to commit details quickly. It’s beneficial in case of working in a team of developers to understand the code history easily.

8. Auto Import

Auto import is a great extension which automatically imports files; you don’t have to do it manually anymore. It’s excellent primarily if you work on a component-based project. It’s enough to put the component name, and the plugin will import it.

9. Path Autocomplete

There is another great extension which will help you if you need to import something manually or add a link to a different file. Path autocomplete extension provides paths completion. While you start typing your path probably with **./ **you will notice a dropdown with folders to select. It’s crazy helpful because you don’t have to dig in your files and search the correct path.

10. Final Newline

Sometimes you have to remember about adding a new line to your document, and final-newline comes with a helping hand here. Every time you will save the file, it will insert a new line at the end of the document.

11. Bracket Pair Colorizer

Bracket pair colorizer helps us to find the closing bracket of the current block of code. It sometimes happens that at the end of your file or function, you have more than one or two closing brackets, and it’s not so easy to find the correct one then. If you are using the Bracket Pair Colorizer plugin, every starting and closing bracket has the same color for one block of code. So if your opening tag is blue, your closing tag will be blue as well.

12. Indenticator

Indeticator is an extension for VS Code which visually highlights current intend depth. It allows distinguishing easily different levels of a different block of codes. Depth is marked with small dots and lines.

13. Debugger for Chrome

And at the end an excellent plugin for debugging. Wouldn’t it be perfect if we could debug in the console like in the Chrome browser? It’s possible with Debugger for Chrome plugin; it supports setting breakpoints, stepping, debugging evil scripts, and more. If you are tired of switching from files in the code editor to debugging console in the browser, it’s a great plugin for you.

Conclusion

In the above article, I shared with you my favorite extensions for Visual Studio Code. I hope you it’s a great tip on how to set your code editor and improve your performance of your development. Also, if you are a beginner, it may help you to focus on learning programming then on looking for a closing tag, or closing bracket.

Happy coding! Thank for reading !