All about ES6 (Part 1)
Javascript for Web Developers
Introduction
JavaScript ES6 (also known as ECMAScript 2015 or ECMAScript 6) is the newer version of JavaScript that was introduced in 2015.
ECMAScript is a standard that provides the specification on how JavaScript programming language should work.
The topics we will cover in this article are :
Setup for JS and Hello World
Variables in JS
Template literals
let vs var vs const
Datatypes(table)
About each datatype
Setup for JS:
Open VS code and create one HTML and one javascript file:
Install Live Server extension in vs code:
In
index.html
add a script tag that will link with 1.js:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> //script tag added here <script src="./1.js"></script> </body> </html>
In 1.js write this :
console.log("Hello World");
Right click on VS code and open live server:
If you are in Mac use command : Cmd + Option + C
. Then open the console tab
If you are in Windows or Linux user : use the shortcut ctrl+shift+j
and then reload the page.
You will get the following output:
However, we can write Hello World in 3 different ways :
//using double quotes:
console.log("hello world");
//using single quotes:
console.log('hello world');
//using backticks
console.log(`hello world`);
Variables in JS
Variables are containers that can store some information
We can reuse that information later and change the information if required
// declare a variable
var firstName = "Amit";
// use a variable
console.log(firstName);
// change value
firstName = "Dinesh";
console.log(firstName)
Rules for naming variables in JS :
// rules for naming variables
// you cannot start with number
// example :-
// 1value (invalid)
// value1 (valid)
var value1 = 2;
console.log(value1);
// you can use only undersore _ or dollar symbol
// first_name (valid)
// _firstname (valid)
// first$name (valid)
// $firstname (valid)
// you cannot use spaces
// var first_name = "amit"; // snake case writing
// var firstName = "amit"; // camel case writing
// first name (invalid) // invalid as it contains spaces
// convention
// start with small letter and use camelCase
Template Literals
They are just string literals allowing embedded expressions denoted by the dollar sign and curly braces ${expression}. These literals are enclosed by the backtick character instead of double or single quotes.
let str = "World";
let message = `Hello ${str}`;
console.log(message); // Hello World
let vs var
The var
variables belong to the global scope when you define them outside a function.
When you declare a variable inside a function using the var
keyword, the scope of the variable is local. For example:
function increase() {
var count = 10;
}
console.log(count); //Output-> ReferenceError: count is not defined
Here, the 'count' variable is local
to the increase() function. It cannot be accessible outside of the function.
Let us take another example where we use var in a for loop:
for (var i = 0; i < 3; i++) {
console.log("Inside the loop:", i);
}
console.log("Outside the loop:", i)
//Output:
Inside the loop: 0
Inside the loop: 1
Inside the loop: 2
Outside the loop: 3
Here, the variable 'i' is a global
variable. Therefore, it can be accessed from both inside and after the for loop.
But if we use let
inside the for loop :
for (let i = 0; i < 3; i++) {
console.log("Inside the loop:", i);
}
console.log("Outside the loop:", i);
//Output:
Inside the loop: 0
Inside the loop: 1
Inside the loop: 2
Uncaught ReferenceError: i is not defined
As soon as we use let
inside the for loop the variable 'i' becomes block scoped(i.e. it can be only used within the for loop).
Hence we can say that let
is block scoped
whereas var is function scoped
Let us take another example:
let firstName ="Amit";
let firstName ="Rohit";
console.log(firstName);
//Output
Uncaught SyntaxError: Identifier 'firstName' has already been declared
var firstName="Amit";
var firstName="Rohit";
console.log(firstName);
//Output
Rohit
It indicates that we cannot declare the same variable more than once using let
within the same scope whereas the var
keyword allows for redeclaration within the same scope.
const
ES6 provides a new way of declaring a constant by using the const
keyword.
Once a variable is assigned using const
, its value cannot be reassigned or modified. It creates a read-only reference to a value. Any attempt to reassign a new value to a const
variable will result in an error.
For example:
// declaring constant
const pi = 3.14;
pi=22
console.log(pi);
//Output
Uncaught TypeError: Assignment to constant variable.
Like the let
keyword, the const
keyword declares block-scoped
variables.
For Example:
function example() {
if (true) {
const x = 10;
console.log(x); // Output: 10
}
console.log(x); // Error: x is not defined
}
example();
Datatypes in JS:
String
String is used to store text. In JavaScript, strings are surrounded by quotes:
Single quotes: 'Hello'
Double quotes: "Hello"
Backticks: `Hello`
// Strings const firstName = "Amit"; const lastName = "Patnaik"; const result = `Name: ${firstName} ${lastName}`; console.log(result); // Name: Amit Patnaik
Number
Number represents integer and floating numbers (decimals and exponentials).
const num1 = 5; //integer const num2 = 3.433; //decimal const num3 = 3e5; // exponent --> 3 * 10^5
A number type can also be
+Infinity
,-Infinity
, andNaN
(not a number).const num4 = 3 / 0; console.log(num4); // +Infinity const num5 = -3 / 0; console.log(num5); // -Infinity // strings can't be divided by numbers const num6 = "abc" / 3; console.log(num6); // NaN
BigInt
Maximum no. that can be stored in JS is:Number.MAX_SAFE_INTEGER
(253 - 1)Any integer greater than
Number.MAX_SAFE_INTEGER
may not be accurately represented, and there is a risk of losing precision or encountering unexpected behavior when performing calculations or comparisons with such large numbers.To store numbers greater than this we use
BigInt
.BigInt can be created in two ways : Using
BigInt()
function or by appendingn
to the end of an integer.For example:
let a=BigInt(78356783663636783638637863) // Using the BigInt function let b =78356783663636783638637863n //Appending n at the end of integer console.log(a); console.log(b); //Output: 78356783663636778873520128n 78356783663636783638637863n
Also mixing
BigInt
with other types will result in aTypeError
.For example:
let a=BigInt(78356783663636783638637863); let b =2n; console.log(a+b); //Adding 2 Big integers //Output 78356783663636778873520130n //no error
let a=BigInt(78356783663636783638637863); let b =2; console.log(a+b); //Adding a Bigint and non Bigint number //Output Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions
Boolean
This data type represents logical entities. Boolean represents one of two values:true
orfalse
.const loggedIn = true; const isAdmin = false; console.log(loggedIn); // Output: true console.log(isAdmin); // Output: false
undefined
If a variable is declared but the value is not assigned, then the value of that variable will be undefined.
let x; console.log(x); // undefined
However, we can assign undefined to a variable
let y = undefined; //assigning undefined to a variable console.log(y); // undefined
null
In JavaScript,
null
is a special value that represents empty or unknown value.Null means "No value at all" or "nothing" or "value unknown".
Null is assigned to a variable as a representation of no value.
Also
typeof null
isobject
const number = null; console.log(number); //null
Remember: By default JS never seta a value to null. Always it is done programmatically
Symbol
A value having the data type Symbol can be referred to as a symbol value. Symbol is an immutable primitive value that is unique.
// Two symbols with the same description const value1 = Symbol('hello'); const value2 = Symbol('hello'); let result = (value1 === value2) ? true : false; // false; // Note: Though value1 and value2 both contain 'hello', they are different as they are of the Symbol type.
Object
In JavaScript, the fundamental way that we group and pass around data is through objects.
const employee = { firstName: 'Amit', lastName: 'Patnaik', email: 'amitpatnaik4518@gmail.com' };
The
employee
variable is assigned an object using object literal notation{}
.The object has three properties:
firstName
,lastName
, andemail
.We will have a deep dive into Objects in upcoming blogs .