Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JS 2016 or ECMAScript 2016
Next article icon

JS 2015 or ECMAScript 6 (ES6)

Last Updated : 01 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

JS 2015 (ES6) also known as ECMAScript 6 (ES6), ECMAScript 6 (ES6) is a significant update to JavaScript, introducing arrow functions, classes, template literals, let and const for variable declaration, enhanced object literals, destructuring, and more modern features for better code organization and readability.

ECMAScript 6 (ES6) New Features

Name

Description

let keyword

It is used to declare variables in JavaScript that are block-scoped.

const keyword

It is used to declare variables with immutable values.

Arrow Functions

It defines anonymous functions in JavaScript.

The ... Operator

Spread/rest operator unpacks elements (spread) or gathers (rest) them conveniently.

For/of

Iterates over values in iterable objects like arrays, and strings.

Map Objects

It stores key-value pairs, allowing any key type.

Set Objects

It stores unique values, preventing duplicates.

Classes

It is used to define blueprints for creating objects.

Promises

Manage asynchronous operations, simplifying callbacks and async handling.

Symbol

It is unique, immutable, used for private property keys.

Default Parameters

Sign values when function arguments are not provided explicitly.

Function Rest Parameter

Collects function arguments as an array for flexible parameter handling.

String.includes()

Checks if substring is present, returning true/false result.

String.startsWith()

Checks if string begins with specified substring, returning boolean.

String.endsWith()

Checks if string ends with provided substring, returning boolean.

Array.from()

Converts array-like/iterable objects to new array with optional mapping.

Array keys()

Iterates over array indices, allowing index-based iteration.

Array find()

Locates and returns the first array element satisfying a provided condition.

Array findIndex()

Retrieves the index of the first array element satisfying a given condition.

New Math Methods

Methods to perform some mathematical functions.

New Number Properties

Methods to perform some numeric functions, that contains the date, integers, and floating points, etc

New Number Methods

Number.isInteger() and Number.isSafeInteger()

New Global Methods

isFinite() and isNaN()

Object entries

Converts object properties to an array of [key, value] pairs

JavaScript Modules

Encapsulate code for better organization and reusability.

Method 1: let and const keyword

  • JavaScript let is a keyword used to declare variables in JavaScript that are block scoped.
  • JavaScript const for declaring variables with immutable values, enhancing code stability and readability.

Syntax:

let variable_name = value;    // let keyword  const const_name;                  // const leyword  const x;  

Example: Here is the basic example of using let and const keyword.

JavaScript
// Using let let x = 10;  // Allowed, since x is declared with let x = 20; console.log(x); // Outputs: 20  // Using const const y = 5; y = 8;  // Error! Cannot reassign a const variable console.log(y); 

Output:

20  TypeError: Assignment to constant variable.    

Method 2: Arrow Function

Arrow functions were introduced in the ES6 version.Arrow functions are anonymous functions i.e. functions without a name and are not bound by an identifier. Arrow functions do not return any value and can be declared without the function keyword. They are also called Lambda Functions.

Syntax:

const gfg = () => {        console.log( "Hi Geek!" );  }  

Example: herecis the basic example of arrow function.

JavaScript
const gfg = () => {     console.log( "Hi from GeekforGeeks!" ); }  gfg(); 

Output
Hi from GeekforGeeks!  

Method 3: Spread Operator

The Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 value is expected.

Syntax:

let variablename1 = [...value];   

Example: In this example, we are using spread operator to create arr2 with elements from arr1 and add 4, 5 and create obj2 by merging obj1 properties and adding c: 3, d: 4.

JavaScript
// Spread operator with arrays let arr1 = [1, 2, 3]; let arr2 = [...arr1, 4, 5]; console.log(arr2);  // Spread operator with objects let obj1 = { a: 1, b: 2 }; let obj2 = { ...obj1, c: 3, d: 4 }; console.log(obj2); 

Output
[ 1, 2, 3, 4, 5 ]  { a: 1, b: 2, c: 3, d: 4 }  

Method 4: for/of Loop

The for...of loop in JavaScript iterates over iterable objects, like arrays, strings, for concise and readable element access and iteration.

Syntax:

for ( variable of iterableObjectName) {      . . .  }  

Example: In this example, the for...of loop iterates over each element in the numbers array and logs each number to the console.

JavaScript
const numbers = [1, 2, 3, 4, 5];  for (const num of numbers) {     console.log(num); }; 

Output
1  2  3  4  5  

Method 5 : Map Objects

In JavaScript, a Map object holds key-value pairs, allowing any type of key, unlike objects. It maintains order and provides methods for manipulation and retrieval.

Syntax:

let map1 = new Map();  

Example: Here is thew basic example of map object.

JavaScript
let map1 = new Map(); map1.set("FirstName", "Rohit"); map1.set("LastName", "Sharma"); map1.set("website", "GeeksforGeeks");  console.log(map1); 

Output
Map(3) {    'FirstName' => 'Rohit',    'LastName' => 'Sharma',    'website' => 'GeeksforGeeks'  }  

Method 6: Set Objects

In JavaScript, a Set object stores unique values of any type. It ensures uniqueness, provides methods for manipulation, and doesn't allow duplicate values within the set.

Syntax:

new Set( [it] );  

Example: Here is the basic example of set object.

JavaScript
const mySet = new Set();  mySet.add(1); mySet.add(2); mySet.add(3);  // Duplicate value, ignored mySet.add(2);  console.log(mySet.has(1)); console.log(mySet.has(4));  mySet.delete(2); console.log(mySet.size); // Outputs: 2 

Output
true  false  2  

Method 7: Promises

Promises in JavaScript manage asynchronous operations, representing eventual results or errors. They simplify handling async code with methods like .then(), .catch(), and allow chaining.

Syntax:

const promise = new Promise((resolve,reject) => {....});   

Example: In this example, The prom function returns a Promise based on the complete parameter, resolving with "success" if complete, and rejecting with "failed" otherwise.

JavaScript
function prom(complete) {     return prom = new Promise(function (resolve, reject) {         console.log("data iss fetching. please wait")         if (complete) {             resolve("i am successfull")         } else {             reject("i am failed")         }     }) }  prom(true).then((result) => console.log(result) ).catch((error) => console.log(error)) 

Output
data iss fetching. please wait  i am successfull  

Method 8: ES6 Symbol

ES6 Symbol is a unique, immutable data type used as object property keys, ensuring uniqueness. It's primarily for internal/private use, avoiding unintended clashes in properties.

Syntax:

let symbol = Symbol();  

Example: In this example, we are going to generate symbols.

JavaScript
// Write Javascript code here let sym1 = Symbol() let sym2 = Symbol('mysymbol') console.log('Type of sym1: ', typeof (sym1)) console.log('Type of sym2: ', typeof (sym2)) 

Output
Type of sym1:  symbol  Type of sym2:  symbol  

Method 9: Default Parameters

It is used to give the default values to the arguments, if no parameter is provided in the function call.

Syntax:

function fnName(param1 = defaultValue1, ..., paramN = defaultValueN) {       . . .  }  

Example: In the below example, the first function gives result 7 whereas the second function call will be “undefined” as we did not pass any second argument.

JavaScript
function add(a, b) {     return a + b }  console.log(add(5, 2)); // 7 console.log(add(5)); // NaN 

Output
7  NaN  

Method 10: Rest Parameter

In JavaScript, the rest parameter allows functions to accept an arbitrary number of arguments as an array, simplifying variable parameter handling and manipulation.

Syntax:

//... is the rest parameter (triple dots)  function functionname(...parameters) {      statement;  }  

Example: In this example, the sum function accepts an arbitrary number of arguments using the rest parameter ...numbers.

JavaScript
function sum(...numbers) {     let total = 0;     for (const num of numbers) {         total += num;     }     return total; }  console.log(sum(1, 2, 3)); 

Output
6  

Method 11: String.includes() Method

The includes() method in JavaScript is used with strings to check if a specified substring is present, returning true if found, false if not.

Syntax:

string.includes( searchvalue, start )  

Example: This method shows the basic use of the String includes() Method.

JavaScript
let str = "Welcome to GeeksforGeeks."; let check = str.includes("Geeks"); console.log(check); 

Output
true  

Method 12: String.startsWith() and String.endsWith() Methods

  • The startsWith() method in JavaScript checks if a string starts with a specified substring, returning true if matched, otherwise false.
  • The endsWith() method in JavaScript checks if a string ends with a given substring, returning true if matched, otherwise false.

Syntax:

str.startsWith( searchString , position )   // startsWith() method   str.endsWith(searchString, length)          // endsWith() method  

Example: Here is the basic example of above-mentioned method.

JavaScript
let str1 = "Hello, Geeks!";  console.log(str1.startsWith("Hello")); console.log(str1.startsWith("Geeks"));  console.log(str1.endsWith("Geeks!")); console.log(str1.endsWith("Hello")); 

Output
true  false  true  false  

Method 13: Array methods

  • Array from() Method: It converts array-like or iterable objects into a new array with optional mapping function.
  • Array keys() Method: It provides an iterator for array indices, allowing iteration over keys/indices in an array.
  • Array find() Method: It locates and returns the first array element satisfying a provided condition.
  • Array findIndex() Method: It retrieves the index of the first array element satisfying a given condition.

Example: In this example we are using the above mentioned methods one by one.

JavaScript
const languages = ["HTML", "CSS", "JavaScript", "React.js"];  // Using Array.from() to create a new array of lengths const lengths = Array.from(languages, lang => lang.length); console.log(lengths); // Outputs: [4, 3, 10, 7]  // Using Array.keys() to iterate over array indices for (const index of languages.keys()) {     console.log(`Index ${index}: ${languages[index]}`); }  // Using Array.find() to find the first language // with length greater than 5 const longLanguage = languages.find(lang => lang.length > 5); console.log(longLanguage); // Outputs: "JavaScript"  // Using Array.findIndex() to find the index of "React.js" const reactIndex = languages.findIndex(     lang => lang === "React.js");      console.log(reactIndex); // Outputs: 3 

Output
[ 4, 3, 10, 8 ]  Index 0: HTML  Index 1: CSS  Index 2: JavaScript  Index 3: React.js  JavaScript  3  

Method 14: New Math Methods

ES6 added the following methods to the Math object:

  • Math.trunc() Method: It removes decimal fractions, returning the integer part of a number, effectively truncating it.
  • Math.sign() Method: It returns the sign of a number as 1 (positive), -1 (negative), or 0 (zero).
  • Math.cbrt() Method: It calculates the cubic root of a number, returning the value that, when cubed, equals the input.
  • Math.log2() Method: It computes the base-2 logarithm of a positive number, indicating the power of 2 needed to obtain the input.
  • Math.log10() Method: It calculates base-10 logarithm of a positive number, representing power of 10 for the input.

Example: Here we are use Math.trunc() and Math.sign() method.

JavaScript
const num1 = [4.9, -7.2, 16, -25, 30, 100];  const truncatedNumbers = num1.map(num => Math.trunc(num)); console.log("Truncated:", truncatedNumbers);  const signValues = num1.map(num => Math.sign(num)); console.log("Sign:", signValues); 

Output
Truncated: [ 4, -7, 16, -25, 30, 100 ]  Sign: [ 1, -1, 1, -1, 1, 1 ]  

Example 2: In this example we are using Math.cbrt(),Math.log2() and Math.log10().

JavaScript
const num2 = [8, -27, 16];  const cbrtRoots = num2.map(num => Math.cbrt(num)); console.log("Cubic Roots:", cbrtRoots);  const log2Values = num2.map(num => Math.log2(Math.abs(num))); console.log("Log base 2:", log2Values);  const log10Values = num2.map(num => Math.log10(Math.abs(num))); console.log("Log base 10:", log10Values); 

Output
Cubic Roots: [ 2, -3, 2.5198420997897464 ]  Log base 2: [ 3, 4.754887502163468, 4 ]  Log base 10: [ 0.9030899869919435, 1.4313637641589874, 1.2041199826559248 ]  

Method 15: New Number Methods

  • Number.isInteger() Method: It checks if a value is an integer, returning true if it is, false otherwise.
  • Number.isSafeInteger() Method: It verifies if a value is within the range of safe integers, preventing precision loss.

Example: In this example we are using the above-mentioned method.

JavaScript
const num1 = 42; const num2 = 3.14; const num3 = 9007199254740992; // Largest safe integer  console.log(Number.isInteger(num1)); console.log(Number.isInteger(num2)); console.log(Number.isSafeInteger(num1)); console.log(Number.isSafeInteger(num3)); 

Output
true  false  true  false  

Method 16: New Global Methods

ES6 added 2 new global number methods:

  • isFinite() Method: It checks if a value is a finite number, returning true for numbers, excluding NaN and Infinity.
  • isNaN() Method: It checks if a value is Not-a-Number (NaN), returning true if it's NaN, false otherwise.

Example: In this example we are using the above-mentioned methods.

JavaScript
const var1 = 12; const var2 = "Geeks"; const var3 = NaN; const var4 = Infinity;  console.log(isFinite(var1)); console.log(isFinite(var2));  console.log(isNaN(var1)); console.log(isNaN(var2)); console.log(isNaN(var3));  console.log(isFinite(var3)); console.log(isFinite(var4));  

Output
true  false  false  true  true  false  false  

Method 17: Object Entries

Object.entries() converts object properties to an array of [key, value] pairs, enabling iteration and manipulation of object contents.

Syntax:

Object.entries( obj )  

Example: Here is the basic example of above-mentioned method.

JavaScript
// creating an object constructor // and assigning values to it const obj = { 0: 'adam', 1: 'billy', 2: 'chris' };  // Displaying the enumerable property [key, value] // pairs of the object using object.entries() method console.log(Object.entries(obj)[1]); 

Output
[ '1', 'billy' ]  



Next Article
JS 2016 or ECMAScript 2016

V

vishalkumar2204
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-basics

Similar Reads

  • JavaScript ES5 (JS 2009)
    JavaScript 2009 (ES5) refers to the fifth edition of the ECMAScript language specification, standardized in 2009. It introduced several features, like strict mode, new methods, JSON support, and improved syntax for better programming practices and compatibility across browsers. ECMAScript 5 (ES5) in
    7 min read
  • ES2015: Latest Version of JavaScript
    ES2015 is the latest version of JavaScript programming language. It is the first major upgrade to JavaScript since 1997. It was approved in June 2015 by ECMA international, an association responsible for approving ECMA standards which programming languages like JavaScript, CoffeeScript and TypeScrip
    4 min read
  • JS 2015 or ECMAScript 6 (ES6)
    JS 2015 (ES6) also known as ECMAScript 6 (ES6), ECMAScript 6 (ES6) is a significant update to JavaScript, introducing arrow functions, classes, template literals, let and const for variable declaration, enhanced object literals, destructuring, and more modern features for better code organization an
    10 min read
  • JS 2016 or ECMAScript 2016
    JavaScript 2016 (ES2016) is a modified version of ES2015 in which they introduced some new features like JavaScript Exponentiation (**) operator, JavaScript Exponentiation assignment (**=), and Array..includes() method for array element presence checking, enhancing calculations, and array operations
    2 min read
  • JS 2017 - ECMAScript 2017
    JavaScript (JS) 2017, or ECMAScript 2017, introduced some new features in JavaScript. It enhanced asynchronous programming with async functions, provided shared memory and atomics for improved concurrency, and introduced Object.values() and Object.entries() for streamlined object manipulation. These
    3 min read
  • JS 2018 - ECMAScript 2018
    JavaScript 2018 (ES9) or ECMAScript 2018 is a modified version of ES8, in which ES9 introduced new features like asynchronous iteration, rest/spread properties, and enhancements to regular expressions, further improving asynchronous programming, object manipulation, and string handling capabilities.
    4 min read
  • JS 2019 - ECMAScript 2019
    ECMAScript 2019, also known as ES10, introduced features like Array.flat(), Array.flatMap(), Object.fromEntries(), and Symbol. description, and some string methods, for enhancing JavaScript's capabilities and expressiveness. JavaScript 2019 (ES10) or ECMAScript 2019 new features are: Name Descriptio
    5 min read
  • JS 2020 - ECMAScript 2020
    JavaScript ECMAScript 2020 (ES11) introduced new features like optional chaining, nullish coalescing, dynamic import(), BigInt, and Promise.allSettled(), etc. enhancing language capabilities for modern web development needs. JavaScript 2020 (ES11) or ECMAScript 2020 new features are: BigInttype for
    5 min read
  • ECMAScript 2021 (JS 2021/2022)
    JavaScript in 2021/2022 continues to evolve, with ES2021/ES2022 bringing enhanced features like private class fields, promise improvements, and record data structures, boosting developer productivity and code quality. JavaScript New Features in ES2021Name Description Promise any(): Resolves if any P
    4 min read
  • New Features in ECMAScript 2021 Update
    ECMAScript is a part of JavaScript language which is mostly used in web technology, building websites, or web apps. ECMAScript is growing as one of the world's most widely used general-purpose programming languages. It is majorly used in embedding with web browsers and is also adopted for server and
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences