30 Days of JAVASCRIPT #10/30

ES6+ Features Part-1

ES6+ is a version of JavaScript that introduces several new features to the language. In this blog post, we will discuss two of these features: let and const for variable declaration and template literals for string manipulation.

let and const

Before ES6, the only way to declare a variable in JavaScript was with the var keyword. However, var has some issues, such as hoisting and scope problems. ES6 introduced two new keywords for variable declaration: let and const.

  • let is used to declare variables that can be reassigned later. It has block-level scope, which means that it is only accessible within the block it was declared in.

  • const is used to declare variables that cannot be reassigned. It also has block-level scope.

Here is an example code that demonstrates the use of let and const:

// Using let
let x = 10;
if (true) {
  let x = 20;
  console.log(x); // Output: 20
}
console.log(x); // Output: 10

// Using const
const y = 10;
if (true) {
  const y = 20;
  console.log(y); // Output: 20
}
console.log(y); // Output: 10

In the above code, we declare two variables x and y using let and const, respectively. We then use them inside an if block and print their values. Finally, we print their values again outside the block. As we can see, the values of x and y inside the block are different from the values outside the block.

Template Literals

Template literals are a new way to create strings in JavaScript. They are enclosed in backticks (`) instead of single or double quotes. Template literals allow for string interpolation, which means that we can embed expressions inside a string. They also allow for multi-line strings without the need for escape characters.Here is an example code that demonstrates the use of template literals:

const name = "John";
const age = 30;
const profession = "developer";

console.log(`My name is ${name}. I am ${age} years old and work as a ${profession}.`);

In the above code, we declare three variables name, age, and profession. We then use them inside a template literal to create a string that prints out a message about the person. As we can see, we use ${} to embed expressions inside the string.In conclusion, let, const, and template literals are powerful features introduced in ES6+ that make JavaScript code more readable and maintainable.