the-geeky-codes-high-resolution-logo-color-on-transparent-background geeky code red logo
  • Home
  • AI
    AIShow More
    generate vector icons
    Generate Vector Icons with ChatGPT DALLE 3: A Comprehensive Guide
    14 Min Read
    Dalle 3
    Dalle 3: A Step-by-Step Guide to Mastering AI Art Generation
    4 Min Read
    5 Best AI Tools to Convert Images to Video Animations
    5 Best AI Tools to Convert Images to Video Animations
    8 Min Read
    Exploring the Impressive Mistral 7B Model
    Exploring the Impressive Mistral 7B Model for Text Summarization and Coding
    6 Min Read
    The AI Revolution this week
    Must Read – The AI Revolution this week 30 Sep 2023: Integrating AI Tools into Everyday Life
    6 Min Read
  • Tutorial
    • React js
    • Python
    • Javascript
  • AI Tools
Reading: Mastering Modern JavaScript: Your Comprehensive Cheat Sheet ES6- ES11
Share
the geeky codesthe geeky codes
Aa
  • AI
  • AI Tools
  • Javascript
  • Python
  • React js
  • Advertise
Search
  • Categories
    • AI
    • AI Tools
    • Javascript
    • Python
    • React js
  • More
    • Advertise
Follow US
Copyright ©2023 The Geeky codes. All Rights Reserved.
the geeky codes > Blog > Tutorial > Javascript > Mastering Modern JavaScript: Your Comprehensive Cheat Sheet ES6- ES11
Javascript

Mastering Modern JavaScript: Your Comprehensive Cheat Sheet ES6- ES11

thegeekycodes By thegeekycodes 1 September 2023 9 Min Read
Mastering Modern JavaScript
SHARE

Mastering Modern JavaScript

🚀👩‍💻👨‍💻 JavaScript, the language that powers the web, continues to evolve and bring new features and improvements with each update. Whether you’re a seasoned developer or just starting your coding journey, staying up-to-date with the latest JavaScript features is essential. In this comprehensive cheat sheet, we’ll explore the key features introduced from ES6 to ES11, along with code examples and outputs.

Contents
Mastering Modern JavaScriptES6 (ECMAScript 2015)let and constArrow FunctionsTemplate LiteralsDestructuring AssignmentSpread OperatorRest ParametersClassesPromisesES7 (ECMAScript 2016)Exponentiation OperatorES8 (ECMAScript 2017)Async/AwaitES9 (ECMAScript 2018)Rest/Spread PropertiesPromise finally()ES10 (ECMAScript 2019)Array flat() and flatMap()Optional Catch BindingObject.fromEntries()ES11 (ES2020)Optional Chaining (?.)Nullish Coalescing Operator (??)Dynamic ImportBigIntGlobalThisResources

Download the cheat here – Mastering Modern JavaScript.pdf

ES6 (ECMAScript 2015)

let and const

In ES6, let and const were introduced to declare variables.

let variableName = 'This is a variable';
const constantValue = 'This cannot be changed';

console.log(variableName); // "This is a variable"
console.log(constantValue); // "This cannot be changed"

Arrow Functions

Arrow functions allow you to write shorter and more readable code when defining simple functions. They remove the need for the function keyword and the return statement in some cases.

Example without Arrow Function:

function add(a, b) {
  return a + b;
}

Example with Arrow Function:

const add = (a, b) => a + b;

One of the most significant advantages of arrow functions is that they capture the surrounding this value. In regular functions, the value of this can change depending on how the function is called. Arrow functions, however, preserve the value of this from their enclosing scope.

Example of this in Regular Function:

function Counter() {
  this.count = 0;
  setInterval(function () {
    this.count++; // This won't work as expected
    console.log(this.count);
  }, 1000);
}

In the above example, this.count won’t behave as expected because this inside the setInterval callback refers to the global object, not the Counter instance.

Example of this with Arrow Function:

function Counter() {
  this.count = 0;
  setInterval(() => {
    this.count++; // This works as expected
    console.log(this.count);
  }, 1000);
}

With the arrow function, this correctly refers to the Counter instance.

Template Literals

Template literals simplify string interpolation.

const name = 'John';
const greeting = `Hello, ${name}!`;

console.log(greeting); // "Hello, John!"

Destructuring Assignment

Destructuring allows you to extract values from objects and arrays.

const person = { name: 'Alice', age: 30 };
const { name, age } = person;

console.log(name); // "Alice"
console.log(age);  // 30

Spread Operator

The spread operator can merge arrays and objects easily.

const array1 = [1, 2, 3];
const array2 = [...array1, 4, 5];

console.log(array2); // [1, 2, 3, 4, 5]

Rest Parameters

Rest parameters capture function arguments as an array.

function sum(...numbers) {
  return numbers.reduce((acc, num) => acc + num, 0);
}

console.log(sum(1, 2, 3)); // 6

Classes

ES6 introduced the class syntax for creating constructor functions.

class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

const cat = new Animal('Whiskers');
cat.speak(); // "Whiskers makes a sound."

Promises

Promises simplify asynchronous operations.

const fetchData = () => {
  return new Promise((resolve, reject) => {
    // Async operation
    if (success) {
      resolve('Data fetched successfully');
    } else {
      reject('Error fetching data');
    }
  });
};

fetchData()
  .then(data => {
    console.log(data); // "Data fetched successfully"
  })
  .catch(error => {
    console.error(error); // "Error fetching data"
  });

ES7 (ECMAScript 2016)

Exponentiation Operator

The exponentiation operator ** simplifies calculations.

const squared = 2 ** 3;

console.log(squared); // 8

ES8 (ECMAScript 2017)

Async/Await

Async/await syntax simplifies working with promises.

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error(error);
  }
}

fetchData()
  .then(data => {
    console.log(data); // Use the fetched data
  })
  .catch(error => {
    console.error(error); // Handle errors
  });

ES9 (ECMAScript 2018)

Rest/Spread Properties

Rest and spread properties simplify object manipulation.

const { x, y, ...rest } = { x: 1, y: 2, a: 3, b: 4 };

console.log(rest); // { a: 3, b: 4 }

Promise finally()

The finally() method allows you to execute code regardless of promise resolution.

fetch('https://api.example.com/data')
  .then(response => response.json())
  .catch(error => console.error(error))
  .finally(() => console.log('Request completed.'));

ES10 (ECMAScript 2019)

Array flat() and flatMap()

flat() and flatMap() simplify array manipulation.

const arr = [1, 2, [3, [4, 5]]];
const flatArray = arr.flat(2);

console.log(flatArray); // [1, 2, 3, 4, 5]
const arr = [1, 2, 3];
const mappedArray = arr.flatMap(x => [x * 2]);

console.log(mappedArray); // [2, 4, 6]

Optional Catch Binding

You can omit the catch parameter.

try {
  // Code that might throw an error
} catch {
  // Handle the error without declaring a variable
}

Object.fromEntries()

Object.fromEntries() converts an array of key-value pairs into an object.

const entries = [['a', 1], ['b', 2]];
const obj = Object.fromEntries(entries);

console.log(obj); // { a: 1, b: 2 }

💁 Check out our other articles😃

 👉  Create Stunning Water Droplet Animation with JavaScript, HTML, and CSS: Step-by-Step Guide

 👉  Creating a Toggle Switcher with Happy and Sad Faces using HTML, CSS, and JavaScript

ES11 (ES2020)

Optional Chaining (?.)

Optional chaining simplifies nested property access.

const user = {
  address: {
    street: '123 Main St',
    city: 'Exampleville',
  };

const city = user?.address?.city;

console.log(city); // "Exampleville"

Nullish Coalescing Operator (??)

The nullish coalescing operator provides a default value for null or undefined.

const defaultValue = 'Default Value';
const userInput = null;

const result = userInput ?? defaultValue;

console.log(result); // "Default Value"

Dynamic Import

Dynamic import allows you to load modules asynchronously.

const moduleSpecifier = './my-module.js';
import(moduleSpecifier)
  .then(module => {
    // Use the module
  })
  .catch(error => {
    // Handle errors
  });

BigInt

BigInt is a relatively new data type introduced in ES11 (ES2020) that allows you to work with arbitrarily large integers. BigInts can represent integers with precision far beyond the capabilities of standard JavaScript numbers.

const bigIntValue = 9007199254740991n;

console.log(bigIntValue); // 9007199254740991

GlobalThis

Before globalThis, accessing the global object (e.g., window in browsers, global in Node.js) required knowing the specific environment, which could lead to non-portable code. With globalThis, you can write code that works in different JavaScript environments without modifications.

You can use globalThis to access the global object in various JavaScript environments, making your code more portable:

console.log(globalThis);

Here’s an example of using globalThis to access the global object in a browser context:

globalThis.document.getElementById('my-element').textContent = 'Hello, globalThis!';

And in a Node.js context:

globalThis.console.log('Hello, globalThis in Node.js!');

This comprehensive cheat sheet covers the key features introduced in JavaScript from ES6 to ES11. Whether you’re building web applications or delving into server-side development with Node.js, mastering these features will empower you as a JavaScript developer.

Now, it’s your turn to dive in, explore these features, and apply them to your coding projects. Happy coding, and may your JavaScript journey be filled with creative and efficient solutions! 🚀👩‍💻👨‍💻

Resources

For more in-depth learning and advanced JavaScript topics, check out the following resources:

  1. Mozilla Developer Network (MDN) JavaScript Guide – MDN’s comprehensive guide to JavaScript, covering everything from basics to advanced topics.
  2. JavaScript.info – A detailed and up-to-date JavaScript tutorial that covers ES6 and beyond.

These resources will help you further expand your knowledge and master the art of JavaScript development. Happy coding!

TAGGED: Code Writing, es11, es6, javascript

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Twitter Copy Link Print
Previous Article Mastering Button Customization in React with Tailwind CSS Mastering Button Customization in React with Tailwind CSS
Next Article Automate Language translations and Save to Excel with Ease Automate Language translations and Save to Excel with Ease!
Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Twitter Follow
Telegram Follow

Subscribe Now

Subscribe to our newsletter to get our newest articles instantly!

Most Popular
Advanced Routing Techniques in Nextjs 15
Advanced Routing Techniques in Next js 15
20 November 2024
Attachment Details Image-to-Text-Converter-with-Claude-Nextjs-15
Building an AI-Powered Image-to-Text Converter with Claude, Next.js 15, and Vercel AI SDK
20 November 2024
Generate-Dynamic-OpenGraph-Images-in-Nextjs15
How to Generate Dynamic OpenGraph Images in Next.js App Router 15 with TypeScript
20 November 2024
Google Analytics 4 in Nextjs 14
How to Install Google Analytics 4 in Next.js 15 (App Router) with TypeScript [2024]
20 November 2024
docker compose
Getting Started with Docker Compose
20 November 2024

You Might Also Like

Understanding Server Actions in Nextjs
TutorialJavascriptNextjsReact js

Understanding Server Actions in Nextjs

7 Min Read
Implementing Dark Mode with JavaScript
TutorialJavascript

Implementing Dark Mode with JavaScript

3 Min Read
Build a Simple Calculator App with React
TutorialReact js

Build a Simple Calculator App with React, Tailwind CSS. Displays History

8 Min Read
Automating Google Sheets to Send Email Reminders
TutorialGoogle SheetsJavascript

Automating Google Sheets to Send Email Reminders

5 Min Read

Always Stay Up to Date

Subscribe to our newsletter to get our newest articles instantly!

the geeky codes geeky code red logo

Providing valuable resources for developers in the form of code snippets, software tutorials, and AI related content.

About

  • About Us
  • Contact
  • Terms and Conditions
  • Privacy Policy
  • Disclaimer
  • Affiliate Disclosure

Resource

  • The Art of AI Prompt Engineering: Crafting Effective Inputs for AI Models

Get the Top 10 in Search!

Looking for a trustworthy service to optimize the company website?
Request a Quote
© 2023 The Geeky Codes. All Rights Reserved
We are happy to see you join Us!

🔥📢Subscribe to our newsletter and never miss our latest code snippets, tutorials and AI updates

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?