02 JavaScript Advanced Concepts Notes Lyst3413
02 JavaScript Advanced Concepts Notes Lyst3413
The JavaScript ES6 introduced a new primitive data type called Symbol.
const s = Symbol();
console.log(s); // Symbol()
console.log(typeof s); // symbol
const s1 = Symbol();
const s2 = Symbol();
console.log(s1 === s2); //false
const s = Symbol("GreatStack");
console.log(s); // Symbol(GreatStack)
const s = Symbol("GreatStack");
console.log(s.description); // GreatStack
const id = Symbol("id");
const course = {
name: "JavaScript",
channel: "GreatStack",
[id]: 1234
}
console.log(course);
console.log(course[id]);
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");
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;
}
Or
let greet = () => {
console.log("GreatStack");
}
greet();
An arrow function doesn’t have its own this value and the arguments object.
Because when you use the arrow function inside the object, it inherits the this value from the
enclosing lexical scope.
If you need to use this keyword in the Prototype method then you should not use arrow function.
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
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
Notice: The rest parameters must appear at the end of the argument list.
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.
You can also write a quote inside another quote. For example,
Special Characters
// \'
let msg = 'Channel\'s name is GreatStack.';
console.log(msg);
Multiline strings
// \n
Accessing characters
strings are immutable. That means the characters of a string cannot be changed
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:
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.
indexOf() method:
indexOf() returns the index of the first occurrence of substring (substr) in a string (str):
trim() method:
charAt() method:
concat() method:
concat() method accepts a list of strings and returns a new string that contains the combined strings.
replace() method:
replaceAll() method:
replace all occurrences of a substring that matches a pattern with a new one
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.
With limit:
let msg = "JavaScript Course By GreatStack";
let subStrings = msg.split(" ", 2);
console.log(subStrings);
// ['JavaScript', 'Course']
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
If you remove the endIndex, the substring() returns the substring to the end of the string.
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.
Syntax:
slice(start, end)
The slice() method has two optional parameters start and end.
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 a = 10;
let b = 10.15;
We can use exponential notation (e) to include too large or too small numbers.
Big Integers:
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
Formatting numbers:
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.
num = 10.004;
console.log(num.toFixed(2)); // 10.00
2. toExponential() method:
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.
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.
JavaScript allows to cast a non-Boolean value to a boolean value using built-in Boolean() function.
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.
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.
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:
arrayName[index]
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:
push() method:
The push() method adds one or more elements to the end of an array and returns the new array’s
length.
We can append the elements of an array to another array using push() method:
unshift() method:
unshift() method adds one or more elements to the beginning of an array and returns the new array’s
length.
pop() method:
pop() method removes the last element from an array and returns the removed element.
shift() method removes the first element from an array and returns that element.
splice() method:
JavaScript Array’s splice() method allows you to delete existing elements, insert new elements, and
replace elements in an array.
// 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.
// 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
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.
slice() Method:
slice() method allows you to extract subset elements of an array and add them to the new array.
slice(start, stop);
High-order methods:
map() method:
filter() method:
reduce() method:
We can use the JavaScript Array reduce() methods to reduce an array to a value.
reduceRight() method:
reduceRight() method starts at the last element and travels backward the first.
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.
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.
// 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.
The sort() method casts elements to strings and compares the strings to determine the orders.
// 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.
Simplify it
forEach() method:
// syntax
Array.forEach(callback [, thisArg]);
This value inside the callback function refers to this 2nd parameter.
Multidimensional Array:
JavaScript modules allow you to break up your code into separate files. This makes your code
organized and easier to maintain.
We can export the variables, functions and classes from a module and reuse them in another module.
// message.js
export let msg = 'GreatStack';
// script.js
import { msg } from './message.js'
console.log(msg);
Other example:
// message.js
export let msg = 'GreatStack';
// script.js
import { msg, greet} from './message.js'
console.log(msg);
greet('GreatStack');
// 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.
// message.js
export let msg = 'GreatStack';
// script.js
import greeting, { msg } from './message.js'
console.log(msg);
greeting('GreatStack');
// 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.
// 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');
// 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.
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
ES2020 introduced the dynamic import of the module via the function-like import().
import(moduleSpecifier);
The import() Expression allows you to dynamically import a module when needed.
The import() returns a Promise that will be fulfilled once the module is loaded completely.
// message.js
export function show(){
console.log('Button Clicked!');
}
// script.js
let btn = document.getElementById("btn");
btn.addEventListener('click', function(){
import('./message.js')
.then((msgModule)=>{
msgModule.show();
})
.catch((error)=>{
console.log(error);
})
})
Here, instead of writing the module path we can also write some expression that will evaluate to a
string.
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.
// 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:
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
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
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():
console.log(Math.pow(3, 3)); // 27
console.log(Math.pow(4, 2)); // 16
console.log(Math.pow(2, 5)); // 32
console.log(Math.sqrt(16)); // 4
console.log(Math.sqrt(64)); // 8
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() 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():
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
console.log(Math.log2(8)); // 3
In JavaScript, there is a built-in object Date for handling all the date and time related operations.
By default, JavaScript will use the browser's time zone and display a date as a full text string:
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:
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:
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
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());