Next-Gen Javascript

Features

Aarthini
10 min readApr 20, 2023
  • let and const
  • Arrow functions
  • exports and imports
  • Classes
  • Spread and Rest parameters
  • Destructuring
  • Template Literals
  • Array functions
  • Async Code

let and const

let

The let keyword is used to declare a block-scoped variable, which means that the variable is only accessible within the block in which it was declared. A block is defined by curly braces {}

let can be reassigned to other values, but they cannot be redeclared.

if (true) { 
let x = 10;
x=15; //reassigned
console.log(x); // outputs 15
}
console.log(x); // Uncaught ReferenceError: x is not defined
let y= 5;
let y= 10; // Error: Identifier 'x' has already been declared

const

The const keyword is used to declare a constant variable, which means that once a value is assigned to it, it cannot be reassigned. Like let, it is also block-scoped.

const variables cannot be redeclared, and neither can they be reassigned to other values.

const PI = 3.14;
PI = 3; // Uncaught TypeError: Assignment to constant variable.

if (true) {
const x = 10;
console.log(x); // outputs 10
}

console.log(x); // Uncaught ReferenceError: x is not defined
Difference between let, var, const

Arrow Functions

Arrow functions are a shorthand syntax for creating functions in JavaScript. It provide a more concise and expressive way to write function expressions.

Syntax
(parameters) => { statements }
  • Parameters: A list of input parameters for the function, enclosed in parentheses. If the function takes no parameters, you can omit the parentheses or use an empty pair of parentheses ().
  • Arrow: A fat arrow => that separates the parameters from the function body.
  • Function body: A set of statements that are executed when the function is called. If the function consists of a single expression, you can omit the curly braces {} and the return keyword.
// Function with no parameters
const greet = () => console.log('Hello!');

// Function with one parameter
const double = x => x * 2;

// Function with multiple parameters
const add = (x, y) => x + y;

// Function with multiple statements in the body
const printMessage = (name, message) => {
console.log(`${name}: ${message}`);
};

Arrow functions have some differences in behavior compared to regular function expressions, such as how they handle the this keyword. However, in general, they can be used interchangeably with regular functions in most cases.

Advantages:

  • Concise syntax: Arrow functions have a more concise syntax than traditional functions, making code easier to read and write. They typically require less code and fewer characters than traditional functions, which can help reduce the potential for errors.
  • Implicit return: Arrow functions automatically return the result of the expression or statement inside the function body, without the need for the return keyword. This can help reduce the amount of code needed to write a function and make the code more readable.
  • Lexical this: Arrow functions capture the value of this from the surrounding scope, rather than creating their own this value. This can help reduce confusion and errors when working with this in object-oriented programming.
  • No binding of this: Arrow functions do not bind their own this, so the value of this inside the function is the same as the value of this outside the function. This can help simplify code and make it easier to reason about.
  • Implicit binding of this: Arrow functions inherit the this value from their lexical enclosing scope, making it easier to access the value of this from parent functions or methods.

export and import

In JavaScript, the exports and imports statements are used to define and access modules, which are self-contained pieces of code that can be reused across multiple files and projects.

export:

The exports statement is used to define what parts of a module should be made available for use outside the module. It can be used to export functions, variables, and objects, as well as classes, interfaces, and other types of code.

// math.js
const add = (x, y) => x + y;
const subtract = (x, y) => x - y;

exports.add = add;
exports.subtract = subtract;

In this example, the add and subract functions are defined within the math.js module, and the exports statement is used to make them available for use outside the module.

import:

The imports statement is used to access the parts of a module that have been exported using the exports statement. It can be used to import functions, variables, and objects, as well as classes, interfaces, and other types of code.

// app.js
import { add, subtract } from './math.js';

console.log(add(1, 2)); // Outputs 3
console.log(subtract(5, 3)); // Outputs 2

In this example, the add and subract functions are imported from the math.js module using the import statement, and are then used within the app.js module.

Classes

In JavaScript, classes are a way of defining objects and their properties and behaviors in a structured and organized manner, making it easier to write and maintain complex code.

class MyClass {
constructor(param1, param2) {
this.property1 = param1;
this.property2 = param2;
}

method1() {
// Method implementation
}

method2() {
// Method implementation
}
}

In this example, the MyClass class is defined with a constructor that takes two parameters and assigns them to the class's property1 and property2 properties. The class also includes two methods, method1 and method2, which can be called on instances of the class.

  • To create an instance of a class, you can use the new keyword:
const myObj = new MyClass('value1', 'value2');

This will create a new instance of the MyClass with the property1 and property2 properties set to value1 and value2 , respectively.

  • Classes in JavaScript can also inherit properties and behaviors from other classes using the extends keyword:
class MySubClass extends MyClass {
constructor(param1, param2, param3) {
super(param1, param2);
this.property3 = param3;
}

method3() {
// Method implementation
}
}

In this example, the MySubClass class extends the MyClass class and adds a new property property3 and method method3. The super keyword is used to call the constructor of the parent class and pass in the param1 and param2 arguments. Instances of MySubClass will have access to the methods and properties defined in both MyClass and MySubClass.

Spread and Rest Parameters

In JavaScript, the spread and rest parameters are both ways of working with arrays and objects making it easier to write cleaner and more concise code.

Spread Operator:

  • The spread syntax is used to “spread” the elements of an array or object into another array or object.
  • It is denoted by the operator.
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const arr3 = [...arr1, ...arr2];

console.log(arr3); // Outputs [1, 2, 3, 4, 5, 6]

In this example, the spread syntax is used to combine the arr1 and arr2 arrays into a new array arr3.

  • Spread syntax can also be used with objects to create a new object that combines the properties of multiple objects.
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };

const obj3 = { ...obj1, ...obj2 };

console.log(obj3); // Outputs { a: 1, b: 2, c: 3, d: 4 }

In this example, the spread syntax is used to combine the obj1 and obj2 objects into a new object obj3.

Rest parameters:

  • The rest parameter, also denoted by the operator, is used to represent an indefinite number of arguments as an array.
  • It is typically used in function definitions to handle variable-length argument lists.
function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}

console.log(sum(1, 2, 3, 4)); // Outputs 10

In this example, the sum function takes an indefinite number of arguments using the rest parameter syntax. The numbers parameter is an array that contains all of the arguments passed to the function.

Destructuring

  • Destructuring is a way to extract values from arrays and objects and assign them to variables in a more concise way.
  • It can be used with arrays, objects, and even nested structures.

Destructing with an array

const arr = [1, 2, 3];

const [a, b, c] = arr;

console.log(a); // Outputs 1
console.log(b); // Outputs 2
console.log(c); // Outputs 3

In this example, the destructuring syntax is used to extract the values of the arr array and assign them to the variables a, b and c.

Destructing with an object

const obj = { a: 1, b: 2, c: 3 };

const { a, b, c } = obj;

console.log(a); // Outputs 1
console.log(b); // Outputs 2
console.log(c); // Outputs 3

In this example, the destructuring syntax is used to extract the values of the obj object's properties a, b and c and assign them to variables with the same names.

Destructing with nested structures

const obj = { 
a: 1,
b: {
c: 2,
d: 3
}
};

const { a, b: { c, d } } = obj;

console.log(a); // Outputs 1
console.log(c); // Outputs 2
console.log(d); // Outputs 3

n this example, the destructuring syntax is used to extract the values of the obj object's properties a, b.c and b.d and assign them to variables with the same names.

Template Literals

  • Template literals allows for easier string interpolation and multiline string formatting in JavaScript.
  • Instead of using the traditional single quotes or double quotes to define a string, template literals are enclosed in backticks (`). Within a template literal, variables or expressions can be inserted using ${…} syntax, which will be evaluated and replaced with their values at runtime.
const name = "John";
const age = 25;
const message = `My name is ${name} and I am ${age} years old.`;
console.log(message);//My name is John and I am 25 years old.
  • Template literals also make it easier to create multiline strings, as they can include line breaks and indentation without needing to use escape characters or concatenation.
const multiline = `
This is a
multiline
string.`;
console.log(multiline);

This will output:

  This is a
multiline
string.

Array functions

Array functions are used to maintain code that involves manipulating and transforming arrays and make it easier to write concise, efficient, and maintainable code when working with arrays.

  • Array.from(): This method creates a new array from an iterable object or array-like object, such as a NodeList or a string.
const str = 'hello';
const arr = Array.from(str);
console.log(arr); // Output: ['h', 'e', 'l', 'l', 'o']
  • Array.find(): This method returns the first element in an array that satisfies a specified condition. If no element satisfies the condition, it returns undefined.
const numbers = [1, 2, 3, 4, 5];
const evenNumber = numbers.find(num => num % 2 === 0);
console.log(evenNumber); // Output: 2
  • Array.findIndex(): This method returns the index of the first element in an array that satisfies a specified condition. If no element satisfies the condition, it returns -1.
const numbers = [1, 2, 3, 4, 5];
const evenNumberIndex = numbers.findIndex(num => num % 2 === 0);
console.log(evenNumberIndex); // Output: 1
  • Array.some(): This method returns true if at least one element in an array satisfies a specified condition, otherwise it returns false.
const numbers = [1, 2, 3, 4, 5];
const hasEvenNumber = numbers.some(num => num % 2 === 0);
console.log(hasEvenNumber); // Output: true
  • Array.every(): This method returns true if all elements in an array satisfy a specified condition, otherwise it returns false.
const numbers = [2, 4, 6, 8, 10];
const areAllEvenNumbers = numbers.every(num => num % 2 === 0);
console.log(areAllEvenNumbers); // Output: true
  • Array.includes(): This method checks whether an array includes a certain value, and returns true or false accordingly.
const numbers = [1, 2, 3, 4, 5];
const includesThree = numbers.includes(3);
console.log(includesThree); // Output: true

Async Code

Async Code features make it easier to write, read, and manage asynchronous code in JavaScript, improving the reliability and performance of web applications.

Promises:

  • Promises are a way to handle asynchronous operations in JavaScript.
  • A Promise represents a value that may not be available yet, but will be resolved at some point in the future.
  • Promises provide a cleaner way to handle callbacks and manage the flow of asynchronous code.
  • A Promise has three states:

Pending: The initial state of a promise. The promise is neither fulfilled nor rejected.

Fulfilled: The state of a promise when it is resolved successfully. The promise returns a value.

Rejected: The state of a promise when it fails to be resolved. The promise returns an error.

const myPromise = new Promise((resolve, reject) => {
// Do some asynchronous operation
setTimeout(() => {
const randomNum = Math.floor(Math.random() * 10);
if (randomNum < 5) {
resolve(randomNum); // fulfilled state
} else {
reject('Number is greater than or equal to 5'); // rejected state
}
}, 1000);
});

myPromise
.then((result) => {
console.log(result); // Output: A number less than 5
})
.catch((error) => {
console.error(error); // Output: Number is greater than or equal to 5
});

In this example, we created a new Promise that simulates an asynchronous operation by generating a random number between 0 and 9 after a 1-second delay. If the number is less than 5, the Promise is resolved with that number. If the number is greater than or equal to 5, the Promise is rejected with an error message.

We then handle the Promise using the .then() method, which is called when the Promise is fulfilled, and the .catch() method, which is called when the Promise is rejected. This allows us to easily handle the results of the Promise in a clear and concise way.

Async/await:

  • The async/await syntax simplifies the use of Promises by allowing developers to write asynchronous code that looks and feels like synchronous code.
  • The async keyword is used to define a function as asynchronous, and the await keyword is used to wait for a Promise to resolve before continuing execution.
async function getData() {
const response = await fetch('https://example.com/data');
const data = await response.json();
return data;
}

getData().then((data) => {
console.log(data);
}).catch((error) => {
console.error(error);
});

This code defines an asynchronous function called getData that fetches data from a URL and returns it as JSON. The await keyword is used to wait for the Promise returned by the fetch() method to resolve before continuing to parse the JSON response.

Difference of async/await and Promise

--

--

Aarthini
Aarthini

Written by Aarthini

Javascript,React Js, Java Developer

No responses yet