Posted in jscurious.com

The shorthand techniques of any programming language help you to write more clean and optimized code and lets you achieve your goal with less coding. Let’s discuss some of the shorthand techniques of JavaScript one by one.

1. Declaring variables

//Longhand 
let x;
let y = 20;

//Shorthand
let x, y = 20;

2. Assigning values to multiple variables

We can assign values to multiple variables in one line with array destructuring.

//Longhand 
let a, b, c;
a = 5;
b = 8;
c = 12;
//Shorthand
let [a, b, c] = [5, 8, 12];

3. The Ternary operator

We can save 5 lines of code here with ternary (conditional) operator.

//Longhand 
let…


Photo by Joshua Aragon on Unsplash

A Promise in JavaScript is an object which returns a result after an asynchronous operation has finished. The result of promise can either be a success or a failure.

The Promise has 3 states.

  • Pending — The Promise has no result yet.
  • Fulfilled — The Promise has resolved.
  • Rejected — The Promise has rejected.
let promise = new Promise((resolve, reject) => {
const number = Math.round(Math.random() * 10);
if(number <= 5) {
resolve('Success');
} else {
reject(new Error('Failed'));
}
});

To create a Promise we use the Promise() constructor with the new keyword. The Promise() constructor accepts a callback function…


(posted in jscurious.com)

A callback is a function that is passed into another function as an argument which can be invoked later inside the function.

Synchronous callbacks

Synchronous means the code statements execute immediately after one another in a sequential manner.

function print(number, result) {
console.log(`${number} is ${result}`);
}
function checkEvenOrOdd(number, callback) {
const result = (number % 2 === 0) ? 'Even' : 'Odd';
callback(number, result);
}
checkEvenOrOdd(56, print);
// 56 is Even

Here the callback is executing immediately and it is not waiting for any asynchronous operation to finish. That’s why it is synchronous callback.

Asynchronous callbacks

If a callback is executing after an asynchronous…


(Posted in jscurious.com)

When we have an array of data we often required to loop through all the array elements and perform some action using the array elements. We can do this using for loop, but JavaScript array forEach() method is the new way to do it.

How forEach() method works

The JavaScript array forEach() method iterates over the array elements and executes a function for each element. Syntax is:

array.forEach(callback, thisArg);

The callback is a function that executes for every array elements and thisArg is a value to use as this in callback.

Example:

let foods = ['bread', 'rice', 'meat', 'pizza'];foods.forEach(function(food) {
console.log(food);
});

Output


Style Binding

To add a single style dynamically from any element we can make use of style binding. Syntax is:

[style.style_property] = "expression"

The value of the expression is normally a string.

<div [style.color]="hasError ? 'red' : 'black'">
...
</div>
<div [style.background-color]="'yellow'">
...
</div>

With style binding we can set only a single style, however to set multiple styles we can use ngStyle directive.

The ngStyle Directive

The ngStyle directive accepts an object where keys will be the CSS property names and the values will be respective expressions.

<div [ngStyle]="{width:'10px', height: '20px'}">
...
</div>
<div [ngStyle]="{color: isPassed?'green':'red',
backgroundColor: getColor()}">
...
</div>

We can also define…


Photo by Veri Ivanova on Unsplash

The setTimeout() method

The setTimeout() method calls a function after a specified time provided in milliseconds. This method takes a function as a first argument and time in milliseconds as the second argument. You can write your logic inside the function body which will execute after the time you have specified.

For example: Show an alert box after 5 seconds.

setTimeout(()=> {
alert('Message after 5 seconds');
}, 5000);

To cancel the timer, you can store the timer first in a variable and call the clearTimeout() function by passing the timer as argument.

var timer = setTimeout(()=> {
alert('Message after 5 seconds');
}, 5000);


Posted in jscurious.com

The String in JavaScript can be converted to Array in 5 different ways. We will make use of split, Array.from, spread, Object.assign and for loop. Let’s discuss all the methods in brief.

1. The split() method

This method is used to split a string based on a separator provided and returns an Array of substring.

let str = 'Tiger,Horse,Elephant,Wolf';let arr = str.split(','); 
//split string by comma
console.log(arr);
//["Tiger", "Horse", "Elephant", "Wolf"]

If you want to split the string by each character, then you can specify an empty string (“”) as separator.

let str = 'jscurious';let arr = str.split('');console.log(arr); 
// ["j", "s"…


array.reduce() in javascript by jscurious.com
array.reduce() in javascript by jscurious.com
Array.reduce() by jscurious.com

The Array.reduce() method reduces the array to a single value. The reduce() method takes one reducer function as the first argument and one initial value as second optional argument. The reducer function executes for each element of array and returns a value which further provided as the first argument (accumulator) to the next reducer function call.

array.reduce(reducerFunction, initialValue);

The reducer function takes two required arguments i.e. accumulator and currentValue. The accumulator is either the initial value or the previously returned value. The second argument is the value of the current element.

function reducerFunction(accumulator, currentValue, currentIndex, array) {}

The reducer function…


Photo by Markus Spiske on Unsplash

Variables in JavaScript have two types of scoping i.e. Local and Global scope. If any variable is declared inside a function, then it is a local variable and if the variable is declared outside the function then it is global variable. The scope of variables is defined by their position in the code.

Lexical Scope

JavaScript follows Lexical scoping for functions. Lexical scope means any child’s scope has access to the variables defined in parent’s scope i.e. inner functions can access the global variables.

var a = 5;function sum() {
return a + 6;
}
console.log(sum()); // 11

In the above…


Photo by Markus Winkler on Unsplash

Like data, we can bind classes to elements in angular. To set some style conditionally on any element we can simply write the CSS styles on a class selector and we can add that CSS class conditionally to any element.

Class Binding

To add or remove a CSS class dynamically from an element we can make use of class binding. Syntax is:

[classs.className] = "boolean expression"

If the given Boolean expression is truthy then the provided class will be added or if it is falsy then it will be removed from the element. For Example:

<div [class.error]="hasError"> </div><div [class.adult]="age >= 18…

Amitav Mishra

A front end web developer who loves to write blogs on JavaScript, Angular, React, HTML, CSS etc. Find them all on jscurious.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store