Advance JavaScript Concept

Today I am going to share with you three advanced javascript concepts. Let's see what is in the content.

  1. try and catch:

try and catch are the interesting syntax of javascript. When you call a function and execute output from it, if there is no type of match then the output will stop executing continue and It will freeze on error.

On the other hand, If you use try and catch inside a function, your function will be continuously executed with the error. Look at the example below:

// Normal function

const convertToTK = (dollar) => {

if (typeof dollar === ‘number’) {

return dollar * 80

}else{

throw Error(‘Amount needs to be a number’)

}

}

const myDollar = convertToTK(‘five’)

console.log(myDollar)

console.log(‘Do not run if crash’)

// Try and catch function

const convertToTK = (dollar) => {

try {

if (typeof dollar === ‘number’) {

return dollar * 80

}else{

throw Error(‘Amount needs to be a number’)

}

} catch (error) {

console.log(error)

}

}

const myDollar = convertToTK(‘five’)

console.log(myDollar)

console.log(‘Do not run if crash’)

2. Functions with Default Parameter Values:

When you have the default parameter value of a function given, if you do not pass a parameter by calling that function. The function will execute with default parameter values. Let’s see how it works:

const add = (a = 0, b = a) => {

return a + b

}

console.log(add(null, 1))

// The output is ‘1’

3. Spread Operator:

// Spread operator in function

const numbers = [55, 58, 78, 94, 5, 15, 0, 65, -2]

console.log(Math.min(…numbers))

// Output is ‘-2’

// Spread operator in array

const names = [‘Ringku’, ‘Rana’, ‘Ripon’, ‘Rajon’]

const ages = [35, 40, 33, 25]

const fullData = […names, …ages]

console.log(fullData)

// Output is ‘[‘Ringku’, ‘Rana’, ‘Ripon’, ‘Rajon’, 35, 40, 33, 25 ]’

// Spread operator in object

const object1 = { a: 1, b: 2 }

const object2 = { c: 3, d: 4 }

const finalObject = { …object1, …object2 }

console.log(finalObject)

// Output is ‘{ a: 1, b: 2, c: 3, d: 4 }’

Self-taught frontend developer