Friday, January 6, 2023

JavaScript REST Pttern

 // Spread due to the right hand side of =

const myArray = [1,2, ...[3,4]];

// Rest due to the left hand side of =   --> To pack or compress
const [a, b, ...others] = [1, 2, 3, 4];
console.log(a, b, others);

const trailblazer = {
    name : 'Srinu',
    address : {
        state : 'Karnataka',
        country : 'India'
    },
    certifications : ['Admin','PD I','PD II', 'Application Architect'],
    trailhead : {
        badges : 115,
        points : 90725,
        trails : 6
    },
    addCertification : function({month, year}) {
        console.log(month,year);
    }
}

// Rest Pttern should be always last
const [admin, pd1,...otherData] =[...trailblazer.certifications,...others];
console.log(admin,pd1,otherData);

// Objects 
const {badges,...restTrailHead} = trailblazer.trailhead;
console.log(restTrailHead);

// functions 
const add = function(...numbers) {
	console.log(numbers); // compress all the values
	let tot = 0;
	for(let i = 0; i < numbers.length; i++) {
		tot += numbers[i];
	}
	console.log(sum);
}
add(2,3,5);
add(2,3,5,7); // Seperate values can be supplied 

const nums = [90, 20, 20];
add(...nums); // Packaged values can be supplied

// Main elemement and rest of the elemement

const substract = function(mainNum,...numbersToSubstract) {
	console.log(mainNum);
	console.log(numbersToSubstract);
}
substract(100,10,2,4,5);

No comments:

Post a Comment