Js Notes
Js Notes
Objects
Creating Objects:
let empty = {}; // An object with no properties
let point = { x: 0, y: 0 }; // Two numeric properties
let p2 = { x: point.x, y: point.y+1 }; // More complex values
let book = {
"main title": "JavaScript",
"sub-title": "The Definitive Guide",
for: "all audiences",
author: {
firstname: "David", surname: "Flanagan" }
};
Creating Objects with new:
let o = new Object(); // Create an empty object: same as {}.
let a = new Array(); // Create an empty array: same as [].
let d = new Date(); // Create a Date object representing the current time
let r = new Map(); // Create a Map object for key/value mapping
Prototypes:
Object.prototype._____
Object.create():
let o1 = Object.create({x: 1, y: 2}); // o1 inherits properties x and y.
o1.x + o1.y // => 3
To create or set a property, use a dot or square brackets as you would to query the
property, but put them on the lefthand side of an assignment expression:
Object Methods
toString() Method:
let text = 7;
let result = text.toString();
document.writeln(typeof text); //number
document.writeln(typeof result); //string
toLocaleString() Method :
The toLocaleString() method returns a Date object as a string, using locale settings.
The default language depends on the locale setup on your computer.
valueOf() Method :
toJSON() Method:
The toJSON() method returns a date object as a string, formatted as a JSON date.
The JSON.stringify() method converts JavaScript objects into strings.
ARRAYS
Array Literals:
var a = []; // An array with no elements
let primes = [2, 3, 5, 7, 11]; // An array with 5 numeric elements
let misc = [ 1.1, true, "a", ]; // 3 elements of various types
The values in an array literal need not be constants; they may be arbitrary expressions:
let base = 1024;
let table = [base, base+1, base+2, base+3];
Array literals can contain object literals or other array literals:
let b = [[1, {x: 1, y: 2}], [2, {x: 3, y: 4}]];
Spread Operator:
The “spread operator,” ..., to include the elements of one array within an array literal:
let a = [1, 2, 3];
let b = [0, ...a, 4]; // b == [0, 1, 2, 3, 4]
The spread operator is a convenient way to create a (shallow) copy of an array:
let original = [1,2,3];
let copy = [...original];
copy[0] = 0; // Modifying the copy does not change the original
original[0] // => 1
We can use a spread operator to turn any string into an array of single-character strings:
let digits = [..."0123456789ABCDEF"];
digits // => ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]
An easy way to remove duplicate elements from an array is to convert the array to a set and
then immediately convert the set back to an array using the spread operator:
Array() Constructor:
Array.of():
It is a method that creates and returns a new array, using its argument values (regardless of
how many of them there are) as the array elements.
Array.from():
let a = new Array(1,5.5,”babu”); //=> 1,5.5,”babu”
let copy = Array.from(a); //=> 1,5.5,”babu”
Reading and Writing Array Elements:
let a = ["world"]; // Start with a one-element array
let value = a[0]; // Read element 0
a[1] = 3.14; // Write element 1
let i = 2;
a[i] = 3; // Write element 2
a[i + 1] = "hello"; // Write element 3
a.length // => 4
Sparse Arrays
A sparse array is one in which the elements do not have contiguous indexes starting at 0.
Normally, the length property of an array specifies the number of elements in the array.
If the array is sparse, the value of the length property is greater than the number of
elements.
Array Length:
[].length // => 0: the array has no elements
["a","b","c"].length // => 3: highest index is 2, length is 3
The pop() method is the opposite of push(): it removes the last element of the array and
returns it, reducing the length of an array by 1.
The unshift() method to insert a value at the beginning of an array, shifting the existing array
elements to higher indexes.
The shift() method removes and returns the first element of the array, reducing the length
by 1 and shifting all elements down to an index one lower than their current index.
let a = [1,2,3];
delete a[1]; // a now has no element at index 1
a.length // => 3: delete does not affect array length
Iterating Arrays:
let x= [..."Hello world"]; // An array of letters
let a;
for( a = 0, len = x.length; a < len; a++) { }
a //=> 11
Multidimensional Arrays:
map():
The map() method passes each element of the array on which it is invoked to the function you
specify and returns an array containing the values returned by your function.
filter():
The filter() method returns an array containing a subset of the elements of the array on
which it is invoked.
find() returns the matching element, and findIndex() returns the index of the matching
element.
let a = [1,2,3,4,5];
a.findIndex(x => x === 3) // => 2; the value 3 appears at index 2
a.findIndex(x => x < 0) // => -1; no negative numbers in the array
a.find(x => x % 5 === 0) // => 5: this is a multiple of 5
a.find(x => x % 7 === 0) // => undefined: no multiples of 7 in the array
every() and some():
The every() method returns true if your predicate function returns true for all elements in
the array.
let a = [1,2,3,4,5];
a.every(x => x < 10) // => true: all values are < 10.
a.every(x => x % 2 === 0) // => false: not all values are even.
The some() method returns true if there exists at least one element in the array for which
the predicate returns true and returns false if the predicate returns false for all elements of
the array.
let a = [1,2,3,4,5];
a.some(x => x%2===0) // => true; a has some even numbers.
a.some(isNaN) // => false; a has no non-numbers.
The reduce() and reduceRight() methods combine the elements of an array, using
the function you specify, to produce a single value.
reduce() takes two arguments. The first is the function that performs the reduction
operation.
let a = [1,2,3,4,5];
a.reduce((x,y) => x+y, 0) // => 15; the sum of the values
a.reduce((x,y) => x*y, 1) // => 120; the product of the values
a.reduce((x,y) => (x > y) ? x : y) // => 5; the largest of the values
reduceRight() works just like reduce(), except that it processes the array from highest
index to lowest (right-to-left), rather than from lowest to highest.
flat() method creates and returns a new array that contains the same elements as the array
it is called on, except that any elements that are themselves arrays are “flattened” into the
returned array.
let a = [1, [2, [3, [4]]]];
a.flat(1) // => [1, 2, [3, [4]]]
a.flat(2) // => [1, 2, 3, [4]]
a.flat(3) // => [1, 2, 3, 4]
a.flat(4) // => [1, 2, 3, 4]
flatMap() method works just like the map() method except that the returned array is
automatically flattened as if passed to flat().
The concat() method creates and returns a new array that contains the elements of the
original array on which concat() was invoked, followed by each of the arguments to concat().
If any of these arguments is itself an array, then it is the array elements that are
concatenated, not the array itself.
let a = [1,2,3];
a.concat(4, 5) // => [1,2,3,4,5]
a.concat([4,5],[6,7]) // => [1,2,3,4,5,6,7]; arrays are flattened
a.concat(4, [5,[6,7]]) // => [1,2,3,4,5,[6,7]]; but not nested arrays
a // => [1,2,3]; the original array is unmodified
let q = []; // q == []
q.push(1,2); // q == [1,2]
q.shift(); // q == [2]; returns 1
q.push(3) // q == [2, 3]
q.shift() // q == [3]; returns 2
q.shift() // q == []; returns 3
When passing multiple arguments to unshift(), they are inserted all at once, which means
that they end up in the array in a different order than they would be if you inserted them
one at a time.
let a = []; // a == []
a.unshift(1) // a == [1]
a.unshift(2) // a == [2, 1]
a = []; // a == []
a.unshift(1,2) // a == [1, 2]
slice() :
let a = [1,2,3,4,5];
a.slice(0,3); // Returns [1,2,3]
a.slice(3); // Returns [4,5]
a.slice(1,-1); // Returns [2,3,4]
a.slice(-3,-2); // Returns [3]
splice():
let a = [1,2,3,4,5,6,7,8];
a.splice(4) // => [5,6,7,8]; a is now [1,2,3,4]
a.splice(1,2) // => [2,3]; a is now [1,4]
a.splice(1,1) // => [4]; a is now [1]
fill():
let a = new Array(5); // Start with no elements and length 5
a.fill(0) // => [0,0,0,0,0]; fill the array with zeros
a.fill(9, 1) // => [0,9,9,9,9]; fill with 9 starting at index 1
a.fill(8, 2, -1) // => [0,9,8,8,9]; fill with 8 at indexes 2, 3
copyWithin():
It modifies the array in place and returns the modified array, but it will not change the
length of the array. The first argument specifies the destination index to which the first
element will be copied. The second argument specifies the index of the first element to be
copied. If this second argument is omitted, 0 is used. The third argument specifies the end of
the slice of elements to be copied. If omitted, the length of the array is used.
let a = [1,2,3,4,5];
a.copyWithin(1) // => [1,1,2,3,4]: copy array elements up one
a.copyWithin(2, 3, 5) // => [1,1,3,4,4]: copy last 2 elements to index 2
a.copyWithin(0, -2) // => [4,4,3,4,4]: negative offsets work, too
Array Searching and Sorting Methods:
indexOf() and lastIndexOf():
let a = [0,1,2,1,0];
a.indexOf(1) // => 1: a[1] is 1
a.lastIndexOf(1) // => 3: a[3] is 1
a.indexOf(3) // => -1: no element has value 3
includes():
let a = [1,true,3,NaN];
a.includes(true) // => true
a.includes(2) // => false
a.includes(NaN) // => true
a.indexOf(NaN) // => -1; indexOf can't find NaN
sort():
let a = ["banana", "cherry", "apple"];
a.sort(); // a == ["apple", "banana", "cherry"]
reverse():
let a = [1,2,3];
a.reverse(); // a == [3,2,1]
toString() method works just like the join() method with no arguments.
[1,2,3].toString() // => "1,2,3"
["a", "b", "c"].toString() // => "a,b,c"
[1, [2,"c"]].toString() // => "1,2,c"