0% found this document useful (0 votes)
27 views

02 JavaScript Advanced Concepts Notes Lyst3413

selfishly only of ourselves, but we must seriously ponder how our actions will affect others. In The Plague, Dr Rieux is driven by the virtues of empathy, love and solidarity in his fight against the contagion. If we learn these lessons now in our moment of crisis, we may be better off

Uploaded by

Rajdip Mondal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

02 JavaScript Advanced Concepts Notes Lyst3413

selfishly only of ourselves, but we must seriously ponder how our actions will affect others. In The Plague, Dr Rieux is driven by the virtues of empathy, love and solidarity in his fight against the contagion. If we learn these lessons now in our moment of crisis, we may be better off

Uploaded by

Rajdip Mondal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Advanced Concepts

Symbol Data Type

The JavaScript ES6 introduced a new primitive data type called Symbol.

Symbols are unique and it can not be changed.

To create a new symbol, we use the global Symbol() function

const s = Symbol();
console.log(s); // Symbol()
console.log(typeof s); // symbol

const s1 = Symbol();
const s2 = Symbol();
console.log(s1 === s2); //false

The Symbol() function accepts a description as an optional argument.

const s = Symbol("GreatStack");
console.log(s); // Symbol(GreatStack)

Access Symbol Description:

const s = Symbol("GreatStack");
console.log(s.description); // GreatStack

Symbols can also be used as object keys.


This is useful when you want to assign a unique identifier to an object.

const id = Symbol("id");

const course = {
name: "JavaScript",
channel: "GreatStack",
[id]: 1234
}
console.log(course);
console.log(course[id]);

The for..in loop doesn’t include symbolic properties:

for(let key in course){


console.log(key);
} // name channel

Sharing Symbols / Global Symbols

const gs = Symbol.for("id");

The Symbol.for() method first searches for the symbol with the id key in the global symbol registry.
It returns the existing symbol if that is available.
Otherwise, the Symbol.for() method creates a new symbol, registers it to the global symbol registry
with the specified key

const gs = Symbol.for("id");
const gs2 = Symbol.for("id");

console.log(gs===gs2); // true, because it is same symbol

keyFor() method:

To get the key associated with a symbol, you use the Symbol.keyFor() method

console.log(Symbol.keyFor(gs)); // id
Arrow functions

Arrow functions are one of the popular features of ES6 syntax for writing JavaScript function
expressions.

// function expression
let add = function(a, b) {
return a + b;
}

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


console.log(add(5,6)); // 11

In single line, we don’t need to add return keyword.

Multiline Arrow Functions

let add = (a, b) => {


let sum = a + b;
return sum;
}
console.log(add(5,6)); // 11

arrow functions with no parameter:

let greet = () => console.log("GreatStack");


greet();

Or
let greet = () => {
console.log("GreatStack");
}
greet();

arrow functions with a single parameter:

let greet = (user) => {


console.log("Hello, " + user);
}
greet("GreatStack");

But instead of this we can write below code:

let greet = user => {


console.log("Hello, " + user);
}
greet("GreatStack");

When You Should Not Use Arrow Functions

An arrow function doesn’t have its own this value and the arguments object.

1. You should not use arrow function in Event handlers:

Because this.value in the event handler always returns undefined.


2. Not use arrow function in Object methods:

Because when you use the arrow function inside the object, it inherits the this value from the
enclosing lexical scope.

3. Not use arrow function in Prototype methods:

If you need to use this keyword in the Prototype method then you should not use arrow function.

4. Functions that use the arguments object:

Arrow functions don’t have the arguments object. Therefore, if you have a function that uses
arguments object, you cannot use the arrow function.
JavaScript Rest Parameters

The rest parameters help us to work with an indefinite number of parameters.


Rest parameters was introduced in ES6 version of JavaScript.

Example:

function add(a, b) {
return a + b;
}
console.log(add(1, 2, 3, 4, 5)); // 3

It adds only 2 values and ignore other arguments that are pass while calling add() function

The parameter (args) is prefixed with the three-dots ( ...). It’s called a rest parameter ( ...args).

function add(...args) {
let result = 0;
for (let arg of args) {
result += arg;
}
return result;
}
console.log(add(1, 2, 3)); // 6
console.log(add(1, 2, 3, 4)); // 10
console.log(add(1, 2, 3, 4, 5)); // 15

we have option to use some arguments in the variables and remaining arguments in rest parameters

function add(a, b, ...args) {


//...
}

Notice: The rest parameters must appear at the end of the argument list.

function add(a, ...args, ba) {


// error
}
JavaScript String and String Methods

In JavaScript, the strings are used for storing and manipulating text.

A string represents zero or more characters that are written inside quotes.

Strings are immutable. It means that if you modify a string, you will always get a new string. The
original string doesn’t change.

There are three ways we can use quotes.


Single quotes: 'Hello'
Double quotes: "Hello"
Backticks: `Hello`

let msg = "GreatStack";


let msg = 'GreatStack';
let msg = `GreatStack`;

You can also write a quote inside another quote. For example,

let msg = 'Channel name is "GreatStack".';


console.log(msg);

Later we will learn Backticks in details.

Special Characters

// \'
let msg = 'Channel\'s name is GreatStack.';
console.log(msg);

Multiline strings

// \n

let msg = 'Channel \n name is \n GreatStack.';


console.log(msg);

JavaScript String Length

let msg = "GreatStack ";


console.log(msg.length); // 11

Accessing characters

We can use square brackets with position [pos]


Position are index based that start from zero.

let msg = "GreatStack ";


console.log(msg[0]); // G
console.log(msg[1]); // r
console.log(msg[2]); // e
console.log(msg[9]); // k

converting a non-string value to a string


let value = 9;
let value2 = value.toString();
console.log(typeof value);
console.log(typeof value2);
console.log(value2);

strings are immutable. That means the characters of a string cannot be changed

let msg = "greatstack";


msg[0] = "G";
console.log(msg); // "greatstack"

JavaScript String Methods

We will learn about commonly used JavaScript String methods:

search() method:

The search() method accepts a regular expression and returns the index of the first match in a string:

let re = /[A-Z]/;
let msg = "hello, how are You";
let index = msg.search(re);
console.log(index);

The following example uses the search() method to return the first occurrence of any capital letter

includes() method:

check if a string contains a substring.

string.includes(searchString [,position])

The includes() method returns true if the search String found in the string; otherwise false.

The optional position parameter specifies the position within the string at which to begin searching
for the searchString. The position defaults to 0.

let msg = "hello, how are You";


let result = msg.includes("are");
console.log(result); // true

indexOf() method:

indexOf() returns the index of the first occurrence of substring (substr) in a string (str):

let msg = "Hello, How are you";


let index = msg.indexOf("How");
console.log(index); // 7

let msg = "Hello, How are you";


let index = msg.indexOf("how");
console.log(index); // -1 (not found) case-sensitivity

It accept one optional parameter to fromIndex


At this index search starts.
let msg = "Hello, How are you";
let index = msg.indexOf("H", 1);
console.log(index); // 7

toUpperCase() & toLowerCase():

let msg = "Hello, How are you";


let newMsg = msg.toUpperCase();
console.log(newMsg);

let msg = "Hello, How are you";


let newMsg = msg.toLowerCase();
console.log(newMsg);

trim() method:

use the trim() to remove whitespace from both sides of a string:

let msg = " GreatStack ";


let newMsg = msg.trim();
console.log(msg);
console.log(newMsg);

trimStart(): remove whitespace characters from the beginning


trimEnd(): remove whitespace characters from the end

charAt() method:

let msg = "GreatStack";


console.log(msg.charAt(0)); // G
console.log(msg.charAt(1)); // r

concat() method:

concat() method accepts a list of strings and returns a new string that contains the combined strings.

let msg = "Hello";


let msg2 = "World";
let newMsg = msg.concat(" ", msg2, "!");
console.log(newMsg);

replace() method:

It replace a substring in a string with a new one.

let newStr = str.replace(substr, newSubstr);

let msg = "Welcome to JS Tutorial";


let newMsg = msg.replace("JS", "JavaScript");
console.log(newMsg);

replaceAll() method:
replace all occurrences of a substring that matches a pattern with a new one

let msg = "Welcome to JS Tutorial, Learn Advance JS";


let newMsg = msg.replaceAll("JS", "JavaScript");
console.log(newMsg);
split() method: Divides a string into an array of substrings.

The split() accepts two optional parameters: separator and limit.

1> Separator : The separator determines where each split should occur in the original string.
2> Limit: The limit is zero or positive integer that specifies the number of substrings. The split() method
will stop when the number of substrings equals to the limit. If the limit is zero, the split() returns an
empty array.

let msg = "JavaScript Course By GreatStack";


let subStrings = msg.split(" ");
console.log(subStrings);
// ['JavaScript', 'Course', 'By', 'GreatStack']

With limit:
let msg = "JavaScript Course By GreatStack";
let subStrings = msg.split(" ", 2);
console.log(subStrings);
// ['JavaScript', 'Course']

substring() method: extract a substring from a string.

substring() returns the part of the string between the start and end indexes

Syntax:
str.substring(startIndex, endIndex)

startIndex: specifies the index of the first character to include in the returned substring

endIndex: substring doesn’t include the character at the endIndex.

let msg = "JavaScript Course By GreatStack";


let subStrings = msg.substring(0,4);
console.log(subStrings); // Java

let msg = "JavaScript Course By GreatStack";


let subStrings = msg.substring(4,10);
console.log(subStrings); // Script

If you remove the endIndex, the substring() returns the substring to the end of the string.

let msg = "JavaScript Course By GreatStack";


let subStrings = msg.substring(11);
console.log(subStrings);
// Course by GreatStack

let email = "[email protected]";


let domain = email.substring(email.indexOf("@") + 1);
let id = email.substring(0, email.indexOf("@"));
console.log(domain); // gmail.com
console.log(id); // greatstackdev

If startIndex is greater than the endIndex, the substring() swaps their roles: the startIndex becomes the
endIndex and vice versa.
If startIndex is less then zero, then considered as zero.
If endIndex is greater than length then considered as length.

slice() method: extract a part of a string.

slice() method extracts a portion of a string and returns it as a substring.

Syntax:
slice(start, end)

The slice() method has two optional parameters start and end.

let msg = "GreatStack";


let subStrings = msg.slice(0, 4);
console.log(subStrings); // Grea

It is similar to substring() method but the difference id:

The substring() method swaps its two arguments if indexStart is greater than indexEnd , meaning that
a string is still returned. The slice() method returns an empty string if this is the case.

let msg = "GreatStack";


let subStrings = msg.slice(4, 2);
console.log(subStrings); // empty

There is one more difference:

Negative arguments in substring() method is treated as zero.


But when we add negative value in slice() method, it makes it as:
str.length + start
str.length + end

let msg = "GreatStack";


let subStrings = msg.slice(-4, -2);
// 10-4 = 6
// 10-2 = 8
console.log(subStrings);
JavaScript Number and Formatting numbers

JavaScript number store both integers and floating-point values.

let a = 10;
let b = 10.15;

We can use exponential notation (e) to include too large or too small numbers.

// let million = 1000000;


let million = 1e6; // multiply by 1,000,000
console.log(million);

// let microsecond = 0.000001;


let microsecond = 1e-6; // divide by 1,000,000
console.log(microsecond);

Big Integers:

JavaScript introduced the bigint type starting in ES2022.

The bigint type stores whole numbers whose values are greater than 253 – 1.

A big integer literal has the n character at the end of an integer literal

let num = 9988776655443322n;


console.log(num);
console.log(typeof num); // bigint

Formatting numbers:

We have different method to format a number.

1. toFixed() method:

The toFixed() method format a number with a specified number of decimal points..

This method accepts an argument that indicates how many decimal points should be used.

let num = 10.006


console.log(num.toFixed(2)); // 10.01

num = 10.004;
console.log(num.toFixed(2)); // 10.00

// it is using rounding method.

2. toExponential() method:

The toExponential() method is used to format a number in exponential notation.

let num = 1000;


console.log(num.toExponential()); // 1e+3

num = 0.001;
console.log(num.toExponential()); // 1e-3
3. toPrecision() method:

The toPrecision() method is used to get a string representation of a number to the specified precision.

The precision argument determines the number of significant digits.

let num = 5.12345;


console.log(num.toPrecision()); // same as toString()
console.log(num.toPrecision(4));
console.log(num.toPrecision(3));
console.log(num.toPrecision(2));
console.log(num.toPrecision(1));

Results are in string type.

if you remove the precision argument, the toPrecision() method will behave like the toString()
method.
Boolean
Now we will learn about
JavaSctipt Bolean Type:

The JavaScript boolean primitive type has two literal values: true and false.

let subscribed = true;


console.log(typeof subscribed); // boolean

JavaScript allows to cast a non-Boolean value to a boolean value using built-in Boolean() function.

let value = "JavaScript";


let check = Boolean(value);
console.log(check); // true

let value = "";


let check = Boolean(value);
console.log(check); // false

let value = 5;
let check = Boolean(value);
console.log(check); // true

let value = 0;
let check = Boolean(value);
console.log(check); // false

If the value is :
Any non empty string
Non-zero number
Or Any object
Then Bloolean() function will convert it into true.

And if the value is:


empty string
Zero, NaN, Null or undefined
Then Boolean() function will convert it into false.

We can convert the boolean data into string using toString() method.

let x = true;
console.log(x, typeof x); // true 'boolean'

let y = x.toString();
console.log(y, typeof y); // true string
JavaScript Array and Array Methods

In JavaScript, an array is an ordered list of values. Each value is called an element specified by an
index.

We can use array for storing multiple values in a single variable.

There are 2 ways to create an array:

First one is array constructor:

let arr = new Array();


console.log(arr); // []

In practice, you will rarely use the Array() constructor to create an array.

The more preferred way to create an array is to use the array literal notation:

let arr = [];


console.log(arr); // [] empty array

let colors = ['red', 'green', 'blue'];


console.log(colors);

Accessing JavaScript array elements:


Now let’s see how to access JavaScript array elements

arrayName[index]

let colors = ['red', 'green', 'blue'];


console.log(colors[0]);
console.log(colors[1]);
console.log(colors[2]);

change the value of an element:

let colors = ['red', 'green', 'blue'];


colors[2] = "orange";
console.log(colors);

let colors = ['red', 'green', 'blue'];


colors[3] = "orange";
console.log(colors); // 4 elements array

Getting the array size:

let colors = ['red', 'green', 'blue'];


console.log(colors.length); // 3

There are some other uses of length property:

colors.length = 0
console.log(colors); // empty array

colors.length = 2
console.log(colors); // remove element

colors.length = 5
console.log(colors); // increase size with empty element

Array Methods:

Methods for Adding / removing elements:

push() method:

The push() method adds one or more elements to the end of an array and returns the new array’s
length.

let numbers = [10, 20, 30];


numbers.push(40);
console.log(numbers);

Push method returns the new length.

let length = numbers.push(40);


console.log(length);

add multiple elements using push() method:

let numbers = [10, 20, 30];


let length = numbers.push(40, 50);
console.log(length);
console.log(numbers);

We can append the elements of an array to another array using push() method:

let numbers = [10, 20, 30];


let newNumbers = [40, 50, 60];
for(let num of newNumbers){
numbers.push(num);
}
console.log(numbers);

unshift() method:

unshift() method adds one or more elements to the beginning of an array and returns the new array’s
length.

let numbers = [10, 20, 30];


let length = numbers.unshift(5);
console.log(length);
console.log(numbers);

pop() method:

pop() method removes the last element from an array and returns the removed element.

let numbers = [10, 20, 30];


let last = numbers.pop();
console.log(last); // 30
console.log(numbers); // [10, 20]
shift() method:

shift() method removes the first element from an array and returns that element.

let numbers = [10, 20, 30];


let first = numbers.shift();
console.log(first); // 10
console.log(numbers); // [20, 30]

splice() method:

JavaScript Array’s splice() method allows you to delete existing elements, insert new elements, and
replace elements in an array.

Deleting elements using splice() method:

// Syntax
Array.splice(position, num);

The position specifies the position of the first item to delete and the num argument determines the
number of elements to delete.

The splice() method changes the original array and returns an array that contains the deleted
elements.

let numbers = [10,20,30,40,50];


deletedNum = numbers.splice(0,2);

console.log(numbers); // [30, 40, 50]


console.log(deletedNum); // [10, 20]

Inserting elements using splice() method:

// syntax
Array.splice(position,0,new_1,new_2,...);

 The position specifies the starting position in the array that the new elements will be inserted.

 The second argument is zero (0) that instructs the splice() method to not delete any array
elements.

 The third argument, fourth argument, and so on are the new elements that are inserted into the
array.

splice() method actually changes the original array. Also, the splice() method does not remove any
elements, therefore, it returns an empty array

let numbers = [10, 20, 30];


numbers.splice(1,0,15,18);
console.log(numbers); // [10, 15, 18, 20, 30]

Replacing elements using splice() method:

The splice() method allows you to insert new elements into an array while deleting existing elements
simultaneously.
To do this, you pass at least three arguments with the second one that specifies the number of items
to delete and the third one that indicates the elements to insert.

let numbers = [10, 20, 30, 40];


numbers.splice(1,1,25);
console.log(numbers); // [10, 25, 30, 40]

slice() Method:

slice() method allows you to extract subset elements of an array and add them to the new array.

The slice() method accepts two optional parameters as follows:

slice(start, stop);

Start: index at which to start extraction


Stop: index at which to end extraction (extracts up to stop-1)

Example: Clone an array

let numbers = [10, 20, 30, 40];


newNumbers = numbers.slice();
console.log(newNumbers); // [10, 20, 30, 40]

Example: Copy a portion of an array

let numbers = [10, 20, 30, 40];


newNumbers = numbers.slice(1, 3);
console.log(newNumbers); // [20, 30]

High-order methods:

map() method:

JavaScript Array map() method allows you to transform elements in an array.


And store the result in new array.

let numbers = [10, 20, 30, 40];


let square = numbers.map(function(x){
return x * x;
});
// let sqrt = numbers.map(x => x * x)
console.log(square);

filter() method:

This method filter elements in an array

let numbers = [10, 20, 30, 40];


let newNumbers = numbers.filter(function(x){
return x > 20;
});
console.log(newNumbers); // [30, 40]

let arr = [10, "red", "green",20, true, 30];


let newArry = arr.filter(function(x){
if(typeof x == "number"){
return x;
}
});
console.log(newArry); // [10, 20, 30]

reduce() method:

We can use the JavaScript Array reduce() methods to reduce an array to a value.

let arr = [1, 2, 3, 4];


let sum = arr.reduce(function(previousValue, currentValue){
return previousValue + currentValue;
});
console.log(sum); // 10

There is one optional parameter (initialValue):


array.reduce(callbackFn [, initialValue])
let arr = [1, 2, 3, 4];
let sum = arr.reduce(function(x, y){
return x + y;
},100);
console.log(sum); // 110

reduceRight() method:

reduceRight() method starts at the last element and travels backward the first.

let arr = [1, 2, 3, 4];


let sum = arr.reduceRight(function(x, y){
return x + y;
});
console.log(sum); // 10

every() method:

every() method check whether all the array elements pass a test.

The every() method returns true if the callback function returns a truthy value for every array element;
otherwise, it returns false.

// syntax
array.every(callback[, thisArg])

thisArg is optional parameter, this value inside the callback function will reference the thisArg.

let arr = [1, 2, 3, 4];


let check = arr.every(function(x){
return x >=0 ;
});
console.log(check); // true

let arr = [1, -2, 3, 4];


let check = arr.every(function(x){
return x >=0 ;
});
console.log(check); // false
some() method:

some() method check if at least one element in an array passed a test.

The some() method executes the callback function once for each element in the array until it finds the
one where the callback function returns a true.

Then it will immediately returns true and doesn’t evaluate the remaining elements.

If no element causes the callback() to return true, the some() method returns false.

let arr = [-1, -2, 3, -4];


let check = arr.some(function(x){
return x >=0 ;
});
console.log(check); // true

let arr = [-1, -2, -3, -4];


let check = arr.some(function(x){
return x >=0 ;
});
console.log(check); // false

Here also we can add an optional parameter

// syntax
array.some(callback[, thisArg]);

This value inside the callback function will refer to the 2nd parameter.

sort() method:

JavaScript Array sort() method to sort arrays of numbers, string, and objects.

the sort() method changes the positions of the elements in the original array.

By default, the sort() method sorts the array elements in ascending order with the smallest value first
and largest value last.

let colors = ["red", "green", "blue", "yellow"];


colors.sort();
console.log(colors);

The sort() method casts elements to strings and compares the strings to determine the orders.

let num = [1, 4, 2, 3, 20, 30, 40, 10];


num.sort();
console.log(num); // [1, 10, 2, 20, 3, 30, 4, 40]

To fix this, we need to pass a compare function to the sort() method.

// syntax
array.sort(comparefunction)

The sort() method will use the compare function to determine the orders of elements.
The compare() function accepts two arguments a and b. The sort() method will sort elements based
on the return value of the compare() function with the following rules:
 If compare(a,b) is less than zero, then a will come first.
 If compare(a,b) is greater than zero, then b will come first.
 If compare(a,b) returns zero, then positions remains unchanged.

let num = [1, 4, 2, 3, 20, 30, 40, 10];


num.sort(function(a, b){
if(a > b) return 1;
if(a < b) return -1;
return 0;
});
console.log(num);

Simplify it

let num = [1, 4, 2, 3, 20, 30, 40, 10];


num.sort(function(a, b){
return a - b;
});
console.log(num); // [1, 2, 3, 4, 10, 20, 30, 40]

Using arrow function

let num = [1, 4, 2, 3, 20, 30, 40, 10];


// sort numbers in ascending order
num.sort((a, b) => a - b);
console.log(num);

let num = [1, 4, 2, 3, 20, 30, 40, 10];


// sort numbers in descending order
num.sort((a, b) => b - a);
console.log(num);

forEach() method:

We can use forEach() method to execute a function on every element in an array.

// syntax
Array.forEach(callback [, thisArg]);

thisArg is optional parameter.

This value inside the callback function refers to this 2nd parameter.

Let’s see one example to print each element of an array in console.

let numbers = [10, 20, 30, 40];


numbers.forEach(function(num){
console.log(num);
})

Multidimensional Array:

you can create a multidimensional array by defining an array of elements,


where each element is also another array.
// let score = [];
score = [
["HTML", 90],
["CSS", 80],
["JavScript", 95],
["React", 75]
]
// access an element of the multidimensional array

console.log(score[0]); ['HTML', 90]


console.log(score[0][0]); // HTML
console.log(score[0][1]); // 90

Now we have completed all the important JavaScript array methods.


Modules in JavaScript

JavaScript modules allow you to break up your code into separate files. This makes your code
organized and easier to maintain.

A module may contain variables, functions, classes etc (Et cetera).

We can export the variables, functions and classes from a module and reuse them in another module.

Let’s execute the modules on web browsers:

Create a new JavaScript file. Name: message.js

// message.js
export let msg = 'GreatStack';

// script.js
import { msg } from './message.js'
console.log(msg);

<!-- HTML -->


<script src="script.js" type="module"></script>

Other example:

// message.js
export let msg = 'GreatStack';

export function greet(name){


console.log("Hello " + name);
}

// script.js
import { msg, greet} from './message.js'
console.log(msg);
greet('GreatStack');

Export After Declarations:

// message.js
let msg = 'GreatStack';

function greet(name){
console.log("Hello " + name);
}
export { msg, greet };
There are two types of exports: Named Exports and Default Exports.

The above examples are name exports.


Now let’s see the example of default exports.

// message.js
export let msg = 'GreatStack';

export default function greet(name){


console.log("Hello " + name);
}
import default with any name.

// script.js
import greeting, { msg } from './message.js'
console.log(msg);
greeting('GreatStack');

There can be only a single export default per file.

Import an entire module as an object:

// message.js
export let msg = 'GreatStack';
export function greet(name){
console.log("Hello " + name);
}
// script.js
import * as msgModule from './message.js'
console.log(msgModule.msg);
msgModule.greet('GreatStack');

You must use the import or export statement outside other statements and functions.

JavaScript allows us to import or export the variables, functions or classes with a new name.

Example: export with new name

// message.js
let msg = 'GreatStack';
function greet(name){
console.log("Hello " + name);
}
export {msg as msg1, greet as greeting}

// script.js
import {msg1, greeting} from './message.js'
console.log(msg1);
greeting('GreatStack');

Import with new name:

// script.js
import {msg1 as newMsg, greeting as newGreet} from './message.js'
console.log(newMsg);
newGreet('GreatStack');

Export as default:

// message.js
let msg = 'GreatStack';
function greet(name){
console.log("Hello " + name);
}
export {msg as default, greet}
// script.js
import newMsg, {greet} from './message.js'
console.log(newMsg);
greet('GreatStack');

JavaScript modules executes in strict mode only. It means that any variables or functions declared in
the module won’t be added automatically to the global scope.

Now let’s understand what is,


Re-exporting a binding:

It’s possible to export bindings that you have imported. This is called re-exporting.

Example:

// message.js
export let msg = 'GreatStack';
export function greet(name){
console.log("Hello " + name);
}

// script.js
import {msg, greet} from './message.js';
export {msg, greet};

Or we can write is as

// script.js
export {msg, greet} from './message.js';
JavaScript Dynamic Imports

In the previous chapter we have studied the import, that is a static import.

In static import you have to added import statement at the top of the file

You can’t add the static import conditionally.


And Module path should be a string.

ES2020 introduced the dynamic import of the module via the function-like import().

Here is the syntax

import(moduleSpecifier);

The import() Expression allows you to dynamically import a module when needed.

moduleSpecifier can be an expression that evaluate to a string.


So you can determine the module path while execution of the code.

The import() returns a Promise that will be fulfilled once the module is loaded completely.

Example: load a module and display message when button clicked.

// message.js
export function show(){
console.log('Button Clicked!');
}

<!-- HTML -->


<button id="btn">Click Here</button>
<script src="script.js"></script>

// script.js
let btn = document.getElementById("btn");

btn.addEventListener('click', function(){

import('./message.js')
.then((msgModule)=>{
msgModule.show();
})
.catch((error)=>{
console.log(error);
})
})

We will learn about Promise in the upcoming tutorials.

Here, instead of writing the module path we can also write some expression that will evaluate to a
string.

So this was the dynamic import in JavaScript.


JavaScript Math Object

The JavaScript Math object allows you to perform mathematical tasks on numbers.

All methods and properties can be used without creating a Math object first.

Math Properties (Constants)

JavaScript provides 8 mathematical constants that can be accessed as Math properties:

// returns PI value
console.log(Math.PI);
// returns Euler's number
console.log(Math.E);
// returns the square root of 2
console.log(Math.SQRT2);
// returns the square root of 1/2
console.log(Math.SQRT1_2);
// returns the natural logarithm of 2
console.log(Math.LN2);
// returns the natural logarithm of 10
console.log(Math.LN10);
// returns base 2 logarithm of E
console.log(Math.LOG2E);
// returns base 10 logarithm of E
console.log(Math.LOG10E);

Math Methods:

There are 4 common methods to round a number to an integer:

Math.round(): returns the nearest integer:

console.log(Math.round(10.6)); // 11
console.log(Math.round(10.5)); // 11
console.log(Math.round(10.4)); // 10

console.log(Math.round(-10.6)); // -11
console.log(Math.round(-10.5)); // -11
console.log(Math.round(-10.4)); // -10

Math.ceil(): returns the number rounded up to its nearest integer.


It returns the smallest integer greater than or equal to a given number.

console.log(Math.ceil(10.6)); // 11
console.log(Math.ceil(10.4)); // 11
console.log(Math.ceil(-10.6)); // -10
console.log(Math.ceil(-10.4)); // -10

Math.floor(): returns the number rounded down to its nearest integer.


It returns the largest integer less than or equal to a given number.

console.log(Math.floor(10.6)); // 10
console.log(Math.floor(10.4)); // 10
console.log(Math.floor(-10.6)); // -11
console.log(Math.floor(-10.4)); // -11
Math.trunc(): returns the integer part of the number: (added in ES6 update)

console.log(Math.trunc(10.6)); // 10
console.log(Math.trunc(10.4)); // 10
console.log(Math.trunc(-10.6)); // -10
console.log(Math.trunc(-10.4)); // -10

Math.pow():

Math.pow(x, y): returns the value of x to the power of y:

console.log(Math.pow(3, 3)); // 27
console.log(Math.pow(4, 2)); // 16
console.log(Math.pow(2, 5)); // 32

Math.sqrt(): It returns the square root of the number:

console.log(Math.sqrt(16)); // 4
console.log(Math.sqrt(64)); // 8

Math.abs(x): returns the absolute (positive) value of x

console.log(Math.abs(10)); // 10
console.log(Math.abs(10.6)); // 10.6
console.log(Math.abs(-10.6)); // 10.6

Math.min() and Math.max():

Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments:
console.log(Math.min(0, 10, 30, 20, -10, -20)); // -20
console.log(Math.max(0, 10, 30, 20, -10, -20)); // 30

Math.random():

Math.random() returns a random number between 0 (inclusive), and 1 (exclusive):

console.log(Math.random());

Math.sign(x):

It returns 1 if x is positive
It returns -1 if x is negative
It returns 0 if x is null

console.log(Math.sign(10)); // 1
console.log(Math.sign(-10)); // -1
console.log(Math.sign(null)); // 0

Math.log2(x): returns the base 2 logarithm of x.

console.log(Math.log2(8)); // 3

Math.log10(x): returns the base 10 logarithm of x.


console.log(Math.log10(10000)); // 4

Math.sin(), Math.cos(), Math.tan():

It returns the sin, cos, tan value of the angle.


Angle is accepted in radians.

Convert degree to radians:

Angle in radians = Angle in degrees x PI / 180.

console.log(Math.sin(90 * Math.PI / 180)); // 1


console.log(Math.cos(0 * Math.PI / 180)); // 1
console.log(Math.tan(45 * Math.PI / 180)); // 0.999

So these are the important methods of the JavaScript Math Object.


JavaScript Date Objects

In JavaScript, there is a built-in object Date for handling all the date and time related operations.

creates a date object with the current date and time:

Date objects are created with the new Date() constructor.

let d = new Date();


console.log(d);
// Wed Sep 27 2023 15:53:09 GMT+0530 (India Standard Time)

By default, JavaScript will use the browser's time zone and display a date as a full text string:

Creating Date Object Using dateString:

let d = new Date("September 1, 2023 10:12:00");


console.log(d);
// Fri Sep 01 2023 10:12:00 GMT+0530 (India Standard Time)

// let d = new Date("2023-9-1 10:12:00");


let d = new Date("2023-9-1");
console.log(d);
// Fri Sep 01 2023 00:00:00 GMT+0530 (India Standard Time)

Create object using new Date(year, month, ...):

format: new Date(year, month, date, hours, minutes, seconds, ms)

 The year should consist of four digits ( for example, 2020);


 The counting of the month must start from 0 (0-11)
 The day of the month is the date parameter; if it is absent, you should assume 1.
 In case hours/minutes/seconds/ms is absent, you should assume them to be equal 0.

// let d = new Date(2023, 11);


// let d = new Date(2023, 11, 20);
// let d = new Date(2023, 11, 20, 10);
// let d = new Date(2023, 11, 20, 10, 9);
let d = new Date(2023, 11, 20, 10, 9, 20);
console.log(d);

Create date using new Date(milliseconds):

JavaScript stores dates as number of milliseconds since January 01, 1970.

Zero time is January 01, 1970 00:00:00 UTC.

One day (24 hours) is 86 400 000 milliseconds. (24 * 60 * 60 * 1000).

let d = new Date(24 * 60 * 60 * 1000);


console.log(d); // zero time + 24 hours

The toUTCString() method converts a date to a string using the UTC standard:

console.log(d.toUTCString());
The toDateString() method converts a date to a more readable format:

let d = new Date(2023, 11, 10);


console.log(d);
console.log(d.toDateString()); // Sun Dec 10 2023

toISOString() method:

console.log(d.toISOString()); // 2023-12-09T18:30:00.000Z

Date.parse(): method returns the number of milliseconds between the date and January 1, 1970:

let ms = Date.parse("2023 12 20");


console.log(ms); // 1703010600000

JavaScript Get Date Methods:

let d = new Date();

console.log(d.getFullYear());
console.log(d.getMonth());
console.log(d.getDate());
console.log(d.getDay());
console.log(d.getHours());
console.log(d.getMinutes());
console.log(d.getSeconds());
console.log(d.getMilliseconds());
console.log(d.getTime()); // ms since January 1, 1970
console.log(Date.now()); // ms since January 1, 1970

JavaScript Set Date Methods:

let d = new Date();

d.setFullYear(2020);
d.setFullYear(2020, 0, 1); // optionally month and day
d.setDate(15);
d.setMonth(11);
d.setHours(20);
d.setMinutes(20);
d.setSeconds(20);
d.setMilliseconds(20);
d.setTime(10000); // milliseconds since January 1, 1970

console.log(d.toDateString());

You might also like