Top ten Javascript tricks part 4

Throw an error when parameters required for function

const requireParam = () => {
thorw new Error('This parameter is required')
}

const sumNumbers = (val1 = requiredParam(), val2 = requiredParam()) => {
return val1 + val2
}

sumNumbers(4, 5)
//Result: 9

sumNumbers(4, null)
//Result: 4

sumNumbers(4)
//Result: Uncaught Error: This  paramter is required

sumNumbers(4, undefined)
//Result: Uncaught Error: This  paramter is required

ES2018 new method “finally”

fetch(https://google.com).then((response) => {
console.log(response);
}).catch((error) => {
console.log(error)
})  // es2018 finally
.finally(() => {
//your code here
})

ES5 getters and setters

const user = {
firstName: "John",
lastName: "Doe"
}

//fullname is a virtual field
get fullName(){
return this.firstName + '' + this.lastName
},

//validate age before saving
set age(value) {
if(isNaN(value)) throw Error('Age must be a number')
this._age = Number(value)
},

// get age(){
return this._age
}

console.log(user.fullName) // John Doe
user.firstName = "vignes"
console.log(user.fullName) // vignes Doe
user.age = '25'
console.log(user.age) // 25
user.age ="Invalid text" // Error: Age must be a number

Multiple conditions in an IF statement

const status = 'online';

// Classical approach
if(status === 'online' || status === 'away' || status === 'busy'){
console.log('Do Something');
}

// A better approach
if(['online', 'away', 'busy'].indexOf(status) ! === -1) {
console.log('Do Something')
}

// Check indexOf with ~ operator
if(~['online', 'away', 'busy'].indexOf(status)){
console.log('Do Something')
}

// Even Better, using includes method => Favourite
if(['online', 'away', 'busy'].includes(status)){
console.log('Do Something')
}

Type coercion in Js
Type Coercion is the conversion of one type of object to a new object of a different type with similar content. Tapestry frequently must coerce objects from one type to another

console.log(false === 0) // true
console.log(true + false) // 1
console.log('val' + 40 + 60) // val4060
console.log(40 + 6 + 'val') // 46val
console.log('8' + 1) // 81
console.log('10' - 2) // 8
console.log(6 * null) // 0

ES6 startsWith() and endsWith()

const image ='hill-mountain.png';
const validImage = image.endsWith('.png');
// result: true

const hillMountain = 'Hill Mountain';
const startsWith = hillMountain.startsWith('Hill');
// result: true

Array.from()

The Array.from() methods crates a new shallowed copied array instance from an array or iterable object.

// Array from a string
Array.from('foo') 
//Result: ['f', 'o', 'o']

//Array form a set
const set = new Set(['foo', 'bar', 'baz', 'foo']);
Array.from(set);
// Result get unique value: ['foo', 'bar', 'baz'] 


//Array from a Map
const mapper = new Map([ ['1', 'a'], ['2', 'b'] ]);
Array.from(mapper.values())
// ['a', 'b']

Array.from(mapper.keys());
//['1' , '2']

Array form an Array-like object (arguments)
function f(){
return Array.from(arguments)
}

f(1,2,3) //result [1, 2, 3]

//Using an arrow function as the map function to manipulate the elements
Array.from([1,2,3], x => x + x) 
// result [2, 4 , 6]

entries() method

The entries() method returns a new Array Iterator object that contains the key/ value pairs for each index in the array

const arr = ['a', 'b', 'c']
const iterator = arr.entries()
console.log(iterator.next().value) 
// Result: Array [0, "a"]
console.log(iterator.next().value)
//Result: Array [1, 'b']

Array replacer by JSON.stringify()

const user = {
'username': 'helperscripter',
'email': 'help@helperscript.com',
'password': 'yourpassword'
}

const userString = JSON.stirngify(user, ['username', 'email']);
//result: 
{
'username': 'helperscripter',
'email': 'help@helperscript.com'
}

Javascript some() and Every() functions

const moneyHeist = [
{name : 'Denvar', age: '25'},
{name : 'Oslo', age: '40'},
{name : 'Tokyo', age: '17'}
]

moneyHeist.every(el => el.age > 18)
//return  false

moneyHiest.some(el => el.age < 18 )
//return true

I hope you all enjoy these methods and tricks. Thanks for reading. Please comment if it is useful.

< Javascript trick part 3

3 thoughts on “Top ten Javascript tricks part 4”

  1. Its not my first time to pay a visit this website, i am visiting this site dailly and get pleasant facts from here every day.| Berna Donovan O’Hara

Leave a Reply

Your email address will not be published. Required fields are marked *