Converting Object to Array – ES2017
// Converting Object => Array
const zoo = {
lion : 'animal',
peacock: 'bird'
}
//Keys
Object.keys(zoo)
// ['lion', 'parrot']
//values
Object.values(zoo)
// ['animal', 'bird']
//keys and values
Object.entries(zoo)
//[['lion','animal'], ['peacock','bird']]
Different ways to convert float to integer
Math.floor(5.95)
// 5
Math.ceil(5.15)
// 6
Math.round(5.4)
// 5
Math.round(5.5)
// 6
console.log(5.95 | 0); // quick way
//result: 5
Merging Object: Multiple objects into a single Object using the spread operator
const person= {name:'Jasim', gender:'Male'};
const tools ={computer:'Mac', editor:'VScode'};
const summary = {...person, ...tools};
*/
{
name: 'jasim',
gender:'Male',
computer:'Mac',
editor:'Vscode'
}
/*
Make Console.log() output colorful and stylish in the browser console
console.log("%c I am red %c I am green", "color:red", "color:green" );
I am red I am green
Remove Character from String
let str ='Hello';
// remove first character
str.slice(1) // ello
// remove last character
string.substring(1,str.length -1)
// Hell
//remove substring from string
str.replace('ello', i)
// Hi
//remove character "LL" from "Hello" with split and join
str.split('l').join('')
// Heo
Add new element or push new element into an Array
let array = ['H', 'i'];
// add new element at last
array.push('!');
// ['H', 'i','!']
//add element at first
array.unShift('!')
// ['!','H', 'i']
3 ways to concat the multidimensional array
let nestedArray = [ [1, 2, 3], [4, 5], [6, 7,8]];
//using Array.flat() method
nestedArray.flat()
//result : [1, 2, 3, 4, 5, 6, 7, 8]
//usign concat and apply
[].concat.apply([], nestedArray)
//result : [1, 2, 3, 4, 5, 6, 7, 8]
//usign concat with ...spread operator
[].concat(...nestedArray);
//result : [1, 2, 3, 4, 5, 6, 7, 8]
Naming Conventional
//Camel case => mostly for variable declaration (camelCase)
<p id="camelCase>Hello!</p>
var camelCase;
//Pascal case (PascalCase)
class PascalCase{}
//hyphen html attribute declaration
<p class="main-paragraph">Hello1</p>
Array sort()
let array = [40, 2, 3, 45, 25, 100]
//Old way
array.sort(function(a, b){ return a-b});
// [2, 3, 25, 40, 45, 100]
//New Es6 way
array.sort((a,b) => a - b)
// [2, 3, 25, 40, 45, 100]
Change the color of cursor (caret) – CSS
input {
caret-color: auto
}
input{
caret-color: red
}
// text the color of below input caret cursor
I hope you enjoying this beautiful tricks in javascript. The third part of the javascript tricks in the next article.
Part 3 javascript trick >