Make your JavaScript code Simpler and Cleaner

Make your JavaScript code Simpler and Cleaner

These practices are what makes our code cleaner, readable, more comprehensible and simpler.

These practices are what makes our code cleaner, readable, more comprehensible and simpler.

Some questions to ask yourself
  • Is it clear what is happening? (What you are trying to achieve)
  • Does it look daunting to read? (Like you’re going to have get some more coffee)
  • Have you made it look more complex than it actually is? (are you over-engineering)
Change your habits

Sometimes, the code you write is perfectly valid, usable and somewhat readable, but you might be going the long way around addressing problem. Maybe that’s because you haven’t made an effort to start using newer syntax, or that you’re stuck in how you work and your thought processes.

It might be time to change your habits by creating new ones; replacing them with shorthand alternatives for solving the same problem. It will involve asking yourself questions constantly until you are used to the new approach.

The shorthand expressions that will be discussed have their limitations. They are not always the right option, as with any tool. However, they are valid language features & syntax.

You may have strong feelings towards some of the code used. If so I would like to hear them!

Let’s start with a simple one

Simplify your truthy checks

Use ‘truthy’ to its full potential

Instead of using a complex if condition to check whether a value is truthy, you can just simply use the variable itself as the condition. You need to know the logic behind a truthy value however.

  • Will evaluate to truthy, if not false, 0, 0n, "", null, undefined, and NaN .

Before

if (condition !== undefined && condition !== null) {
    
    // handle truthy condition
}

After

if (condition) {
// handle truthy condition
}
Ternary Operators

Stop using so many if-else statements

Ternary Operators are frequently used as a shortcut to an if statement. It is simply asking a question (the condition), with which you execute some code if the answer is yes (truthy) or no (falsy).

Therefore, there are three parts to the statement: the condition to evaluate, the truthy expression, and the falsy expression.

condition ? exprIfTrue : exprIfFalse

Before

if (num > 5) {
   
   return 'number is above 5';
  
} else {
  
   return 'number is not above 5';
  
}

After

return num > 5 ? 'number is above 5' : 'number is not above 5';

When ternary operators get messy

Ternary operators are recommended for a single expression. You can use them to execute code based on the condition: condition ? executeThis() : executeOther() or assign to variables const num = condition ? 3 : 5; .

It gets messy when you introduce multiple ternary operators together into a single expression. For example…

((typeof val === 'string' ? runStringFunction() : false) ? runFunctionWhenStringFuncTrue() ? 'ok' : 'might be ok') : 'exited early so not ok'

The logic might not be clear at first glance, but you want it to be! For your future self and your peers.

When intent starts to become unclear, you should break them up into single statements or use an if-else statement.

if (typeof val === 'string') {
  if (runStringFunction()) {
       
     if (runFunctionWhenStringFuncTrue()) {
        return 'ok';
     }
     
     return 'might be ok';
  }
}
return 'exited early so not ok';

Bonus (omit the ‘else’)

As you can see from above if-else, you can omit the else if you return within the if statement. The return would cause the function to return early, making the else redundant (therefore you don’t need it for the logic to work as intended).

Short Circuit Evaluation

(Do you really need an if-else for variable assignment)

Short-Circuit Evaluation is a condition where the logical operator used, in addition to the precedence, dictates whether the statement should take the return value early (short circuit). It allows you to prevent unnecessary execution of code.

  • (some falsy expression) && _expr_ is short-circuit evaluated to the falsy expression;
  • (some truthy expression) || _expr_ is short-circuit evaluated to the truthy expression.

Before

let value; // we want to assign 'other' to 'value' if it is not null or undefined

if (other !== undefined && other !== null) {
  
    value = other;
  
    return value;
}

value = 'other was falsy';

return value;

After

const other = '';

value = other || 'other was falsy'; // will return 'other was falsy'

Bonus: Non-Boolean values

Short circuit evaluation, when used with non-boolean values, can return non boolean values.

  • && operator short circuits to the first falsy value
  • || operator short circuits to the first truthy value
const other = '';

const value = other || 'other falsy'; // returns 'other falsy'

other = 'Im truthy now';

value = other && ''; // returns 'Im falsy now' 

However be careful with introducing complexity. You begin to sacrifice the benefits of short circuit evaluation when you introduce multiple logical operators. It’s a breeding ground for irritatingly simple (but easy to miss) bugs.

This is due to operator precedence. It is important to note that the && will be evaluated first due to precedence, unless you wrap the separate logical operator conditions in parenthesis.

true || false && false // returns true, because '&&' is executed first
(true || false) && false // returns false, due to no precedence
Arrow functions

An arrow function expression is a syntactically compact alternative to a regular function. It does not have it’s own bindings to this , arguments , super or new.target .

Using an arrow function makes our code more concise, simplifies scoping and this .

Before

const func = function() {
    // do something
}

After

const func = () => { return 'something'; }
func();
// OR
const func = () => 'something';
// OR WITH PARAM (SINGLE)
func();
const func = arg => {
   console.log(arg);
}
func('hello');
// OR WITH MULTI PARAMS
const func = (arg, arg1) => {
    console.log('arg: ', arg);
    console.log('arg1: ', arg1);
};

func('hello', 'there');
Looping

Use the forEach Array Prototype method

It allows you to iterate over elements an operate on them one at a time. The operation on each element is provided through the callback parameter. It looks cleaner and is easier to infer intent.

Before

const array = ['1', '2', '3'];
for (const val of array) {
  
}
// or
for (let i = 0; i < array.length; i++) {
  
}

After

const array = ['1', '2', '3'];
array.forEach(val => {
    // do something
})

However, one drawback is that you cannot terminate a **forEach** execution early, as you can with regular for..of statements. If you require the possibility for early termination, then this isn’t the correct tool.

There may be a difference in performance of the forEach() compared to other for loops. Tests have shown that [forEach](https://github.com/dg92/Performance-Analysis-JS) is significantly slower, however for simple tasks there should be no real performance concern.

Spread Operator

The spread operator allows an iterable to be expanded where there are zero or more arguments, such as elements in an array or key-value pairs for objects.

Before

const array1 = [0, 1, 2, 3, 4];
const array2 = [5, 6, 7, 8, 9];

function(array1, array2) {
  
  for (const value of array2) {
    
    array1.push(value);
    
  }
}

After

const array = [0, 1, 2, 3, 4];
const other = [5, 6, 7, 8, 9];

function(array1, array2) {

    return [ ...array1, ...array2 ];
    
}
Rest Operator

The rest operator allows an indefinite number of arguments, represented as an array.

Before

function add(x, y, z?) {
  return x + y + (z || 0);
}

add(1, 2, 3)

After

function add(...nums) {
  return sum(...nums);
}

add(1, 2, 3, 4, 5);
add(1, 3);
add(4, 5, 3, 4);
Default object values (using spread)

When assigning values to objects, sometimes you want to check whether they are truthy (have been defined and are not null etc).

If they are falsy you might want to fallback to default values. You can achieve this with the spread operator. The second spread has the ability to overwrite object values that have already been defined, otherwise the defaultValues are kept.

Therefore, the default values are used as the first spread so that the second spread overwrites the first.

Before

function handleParams(params?: any) {
const finalParams = {
    
    one: params && params.one ? params.one,
    two: params && params.two? params.two,
    three: params && params.three ? params.three
};
    
    // do something with the params
}

After

const defaultValues = {
   one: 'oneDefault',
   two: 'twoDefault'
   three: 'threeDefault'
};

function handleParams(params?: any) {
    const finalParams = { ...defaultValues, ...params };
    
    // do something with the params
    return finalParams;
}

handleParams({one: 'oneNew', three: 'threeNew'});
// will return {one: 'oneNew', two: 'twoDefault', three: 'threeNew'}
While count-down

This is just a simple replacement for a for loop iterating over each index of an iterable. Using a while loop with a decrementing value val-- will count down to zero (which itself is falsy) to end the loop.

It looks cleaner (to me) and easy to understand what you are iterating over at first glance.

Before

for (let i; i < array.length; i++) {
    // do something
}

After

const length = array.length;
while(length--) {
    // do something
}
The bitwise NOT operator

Checking if a value is in an Array

The bitwise NOT operator can be used with an indexOf statement to check whether a value exists in an Array or String.

Where we would normally check whether the return value from the indexOf operation was more than -1 , the tilde ~ will return true if indexOf returns 0 or higher.

The logic behind the bitwise NOT is ~n == -(n+1) .

Before

const array = [0, 1, 2, 3, 4];
if (array.indexOf(5) > -1) {
  
   return 'exists';
  
} else {
  
    return 'does not exist';
  
}

After

const array = [0, 1, 2, 3, 4];

if (~array.indexOf(4)) // true

This simpler syntax can also be achieved with Array.prototype.find and Array.prototype.includes .

if (array.includes(3)) // true
  
if (array.find(val => val === 2)) // true
Self-Calling Anonymous Functions (IIFE)

We would use an IIFE (Immediately-Invoked Function Expression) when there is code which we want to be executed immediately on parsing by the browser, and/or if we do not want to pollute the namespace with conflicting variables. It essentially introduces another scope.

It is useful if you need to execute a function immediately after declaring it. It combines the declaration + execution in one concise expression.

Before

function random() {
    // do something
}

random()

After

!function() {
}()

(function() {})()

You can use any unary operator in place of ! to self-execute a function.

~function(){}()
+function(){}()

You may also like: Keeping your JavaScript code clean forever and scalable.

An important point to remember

These shorthand expressions are intended to make code simpler and cleaner.

Therefore, it is counter-productive and defeats the original purpose to use multiple shorthand expressions together.

Thank you for reading!

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

Learn JavaScript Crash Course | Best Javascript Tutorial

Learn JavaScript Crash Course | Best Javascript Tutorial

Take the first steps to mastering JavaScript, one of the fastest growing languages globally today. Because of its flexibility, it is there everywhere today: be it the web, mobile and or the desktop. Want to be one of the over 50,000 people who have benefited from this course? Join the learning fun!

Description
So you need to learn Javascript and learn it fast!

Are you a designer who's now adding JavaScript to your knowledge arsenal? Are you a student who needs a fast and high-quality JavaScript course? Are you a traditional developer trying to learn the basics? Are you applying for a job that requires JavaScript.

JavaScript is not only emerging as the most important language to know, it's flexibility is unique. With JavaScript being deployed on the web, mobile and even the desktop this is the one language that all technologists need to know. As a JavaScript developer you'll find opportunity around every corner!

This is a crash course meaning it moves quick. Every meaningful lecture is chock full of information that you can immediately apply to your coding work. Taught by a master instructor, you'll find that Javascript: Crash Course is a extremely efficient way to learn.

Each lecture course lecture includes the actual code developed by the master instructor during the lecture. No more staring at a blank screen when figuring out how to practice use the included code as a starting point.

The course culminates with developing a full quiz application called Trivia. You'll learn from building out this application yourself and modifying it and making it your own!

Join the over 500,000 learners who've enjoyed LearnToProgram courses. At LearnToProgram, we're teaching the world to code!

Who is the target audience?

Newbies Who Want to Learn Javascript Quickly
Current Programmers who need a Crash Course in Javascript
Those with Limited Time who Want to Learn Alot
Teacher and Students
Designers and Developers who Want to Learn JavaScript Efficiently
Basic knowledge
Foundational HTML
Text editor
Web Browser
What will you learn
Understand and write Javascript Code
Run Javascript Code in a Browser
Choose and Utilize Tools Used by Professional Javascript Developers
Understand the Purpose of Javascript Variables
Declare and Initialize Javascript Variables
User Variables with Strings and Numbers
Perform Mathematical Operations with Javascript
Obtain input from the User via Alert Boxes
Obtain input from the User via Forms
Understand Simple Conditionals with If
Create Complex Conditionals with If Else If
Create While Loops
Create For Loops
Understand the Purpose and Power of Javascript Objects
Use Event Objects to Track Events that Occur
Use the Javscript Date Object to Track Dates
Use the Javascript String Object to Manipulate Strings
Include Audio and Video Content with the Media API
Use the XMLHttpRequest() Object to Exchange Data
Create a Basic Ajax Request
Parse JSON code

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.