Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

38 Practical JavaScript ES6–ES12 Techniques for Modern Development

Tech Nov 20 14

Block Scoping with let and const

The var keyword suffers from function‑scoped hoisting that can cause unexpected bugs. let and const offer true block scoping and prevent access before declaration – the temporal dead zone. const blocks reassignment but still allows property mutations.

let userName = 'Alex';
function display() {
  console.log(userName); // ReferenceError
  let userName = 'Jordan';
}
display();

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i)); // 3 3 3
}
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i)); // 0 1 2
}

Default Function Parameters

Instead of writing param = param || default, set the default directly in the parameter list. This keeps intent clear and simplifies the function body.

function createProfile(name = 'Guest', age = 18) {
  console.log(`Name: ${name}, Age: ${age}`);
}
createProfile();               // Name: Guest, Age: 18
createProfile('Bob', 25);      // Name: Bob, Age: 25

Rest Parameters

The rest syntax collects remaining arguments into a true array, replacing the implicit arguments object.

function calculateTotal(discount, ...prices) {
  const total = prices.reduce((sum, p) => sum + p, 0);
  return total * (1 - discount);
}
console.log(calculateTotal(0.1, 20, 30, 50)); // 90

Spread Operator for Arrays

The spread operator expands an iterable into individual elements, making array concatenation and copying effortless.

const frontEnd = ['HTML', 'CSS'];
const backEnd = ['Node.js', 'Express'];
const fullStack = [...frontEnd, ...backEnd];
console.log(fullStack); // ['HTML','CSS','Node.js','Express']

Template Literals

Backtick‑delimited strings support expression interpolation and multi‑line content without concatenation.

const item = 'laptop';
const price = 999;
const msg = `Your ${item} costs $${price}.`;
console.log(msg);

Object.keys

Object.keys(obj) returns an array of the object’s own enumerable property names.

const user = { id: 1, name: 'Sam', active: true };
const keys = Object.keys(user);
console.log(keys); // ['id','name','active']

Arrow Functions

Arrow functions provide a concise syntax and inherit the surrounding this context, making them ideal for callbacks.

const add = (a, b) => a + b;
const greet = name => `Hello, ${name}`;
const returnObj = () => ({ status: 'OK' });

const counter = {
  count: 0,
  increment: () => this.count++ // `this` refers to outer scope
};

Array.forEach

Execute a function once for each array element in order.

['a', 'b', 'c'].forEach((letter, index) => {
  console.log(`${index}: ${letter.toUpperCase()}`);
});
// 0: A, 1: B, 2: C

Array.map

Create a new array by transforming every element with a provided function.

const lengths = ['cat', 'dog', 'bird'].map(animal => animal.length);
console.log(lengths); // [3,3,4]

Array.filter

Produce a new array containing only the elements that pass a test.

const evenNumbers = [1,2,3,4,5,6].filter(n => n % 2 === 0);
console.log(evenNumbers); // [2,4,6]

Array.some

Check if atleast one element satisfies a condition; returns a boolean.

const hasNegative = [10, -5, 20].some(n => n < 0);
console.log(hasNegative); // true

Array.every

Verify that all elements meet a certain criteria; returns a boolean.

const allPositive = [10, 20, 30].every(n => n > 0);
console.log(allPositive); // true

Array.reduce

Accumulate array values into a single result using a reducer function.

const total = [1,2,3,4].reduce((acc, curr) => acc + curr, 0);
console.log(total); // 10

// Counting occurrences
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
const countMap = fruits.reduce((acc, fruit) => {
  acc[fruit] = (acc[fruit] || 0) + 1;
  return acc;
}, {});
console.log(countMap); // { apple:3, banana:2, orange:1 }

Object Property Shorthand

When a variable name matches the property name, you can omit the value.

const firstName = 'Jane';
const lastName = 'Doe';
const person = { firstName, lastName };
console.log(person); // { firstName:'Jane', lastName:'Doe' }

Promises

Represent a value that will be available in the future. Use then for success, catch for errors, and static methods like all and race for coordination.

const fetchData = () =>
  new Promise((resolve, reject) => {
    setTimeout(() => resolve('Data loaded'), 1000);
  });

fetchData()
  .then(result => console.log(result))
  .catch(err => console.error(err));

// Promise.all
Promise.all([Promise.resolve(1), Promise.resolve(2)])
  .then(([a, b]) => console.log(a + b)); // 3

// Promise.race – returns the first settled promise
Promise.race([
  new Promise(res => setTimeout(res, 100, 'fast')),
  new Promise(res => setTimeout(res, 200, 'slow'))
]).then(console.log); // 'fast'

Classes

Provide a clearer syntax over constructor functions and prototypes, with extends and super for inheritance.

class Animal {
  constructor(type) {
    this.type = type;
  }
  speak() {
    console.log(`${this.type} makes a sound.`);
  }
  static info() {
    console.log('Animals are living beings.');
  }
}

class Dog extends Animal {
  constructor(name) {
    super('dog');
    this.name = name;
  }
  speak() {
    console.log(`${this.name} barks.`);
  }
}

const buddy = new Dog('Buddy');
buddy.speak();   // Buddy barks.
Animal.info();   // Animals are living beings.

Destructuring Assignment

Unpack values from arrays or properties from objects directly into variables.

const user = { name: 'Chris', age: 28 };
const { name, age } = user;
console.log(name); // Chris

const colors = ['red', 'green', 'blue'];
const [first, second] = colors;
console.log(second); // green

// Nested destructuring
const config = { db: { host: 'localhost', port: 5432 } };
const { db: { host, port } } = config;
console.log(host); // localhost

find and findIndex

find returns the first element that matches a condition; findIndex returns its index (or -1).

const students = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' }
];
const bob = students.find(s => s.name === 'Bob');
const index = students.findIndex(s => s.name === 'Bob');
console.log(bob);     // { id:2, name:'Bob' }
console.log(index);   // 1

for...of and for...in

for...in iterates over enumerable property keys; for...of iterates over values of iterables.

const arr = [10, 20, 30];
for (const index in arr) {
  console.log(typeof index, index); // string '0', '1', '2'
}
for (const value of arr) {
  console.log(value); // 10, 20, 30
}

Set and Map

Set stores unique values of any type. Map holds key‑value pairs where keys can be anything. Both preserve insertion order.

const numberSet = new Set([1, 2, 2, 3]);
console.log(numberSet); // Set {1,2,3}

const map = new Map();
map.set('key1', 'value1');
map.set(42, 'answer');
console.log(map.get('key1')); // value1
console.log(map.has(42));     // true

// Using Set to remove duplicates
const duplicateArray = [1,2,2,3,3,4];
const uniqueArray = [...new Set(duplicateArray)];
console.log(uniqueArray); // [1,2,3,4]

Array.includes (ES7)

Check whether an array contains a value, correctly handling NaN unlike indexOf.

console.log([1,2,NaN].includes(NaN)); // true
console.log([1,2,3].includes(4));     // false

Exponentiation Operator (ES7)

** raises a number to a power, replacing Math.pow.

console.log(3 ** 4); // 81

Object.values (ES8)

Returns an array of the object’s own enumerable property values.

const car = { make: 'Toyota', model: 'Camry', year: 2021 };
console.log(Object.values(car)); // ['Toyota','Camry',2021]

Object.entries (ES8)

Returns an array of the object’s own [key, value] pairs.

const fruitPrices = { apple: 1, banana: 0.5 };
console.log(Object.entries(fruitPrices)); // [['apple',1],['banana',0.5]]

async/await (ES8)

Write asynchronous code that reads like synchronous flow. await pauses the async function until the promise settles.

const delay = ms => new Promise(res => setTimeout(res, ms));

async function sequence() {
  console.log('start');
  await delay(1000);
  console.log('1 second later');
  await delay(500);
  console.log('1.5 seconds total');
}
sequence();

for await...of (ES9)

Iterate over async iterables, processing each settled promise in order.

const createPromises = () => [
  delay(2000).then(() => 'two seconds'),
  delay(1000).then(() => 'one second'),
  delay(500).then(() => 'half second')
];

async function processInOrder() {
  for await (const msg of createPromises()) {
    console.log(msg);
  }
}
processInOrder();
// two seconds, one second, half second

Promise.finally (ES9)

Execute code after a promise settles, regardless of outcome, useful for cleanup.

fetchData()
  .then(data => console.log('success', data))
  .catch(err => console.error('error', err))
  .finally(() => console.log('cleanup'));

Array.flat (ES10)

Flatten nested arrays to a given depth. Pass Infinity for complete flattening.

const nested = [1, [2, [3, [4]]]];
console.log(nested.flat(2));        // [1, 2, 3, [4]]
console.log(nested.flat(Infinity)); // [1, 2, 3, 4]

Array.flatMap (ES10)

Map each element to an array and immediately flatten the result one level.

const phrases = ["Hello world", "Goodbye moon"];
const words = phrases.flatMap(phrase => phrase.split(' '));
console.log(words); // ['Hello','world','Goodbye','moon']

BigInt (ES10)

Represent integers larger than 2^53 - 1. Append n or use the BigInt() constructor.

const huge = 9007199254740991n;
const alsoHuge = BigInt('9007199254740991');
console.log(huge + 1n);      // 9007199254740992n
console.log(typeof huge);    // bigint

Object.fromEntries (ES10)

Convert a list of key‑value pairs back into an object – the reverse of Object.entries.

const entries = [['theme', 'dark'], ['layout', 'grid']];
const settings = Object.fromEntries(entries);
console.log(settings); // { theme:'dark', layout:'grid' }

String.trimStart and trimEnd (ES10)

Remove whitespace from only the beginning or end of a string.

const padded = '   text   ';
console.log(padded.trimStart()); // 'text   '
console.log(padded.trimEnd());   // '   text'

Promise.allSettled (ES11)

Wait for all promises to settle (fulfilled or rejected) and receive an array of status objects.

const p1 = Promise.resolve('yes');
const p2 = Promise.reject('no');
Promise.allSettled([p1, p2]).then(results => {
  results.forEach(r => console.log(r.status));
});
// fulfilled
// rejected

Optional Chaining and Nullish Coalescing (ES11)

?. safely accesses nested properties without throwing if a reference is nullish. ?? provides a default only when the left side is null or undefined, unlike || which treats all falsy values equally.

const user = { profile: { name: 'Alex' } };
console.log(user.profile?.age);      // undefined (no error)

const street = user?.address?.street ?? 'No street';
console.log(street);                 // 'No street'

// Contrast with ||
console.log(0 || 'default');         // 'default'
console.log(0 ?? 'default');         // 0

Promise.any (ES12)

Resolves as soon as the first promise fulfills; rejects only if every promise rejects.

Promise.any([
  Promise.reject('error 1'),
  Promise.resolve('quick success')
]).then(result => console.log(result)); // 'quick success'

Promise.any([
  Promise.reject('e1'),
  Promise.reject('e2')
]).catch(err => console.log(err)); // AggregateError

Numeric Separators (ES12)

Insert underscores in numeric literals to improve readability. They have no effect on the value.

const billion = 1_000_000_000;
const hex = 0xFF_FF_FF;
console.log(billion); // 1000000000

Logical Assignment Operators (ES12)

Combine logical operators with assignment to conditionally set a variable.

let a = null;
a ??= 'default';  // a becomes 'default' if null/undefined
console.log(a);    // default

let b = 0;
b ||= 10;         // b becomes 10 because 0 is falsy
console.log(b);    // 10

let c = 1;
c &&= 2;          // c becomes 2 because 1 is truthy
console.log(c);    // 2

Computed Property Names

Use an expression inside brackets to dynamically define object keys.

const field = 'age';
const person = {
  name: 'Eve',
  [field]: 25
};
console.log(person); // { name:'Eve', age:25 }

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.