0% found this document useful (0 votes)
5K views

Js Notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5K views

Js Notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

INTRODUCTION

let x; // Declare a variable named x.


x = 0; // Now the variable x has the value 0
// JavaScript supports several types of values
x = 1; // Numbers.
x = 0.01; // Numbers can be integers or reals.
x = "hello world"; // Strings of text in quotation marks.
x = 'JavaScript'; // Single quote marks also delimit strings.
x = true; // A Boolean value.
x = false; // The other Boolean value.
x = null; // Null is a special value that means "no value."
x = undefined; // Undefined is another special value like null.
// JavaScript's most important datatype is the object. An object is a collection of
//name/value pairs, or a string to value map.
let book = { topic: "JavaScript", edition: 7 }; // The curly brace marks the end of the object.
// Access the properties of an object with . or []:
book.topic // => "JavaScript"
book["edition"] // => 7: another way to access property values.
book.author = "Flanagan"; // Create new properties by assignment.
book.contents = {}; // {} is an empty object with no properties.

// JavaScript also supports arrays (numerically indexed lists) of values:


let primes = [2, 3, 5, 7]; // An array of 4 values, delimited with [ and ].
primes[0] // => 2: the first element (index 0) of the array.
primes.length // => 4: how many elements in the array.
primes[primes.length-1] // => 7: the last element of the array.
primes[4] = 9; // Add a new element by assignment.
primes[4] = 11; // Or alter an existing element by assignment.
let empty = []; // [] is an empty array with no elements.
empty.length // => 0

// Functions are parameterized blocks of JavaScript code that we can invoke.


function plus1(x) {
return x + 1;
}
plus1(y) // => 4: y is 3, so this invocation returns 3+1

let square = function(x) { return x * x; };


square(plus1(y)) // => 16: invoke two functions in one expression
When we use functions with objects, we get methods:
let a = []; // Create an empty array
a.push(1,2,3); // The push() method adds elements to an array
a.reverse(); // Another method: reverse the order of elements

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

let o2 = Object.create(null); // o2 inherits no props or methods.


let o3 = Object.create(Object.prototype); // o3 is like {} or new Object().
Querying and Setting Properties
To obtain the value of a property, use the dot (.) or square bracket ([]) operators.
If using the dot operator, the righthand side must be a simple identifier that names the
property. If using square brackets, the value within the brackets must be an expression that
evaluates to a string that contains the desired property name:

let author = book.author; // Get the "author" property of the book.


let name = author.surname; // Get the "surname" property of the author.
let title = book["main title"]; // Get the "main title" property of the book.

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:

book.edition = 7; // Create an "edition" property of book.


book["main title"] = "ECMAScript"; // Change the "main title" property.

Object Methods
toString() Method:

let text = 7;
let result = text.toString();
document.writeln(typeof text); //number
document.writeln(typeof result); //string

The toString() method returns a string as a string.


The toString() method does not change the original string.
The toString() method can be used to convert a string object into a string.

toLocaleString() Method :

var d = new Date();


let text = d.toLocaleString();
document.writeln(text)

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 :

The valueOf() method is the default method for JavaScript strings.


This method returns the primitive value of a string.
It does not change the original string. It can be used to convert a string object into a string.

var text = new String("Hello World!");


var result = text.valueOf()
document.writeln(typeof text) //object
document.writeln(typeof result) //string

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}]];

let count = [1,,3]; // Elements at indexes 0 and 2. No element at index 1(undefined)


let undefs = [,,]; // An array with no elements but a length of 2

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:

let letters = [..."hello world"];


[...new Set(letters)] // => ["h","e","l","o"," ","w","r","d"]

Array() Constructor:

let a = new Array();


This method creates an empty array with no elements

let a = new Array(10);


Call it with a single numeric argument, which specifies a length.

let a = new Array(5, 4, 3, 2, 1, "testing, testing");


In this form, the constructor arguments become the elements of the new array.

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.of() // => []; returns empty array with no arguments


Array.of(10) // => [10]; can create arrays with a single numeric argument
Array.of(1,2,3) // => [1, 2, 3]

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

let a = [true, false]; // This array has elements at indexes 0 and 1


a[2] // => undefined; no element at this index.
a[-1] // => undefined; no property with this name.

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.

let a = new Array(5); // No elements, but a.length is 5.


a = []; // Create an array with no elements and length = 0.
a[1000] = 0; // Assignment adds one element but sets length to 1001.

Array Length:
[].length // => 0: the array has no elements
["a","b","c"].length // => 3: highest index is 2, length is 3

a = [1,2,3,4,5]; // Start with a 5-element array.


a.length = 3; // a is now [1,2,3].
a.length = 0; // Delete all elements. a is [].
a.length = 5; // Length is 5, but no elements, like new Array(5)

Adding and Deleting Array Elements:

let a = []; // Start with an empty array.


a[0] = "zero"; // And add elements to it.
a[1] = "one";
we can also use the push() method to add one or more values to the end of an array.
let a = []; // Start with an empty array
a.push("zero"); // Add a value at the end. a = ["zero"]
a.push("one", "two"); // Add two more values. a = ["zero", "one", "two"]

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:

let table = new Array(10); // 10 rows of the table


for(let i = 0; i < table.length; i++) {
table[i] = new Array(10); // Each row has 10 columns
}

// Initialize the array


for(let row = 0; row < table.length; row++) {
for(let col = 0; col < table[row].length; col++) {
table[row][col] = row*col;
}
}
Array Methods
Array Iterator Methods:
forEach():
forEach() invokes your function with three arguments: the value of the array element, the
index of the array element, and the array itself. If you only care about the value of the array
element, you can write a function with only one parameter— the additional arguments will
be ignored.

let data = [1,2,3,4,5], sum = 0;


// Compute the sum of the elements of the array
data.forEach(value => { sum += value; }); // sum == 15
// Now increment each array element
data.forEach(function(v, i, a) { a[i] = v + 1; }); // data == [2,3,4,5,6]

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.

let a = [1, 2, 3];


a.map(x => x*x) // => [1, 4, 9]: the function takes input x and returns x*x

filter():
The filter() method returns an array containing a subset of the elements of the array on
which it is invoked.

let a = [5, 4, 3, 2, 1];


a.filter(x => x < 3) // => [2, 1]; values less than 3
a.filter((x,i) => i%2 === 0) // => [5, 3, 1]; every other value

find() and findIndex() :

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.

reduce() and reduceRight():

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.

// Compute 2^(3^4). Exponentiation has right-to-left precedence


let a = [2, 3, 4];
a.reduceRight((x,y) => Math.pow(y,x)) // => 2.4178516392292583e+24

flat() and flatMap():

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().

let phrases = ["hello world", "the definitive guide"];


let words = phrases.flatMap(phrase => phrase.split(" "));
words // => ["hello", "world", "the", "definitive", "guide"];

Adding arrays with concat() :

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

Stacks and Queues with push(), pop(), shift(), and unshift() :

let stack = []; // stack == []


stack.push(1,2); // stack == [1,2];
stack.pop(); // stack == [1]; returns 2
stack.push(3); // stack == [1,3]
stack.pop(); // stack == [1]; returns 3
stack.push([4,5]); // stack == [1,[4,5]]
stack.pop() // stack == [1]; returns [4,5]
stack.pop(); // stack == []; returns 1

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]

Subarrays with slice(), splice(), fill(), and copyWithin():

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]

Array to String Conversions:


The join() method converts all the elements of an array to strings and concatenates them,
returning the resulting string. You can specify an optional string that separates the elements
in the resulting string. If no separator string is specified, a comma is used.
let a = [1, 2, 3];
a.join() // => "1,2,3"
a.join(" ") // => "1 2 3"
a.join("") // => "123"
let b = new Array(10); // An array of length 10 with no elements
b.join("-") // => "---------": a string of 9 hyphens

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"

You might also like