Modern JavaScript Syntax
💻 JavaScriptUse let and const, arrow functions, destructuring, template literals and modules.
Modern JavaScript is shorter and safer than the older syntax you may see in old tutorials. These features are now standard in every browser.
- Choose let or const.
- Write arrow functions.
- Destructure objects and arrays.
- Use template literals and modules.
let and const
Use const by default. Use let only when the variable must be reassigned. Avoid var, which has confusing scoping rules.
const school = "Courselord";
let score = 0;
score = score + 10;Arrow Functions
Arrow functions are shorter and keep the surrounding this. Use braces for multiple statements and omit them for a single expression.
const double = n => n * 2;
const greet = name => `Hello, ${name}!`;
const students = ["Ada", "Bola", "Chidi"];
const greetings = students.map(greet);
console.log(greetings);Destructuring
Destructuring pulls values out of objects and arrays into named variables.
const student = { name: "Amina", age: 16, level: "SS2" };
const { name, level } = student;
const scores = [88, 92, 75];
const [first, second] = scores;
console.log(name, level); // Amina SS2
console.log(first, second); // 88 92Modules
Split code across files with export and import. Modules keep global scope clean and make code easier to test.
// maths.js
export function add(a, b) {
return a + b;
}
// app.js
import { add } from "./maths.js";
console.log(add(2, 3)); // 5Practice
- Rewrite a function declaration as an arrow function.
- Destructure two properties from an object.
- Use a template literal to build a greeting.
Hands-on exercise
Rewrite this older code using const, an arrow function and a template literal:
var name = 'Ada';
function greet(person) { return 'Hello, ' + person + '!'; }
console.log(greet(name));
Recap
Modern syntax reduces noise: const by default, arrow functions for short callbacks, destructuring for values and modules for structure.
Example
const school = "Courselord";
let score = 0;
score = score + 10;
Exercises
var name = 'Ada';
function greet(person) { return 'Hello, ' + person + '!'; }
console.log(greet(name));
Expected Output
Hello, Ada!