Image for post
Image for post
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 marks = 26;
let result;
if(marks >= 30){
result = 'Pass';
}else{
result = 'Fail';
}…


Image for post
Image for post
(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 operation has finished then it is an Asynchronous callback. …


Image for post
Image for post
(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

bread
rice
meat…


Image for post
Image for post

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 the style object in the component and use it in template. We will set the CSS property values with dynamic validations. …


Image for post
Image for post
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);
clearTimeout(timer)…

Image for post
Image for post
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", "c", "u", "r", "i", "o", "u"…


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 also takes two optional arguments i.e. currentIndex and array. The currentIndex is the index of currentValue in array and the last optional argument is the array on which the reduce() method called upon. …


Image for post
Image for post
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 example, function sum() is using global variable "a" to perform the addition. That means variable "a" is in scope of sum(). …


Image for post
Image for post
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 ? …


Image for post
Image for post
Posted by jscurious.com

There are various methods available to find elements or their positions in Array. But we can always choose the method that satisfies our search criteria i.e. whether we are searching for element or its position in the array.

We will be discussing about 6 ways to find in array. The various methods are find, findIndex, includes, indexOf, lastIndexOf and loops ( for, filter, map). Let's check them out in brief.

The find() method

The Array find() method returns the first matched element in array that satisfies a condition. The find() method takes a function as argument which returns true or false based on some condition. The find() method executes this function for each element of array. If the function returns true for any element then that element will be returned by the find() method and it stops checking further for rest of the elements. …

About

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