Default Parameters & Object Shorthand
ES6 lets you give function parameters default values and write shorter object literals. Less boilerplate, fewer if (x === undefined) checks.
Default parameters
function createUser(name, role = 'student', active = true) {
return { name, role, active };
}
createUser('Alex'); // role student, active true
createUser('Admin', 'admin'); // active still true
createUser('Guest', 'guest', false);
Object property shorthand
const name = 'Node.js Chat Course';
const price = 499;
const currency = 'INR';
// Old
const product1 = { name: name, price: price, currency: currency };
// ES6 shorthand
const product2 = { name, price, currency };
Method shorthand in objects
const api = {
baseUrl: 'https://api.toolliyo.com',
getHealth() {
return fetch(this.baseUrl + '/health');
}
};
🌍 Real-world example — Send email with optional CC
function buildEmail({ to, subject, body, cc = [] }) {
return { to, subject, body, cc, sentAt: new Date().toISOString() };
}
buildEmail({
to: 'student@example.com',
subject: 'Welcome to Toolliyo',
body: 'Start with ES6 lesson 1.'
});⚠️ Common Mistake: Default only triggers for undefined, not null:
fn(null) does not use default — pass undefined or omit the argument.👨🏫 Teaching note: Quiz: what does greet(name = "Guest") return when called with greet("")? Empty string — default not used.