// Traditional function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => a + b;
// Arrow function with block
const calculate = (a, b) => {
const result = a * b;
return result;
};
// Single parameter (parentheses optional)
const square = x => x * x;
// No parameters
const sayHello = () => 'Hello!';
// Returning object literals
const createUser = (name, age) => ({ name, age });
6.1.2 Lexical This
// Traditional function with 'this' binding issues
class Timer {
constructor() {
this.seconds = 0;
setInterval(function() {
this.seconds++; // 'this' is undefined
}, 1000);
}
}
// Arrow function with lexical 'this'
class Timer {
constructor() {
this.seconds = 0;
setInterval(() => {
this.seconds++; // 'this' refers to Timer instance
}, 1000);
}
}
6.2 Template Literals
6.2.1 Basic Usage
// String interpolation
const name = 'John';
const greeting = `Hello, ${name}!`;
// Multiline strings
const multiline = `
This is a
multiline
string
`;
// Expression interpolation
const a = 10;
const b = 20;
console.log(`Sum: ${a + b}`);
// Tagged templates
function myTag(strings, ...values) {
return strings.reduce((result, str, i) =>
`${result}${str}${values[i] || ''}`, '');
}
const result = myTag`Sum of ${a} and ${b} is ${a + b}`;
// Rest parameters in functions
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
// Combining with regular parameters
function multiply(multiplier, ...numbers) {
return numbers.map(num => multiplier * num);
}
// Object rest properties
const { a, b, ...rest } = { a: 1, b: 2, c: 3, d: 4 };
6.5 Modules
6.5.1 Module Syntax
// Exporting
export const pi = 3.14159;
export function square(x) {
return x * x;
}
export class Circle {
constructor(radius) {
this.radius = radius;
}
}
// Default export
export default class User {
constructor(name) {
this.name = name;
}
}
// Importing
import User from './User.js';
import { pi, square } from './math.js';
import * as mathUtils from './math.js';
import { rename as newName } from './module.js';
6.6 Map dan Set
6.6.1 Map
// Creating a Map
const map = new Map();
// Setting values
map.set('key1', 'value1');
map.set(42, 'number key');
map.set(obj, 'object key');
// Getting values
console.log(map.get('key1'));
// Checking existence
console.log(map.has('key1'));
// Deleting entries
map.delete('key1');
// Size and clearing
console.log(map.size);
map.clear();
// Iteration
map.forEach((value, key) => {
console.log(`${key} = ${value}`);
});
for (const [key, value] of map) {
console.log(`${key} = ${value}`);
}
6.6.2 Set
// Creating a Set
const set = new Set([1, 2, 3, 3]); // Duplicates removed
// Adding values
set.add(4);
set.add(5);
// Checking existence
console.log(set.has(4));
// Deleting values
set.delete(4);
// Size and clearing
console.log(set.size);
set.clear();
// Iteration
set.forEach(value => {
console.log(value);
});
for (const value of set) {
console.log(value);
}