JavaScript
Arrow Functions
Arrow functions offer a concise syntax for writing function expressions.
const addNumbers = (a, b) => { return a + b; };
// OR a one-liner:
const addNumbers = (a, b) => a + b;
Syntax rule:
const functionName = (parameters) => {
return returnValue;
};
// OR a one-liner:
const functionName = (parameters) => returnValue;
Arrow functions are often used within modern frameworks (like React) due to their concise syntax, especially when defining components, handling event callbacks, and mapping arrays.
They do not have their own this context, which makes them unsuitable for defining object methods where this is expected to refer to the object itself.
const firstSpeaker = {
name: 'John Smith',
sayHi: function () {
console.log(`Hi, I'm ${this.name}!`);
},
};
firstSpeaker.sayHi(); // Output: Hi, I'm John Smith!
// Using an arrow function for an object method:
const secondSpeaker = {
name: 'John Smith',
sayHi: () => {
console.log(`Hi, I'm ${this.name}!`);
},
};
secondSpeaker.sayHi(); // Output: Hi, I'm undefined!
Destructuring
Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
const users = ["Tom", "David", "Kono", "Clerc"];
// Destructuring an array
const [firstPlace, secondPlace, thirdPlace] = users;
console.log(firstPlace); // Tom
console.log(secondPlace); // David
// Using the rest operator
const [, ...rest] = users;
console.log(rest); // [ 'David', 'Kono', 'Clerc' ]
// Destructuring an object
const user = {
username: "John Smith",
jobTitle: "Dev Backend",
company: "Corpo Corp"
};
const {username, jobTitle, company} = user;
console.log(username); // John Smith
console.log(jobTitle); // Dev Backend
Destructuring makes code more compact and easier to understand, reducing the need for repetitive dot notation or array indexing.
Modules (Default and Named Exports)
JavaScript uses modules to export and import code between files, improving maintainability and code organization.