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

Javascript Notes

JavaScript is a programming language that can be used for both client-side and server-side applications. It allows developers to add interactivity to websites through features like modifying HTML content, handling events, and communicating with servers. Some common uses of JavaScript include powering interactive elements on websites, building single-page applications, and creating server-side applications using Node.js.

Uploaded by

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

Javascript Notes

JavaScript is a programming language that can be used for both client-side and server-side applications. It allows developers to add interactivity to websites through features like modifying HTML content, handling events, and communicating with servers. Some common uses of JavaScript include powering interactive elements on websites, building single-page applications, and creating server-side applications using Node.js.

Uploaded by

Sudharsan Leonic
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

JAVASCRIPT

What is JavaScript?

JavaScript is a programming language. It can be used on both client and


server-side.

Client-side: 

JavaScript we run in a browser that we call client-side JavaScript


example:-ReactJs, AngularJs, jQuery, and Vuejs 

Server-side: 

JavaScript we run outside the browser that we call server-side


JavaScript example: Nodejs, ExpressJs, NextJs, NestJs, and KoaJs.

Used to: 

 HTML gives structure to applications, CSS styles applications, and


JavaScript makes applications interactive.  

JavaScript is used to develop web applications mobile applications and


desktop applications.   

JavaScript is a case sensitive language

ECMAScript:

ECMA Stands for European computer manufacturing Association

ECMAScript: ECMA association added new concepts or advanced


concepts to the JavaScript is known as ECMAScript

The current version of ECMAScript is ECMAScript-12, popular version is


ES-6

How JavaScript works on the client side

function institute (name) {


*JavaScript, we run in a browser
document. write (name)
that we call client-side
} JavaScript. Browsers do not
understand JavaScript Browsers
institute (“Jspider”); only understand HTML

institute (“Qspider”);

institute (“Pyspider”)

*HTML understands JavaScript,


<! DOCTYPE html> so we link our JavaScript file to

<Html lang=’en’>
the HTML file using the script
tag
<Head>
*JavaScript engine is a program
</Head>
that is responsible for compiling
<Body> and executing JavaScript
<script src= ‘index.js’> </script> program

</Body> JavaScript engine first complies


with our JavaScript source file
line by line. If any syntax error
returns a compile-time error. If
there is no error, it converts the
source code to machine-
JIT co m piler Byte co de In terpreter
understandable code and sends
it to the interpreter.
Ja v a Sc r i p t e n g i n e

Web browser
The interpreter will run line by
line if logical errors return a
runtime error. If there is no
logical error, we can see the
result in a browser.

Output

All modern Browser have their JavaScript engines

Google Chrome: v8 engine.

Mozilla Firefox: spider monkey engine

Safari: JavaScript core engine

Microsoft Edge: Chakra engine

How JavaScript works on the server side

JavaScript we run outside the browser that we call server-side


JavaScript example: Nodejs, ExpressJs, NextJs, NestJs, and KoaJs.

JIT co m piler Byte co de In terpreter


Output
Source
code

Ja v a Sc r i p t e n g i n e
Everything works like the client side, but we run outside the browser by
using backend software like NodeJS, ExpressJs, NestJs, and NextJs.
output will be seen in the console

1. Install NodeJS software 

2. Open a command prompt and go to the file location of JavaScript and


run command node yourjavascriptfilename.js and hit enter. You can see
the output in the console

Example: PSC: \Users\ADMIN\One Drive\Desktop\Js> node index.js

Difference between java and JavaScript

JAVA JAVASCRIPT

Java is both compiled and JavaScript is only an interpreted


interpreted language. language.

Java is a static typed programming JavaScript is a dynamically typed


language because while storing the language because the programmer
data programmer must decide the gives the value interpreter will
kind of data type he is storing. the decide the data type while
stored data type cannot be executing
changed in future

int a = 20 ; let a = 20;


a=40; a=”sheela”;
a=”sheela”; // cannot be changed
in future.
Java is a strongly typed JavaScript is a weakly typed
programming language because we programming language
must follow the syntaxes otherwise
it will give an error let a = 20
console.log(a) // semicolon is not
int a = 20; provided then also compiler will
System.out.println(a) // semicolon ignore the minor mistakes and it
is not given it is going to give an will execute the program
error

java is only a server-side language JavaScript is both client and server


-side language

Java is multi-threaded language JavaScript is single threaded


language

Functions
What is the Function? And it’s advantages?

The Function is a block of code defined to perform a particular task or


operation.

Advantages

The main advantage of function is reusability.

And Code modularity (Bigger tasks can be divided into smaller tasks,
each small task can be defined as a function)
Syntax: - function add (par1, par2) {

return par1 + par2

let returnedResult = add (5, 3);

console.log (add (5, 3));

In JavaScript to declare a function we declare it with function keyword

2. function has a name; function name holds the whole structure of the

Function

3While passing parameters inside a parenthesis don’t use var, let, const
keyword

4. JavaScript function can return any value type including non-primitive


value and expressions

5.Whenever function is returning to access values you must store in a


variable or console.log ();

6. If the function is not returning anything it returns undefined

Types of function

        1. Named function or Regular function

        2. Anonymous function

       3. Arrow function

      4. Function expression
      5. Callback function

6. Self-invoking function

 1. Named function:- function which is declared with name is known as


named function

 Syntax: - function add () {

      }

 2. Anonymous function: - means function which is declared without


name is known as Anonymous function

Syntax:- function () {}

We pass Anonymous function to another function as an argument we


call it as callback function

Example: function addition (a, b) {

            console.log (a (5, 2) + b);

    }

addition (function (c, d) {return c * d}, 123);

If we are not passing anonymous function as an argument to another


function, we must store in a variable otherwise we will get syntax error:
Function statements require a function name

3. Arrow function:

 let add = () => {}

Arrow function introduced in ES-6


It is a shorter form of function it reduces number lines of code

We declare this function without function keyword

About parenthesis

If function has no parameter and function has more than one parameter
parenthesis are mandatory

If function has only one parameter parenthesis is not mandatory

About curly brackets and return keyword

if we have only statement and that statement is return statement than


curly brackets and return keyword is not mandatory

If function has more than one statement than curly brackets are
mandatory if function is returning something than return key mandatory

    

4. function expression:

Syntax:- anonymous function structure or arrow function structure is


assigning to variable that we call it as function expression

 let add = function (a, b) {console.log (a*b)}

add (20, 50) then variable holds the function structure

let multiply = (a, b) => {console.log (a-b)}

multiply (20, 2);

    
5. Callback function: -is a function which is passed as argument to
another function is called as callback function

call back function are used to handle Asynchronous type of data

 function addition (a, b) {

            console.log (a (5, 2) + b);

 addition (function (c, d) {return c * d}, 123);

6. Self-invoking function: - is also called as immediately invoked function


expression (IIFE)

This function gets invoke automatically once in the entire life cycle of
program

 IIFE protects the data

    

   Example 1: (function () {

            console.log ("hello");

        }());

            

  Example 2:- (function () {

       console.log ("hello");

     })();
Strings
What is the string?

In JavaScript zero or more characters enclosed between 'single quote'


and "double quote" or `in back-tics, ` we call it as a string.

Examples: -

 let string1 = ' ' // zero character

let string2 = 'Jspider is java training center' // written characters


between single quotes;

let string3 = "Qspider is testing training center" // written characters


between double quotes;

 let string4 = `Pyspider is a python training center ` // written


characters between back-tics

Note:-

JavaScript will misunderstand the same quotes within the same quoted
string it will give an error.

Error Example: 1.'Bhagat Singh's father'

2. "Bhagat" Singh "s father"

3. `Bhagat `Singh `s father`

To use the same quotes within the same quoted string use backslash
before that quote it will consider that quote as a character

Example: 1.'Bhagat Singh\'s father

2. "Bhagat\" Singh\"s father"

3. `Bhagat \`Singh\`s father`

You can write quotes within quotes, but they don't have to match with
the enclosed quotes

Examples: 1.'Abdul ` Kalama "s father';

2." Abdul` Kalama’s father";

3. `Abdul Kalama’s "father"`

String’s inbuilt methods

        1. indexOf ()

        2.lastIndexOf()

        3.search()

        4.startsWith()

        5.endsWith()

        6.includes()

        7.slice()

        8.substring()

        9.substr()

        10.charAt()

        11.charCodeAt()

        12.toUpperCase()
        13.toLowerCase()

        14.concat()

        15.trim()

        16.split()

        17.replace()

        18.replaceAll()

1. string. indexOf ('string value’, search position) :

This method accepts a string value, finds that the string value is in
which index in the specified string It returns the index position of the
first occurred match only. If string value is not matching it will return -1.

 Accepts:- two arguments

The first argument is string value

The second argument is the search position from which index you want
to search. The second argument is not mandatory, if you have not given
a second argument it is going to search from 0 th index position.

Example:-

let string1 = "Jspider is java training center java";

console.log (string1.indexOf('j')); // output 11

console.log (string1.indexOf('java')); // output 11

console.log (string1.indexOf('java', 20)); // output 31


console.log (string1.indexOf('Python')); // output is -1 because Python is
not present in the string1

2.string. lastIndexOf()  method returns the index of the last occurrence


of a specified text in a string. Works like indexOf (), but it begins search
from last

let string = "Jspider is java training center java";

console.log(string.lastIndexOf("java")); // output: 32 java is present in


the 11 index, but this method starts search from last

console.log(string.lastIndexOf("java",20)); // output: 11 second argument


specifies search position, so output is 11

4.string.includes("string value", position) method accepts string value if


that string value is present in the specified string it returns true if a
string value is not present it returns false

The second argument specifies the position to start the search.

let string = "Jspider is java training center";

console.log (string. includes ("java")); //output:- true

console.log(string. includes("java", 15)); //output:-false the second


argument specifying search from 15 index after 15 index Java is not
present, so it is returning false

5.str.startsWith(“string value”) method returns true if a string begins


with a specified value, otherwise false: */
let str = "Jspider is java training center";

console.log(str.startsWith("Jspider")); // output:- true

console.log(str.startsWith("Qpsider")); //output:- false

6.str.endsWith(“string value”) method returns true if a string ends with


a specified value, otherwise false: */

let str = "Jspider is java training center";

console.log(str.endsWith("center")); // output:- true

console.log(str.endsWith("Qspider")); //output:- false

7.string .slice(‘start position’, ‘end position’)

slice() method is to slice or extract content from an existing string

It does not slice the original string. slice() method creates a new string.

 Arguments:-accepts two arguments 

The first argument is to specify the start index position for the slice

The second argument is to specify the end index position for the slice.
slice () method does not include the last index character while slicing

Examples:

let string1 = "Jspider is java training center";

console.log (string1.slice ()); // output: - Jspider is java training center


(If we have not given any arguments, it extracts the whole string.)

console.log (string1.slice (10)); // output: - java training center (If we


have given only argument, it considers it as the start position. from that
start position, and it will slice until the end of the string)

console.log (string1.slice (11, 17)); //output:-java t (if we have given two


arguments, it will slice from the start position to the end position. but it
will not consider the end position character)

console.log (string1.slice (-10, -2)) // output: - ing cent (this method


accepts negative indexes also. Negative index starts from -1)

8.string .substring(‘start position’, ‘end position’);

substring () method works like slice() method, but it considers negative


value as 0

let string1 = "Jspider is java training center";

console.log(string1.substring()); // output:- Jspider is java training


center

console.log(string1.substring(5)); // output:- er is java training center

console.log(string1.substring(5, 15)); // output:- er is java


console.log(string1.substring(-10, 30)); // output: this method considers
negative value as zero

console.log(string1.substring(-10, -16)); // this method considers


negative value as zero

9.string .substr(‘start position’, length);

substr() method works like slice() method but it second parameter


specifies the length of character you want extract

examples

let string1 = "Jspider is java training center";

console.log (string1.substr()); // output:-Jspider is java training center


 no arguments mean extracts whole string content

console.log (string1.substr(10)); // output:-java training center  only one


argument means it slices from 10th index to until last index of string

console.log (string1.substr(10, 15)); //output:-java training  first


argument specifies start index position, and second argument specifies
length of characters you want slice

console.log (string1.substr(-20, 5)); // output: -java  this method accepts


a negative value as the start position to extract

10. charAt(index number):- method takes index number from that it


returns a character which is in that index

 let string1 = "Jspider is java training center";

console.log (string1.charAt()); //output: J no argument means false,


false value is 0 so it returns the first-string character

console.log (string1.charAt(5)); //output: e method returns the character


at a specified index in a string

console.log (string1.charAt(50)); // if character is not present in that


index it returns empty space

11. charCodeAt(index number):-

charCodeAt (index number) method accepts index number returns


ASCII value of that character

let string1 = "ABCDdef*";

console.log (string1.charCodeAt(1)); // output : 66

console.log (string1.charCodeAt()); // output : 65

console.log (string1.charCodeAt(7)); // output : 42C

 12. string. toUpperCase() :-

Method converts lowercase string to uppercase it will not change the


actual string, it creates a new string 

let institute = 'jspider';

let result = institute.toUpperCase();

console.log (result); // output: JSPIDER

console.log (institute); // output: jspider the actual string is not changed


13. string. toLowerCase() :-

Method converts uppercase string to lowercase it will not change the


actual string, it creates a new string 

  let institute = 'JSPIDER';

 let result = institute.toLowerCase();

 console.log (result); // output: jspider

console.log (institute); // output: JSPIDER the actual string is not


changed

 14. string. concat() :-

Method joins two or more strings this method creates a new string it will
not change the original strings

let institute = "Jspider "

let sufixText = "Is Java training center";

let place = " Basavanagudi Bengaluru";

let concatedString = institute.concat(sufixText, place);

console.log (concatedString); // output: - Jspider Is Java training center


Basavanagudi Bengaluru

console.log (institute); //output:- Jspider

console.log (sufixText); // output:-Is Java training center


console.log (place); // output: - Basavanagudi Bengaluru

15. string.trim() method removes white space from both the side of the
string

 let string1 = "     Jspider is java training center    ";

let result = string1.trim();

console.log (string1); // output: - Jspider is java training center   original


string

console.log (result); //output:-Jspider is java training center trim ()


method removed white space from both the side of the string

16.string.split(' * ') method converts string into an array

This method accepts separator, if we have given a separator split ()


method will split at that place makes it as an array element

If we have not given any separator, it will make it as arrays single


element

let string1 = "Jsp*id*ers";

console.log (string1.split ('*')); //output ['Jsp', 'id', 'ers'] splits in Axtrics


('*')

let string2 = "Java_training_center";

console.log (string2. split ("_")); // output ['Java', 'training', 'center']


splits in under score ('_')
let string3 = "Jspiders";

console.log (string3. split ('')); // output ['J',’s’, 'p', 'i',’d’, 'e', 'r',’s’] if we
have given only '' quotes split () method makes every character as an
array element

console.log (string3.split ()); //output ['Jspiders'] if we have not given


any separator split () method makes whole string as array single
element

17.string.replace ('old value', 'new value') method replaces a specified


value with another value in a string:  

let string1 = "Jspider is  a java training center Jspider Basavanagudi


JSPIDER ";

console.log (string1. replace ('Jspider', "QSPIDER")); output:  QSPIDER


is a java training center Jspider Basavanagudi JSPIDER replace ()
method replaced only the first match, and it is case sensitive also

To replace multiple and to consider any case use regular expression

console.log (string1.replace (/Jspider/ig, "QSPIDER")); //output:


QSPIDER is a java training center QSPIDER Basavanagudi QSPIDER
Back-ticks or template strings or template literals

introduced in ECMAScript-6

let strTemplate1 = `Abdul Kalama’s father name is "Jainulabiddin


Marakayar"` // we can use double quote and single quotes in back-ticks

let strTemplate2 = `Avul Pakir Jainulabiddin

Abdul Kalama was an Indian aerospace

scientist who served as the 11th President of India from 2002 to 2007`
// allow us to write multiline code

let strTemplate3 = `

        <div class="parent1">

            <h1>heading tag</h1>
            <p>Paragraph tag</p>

        </div>

        <div class="parent2">

            <h1>heading tag</h1>

            <p>Paragraph tag</p>

        </div>

        `// we can write multiline html codes

        let value1 = 55;

        let value2 = 65

let result = `total value is ${value1 + value2}`

      console.log (result); //output:- total value is 120 using ${} we can


perform expression and we can call variable name

Numbers
JavaScript has only one type of number, it can be written with or without
a decimal point

let num1 = 12; //without decimal point(integer number)

let num2 = 12.55 // with decimal point(floating number)

Extra-large and an extra small number can be written with scientific


notation (exponential notation)

let num3 = 125e5;


let num4 = 125e-5;

console.log (num3); // output: - 12500000

console.log (num4); // output: - 0.00125

Integer numbers are accurate up to 15 digits

let num5 = 999999999999999;

console.log (num5); // 15 digits number output: - 999999999999999

let num6 = 9999999999999999;

console.log (num6); // 16 digits number output: -


10000000000000000

In JavaScript string concatenation and addition has the same operator


(+) numbers adding with a string will be string concatenation.

console.log (20 + 20); // output: - 40 number + number =


number

console.log ('20' + '20'); // output: - 2020 string + string = string


concatenation

console.log ('20' + 20); //output:- 2020 strings + number = string


concatenation

console.log (20 + '20'); //output:- 2020 numbers + string = string


concatenation

1.num.toExponential () method returns a string with a rounded number


written using exponential notation

The parameter defines the number of characters after the decimal point.

let num = 12.5969;

console.log (num.toExponential ()); //output:- 1.25969e+1


console.log (num.toExponential (2)); //output:- 1.26e+1   parameter
decided number of characters after decimal point

2.num.toFixed() method returns string the parameter defines the length


of character after the decimal point.

num.toExponential (2) is perfect for working with money

let num = 150.599;

console.log (num.toFixed()); //output:- 151 no parameter means no


character after decimal point

console.log (num.toFixed(2)); // output:- 150.60

3.num.toPrecision() method returns string, parameter defines the length


of characters

console.log (num.toPrecision(3)); //output 5.23e+6

console.log (num.toPrecision(1)); //output 5

Number () method used to convert string number to pure number

 console.log (Number ("35")); // output 35 converted string to number

console.log (Number ("  35")); // output 35 spaces are allowed and


converts string to number

console.log (Number (" 35  ")); // output 35 spaces are allowed and


converts string to number

console.log (Number (" 15.8")); // output 15.8

parseInt() parses a string and returns a whole number. Spaces are


allowed. Only the first number is returned

console.log (parseInt ("15.8")); // output: 15


console.log (parseInt ("  15.8 ")); // output 15 spaces are allowed

console.log (parseInt ("55.8 rupees")); // output 55 the first number is


returned

console.log (parseInt ('total 55')); // output NaN

parseFloat() parses a string and returns a number. Spaces are allowed.


Only the first number is returned

onsole.log (parseFloat ('10.5')); //output:- 10.5

console.log (parseFloat ("  20.8")); // output:- 20.8 Spaces are allowed

console.log (parseFloat ('10.5 years')); // output: - 10.5 only the first


number is returned

console.log (parseFloat (‘years 10’)); // NaN

NaN: - Not a Number, whenever we are operating with the number and
character JavaScript, returns NaN

console.log (10 / "arun"); //output NaN

inNaN():-You can use the global JavaScript function isNaN() to find out
if a value is a not a number

console.log (isNaN (10 / "ARUN")) // when passed value is not a number


returns true

console.log (isNaN(20)); // it is number so false


Array¬
JavaScript array is a collection of homogeneous or heterogeneous elements.

Array creation : to create an array use array literal [] and store elements in
between array literal each element separated by comm

let employeeList = ["Ravi", "Anand", "Laxmi", "Karan", "Abdul", "Sagar"]; //


homogeneous array (same type of element)

let list = [1, 2, 3, { name: "arun", lastName: "sagar", age: 25 }, "sagar", [10, 11, 12],
100, 500] // heterogeneous element (different types of elements)

to check how many elements are in an array use length property

console.log(employeeList. length); // output : 6

console.log(list.length);// output : 8

Read ( to read array element use index number, array's first element will be in
0th index position and array's last element will be stored in array.length-1 )

let array = [200, 300, 400, 500, 600,]

        //            0    1     2     3   4

console.log(array[0]); // output : 200

console.log(array[1]); // output : 300

console.log(array[4]); // output : 600

Update

array[0] = "Kalam";

array[3] = "Subhash chandra";

console.log(array); // output: ['Kalam', 300, 400, 'Subhash chandra', 600]

Adding new element

array[5] = 55;

array[6] = 100;

console.log(array); // output : ['Kalam', 300, 400, 'Subhash chandra', 600, 55,


100]
array.pop()

 Used:- the pop() method is used to remove the last element from the
array.

Argument:- This method accepts 0 arguments.

Return: pop()  method returns the removed element from the array

Affects: pop()  method affects the original array

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

console.log(numbers); // before pop() output:-[1, 2, 3, 4, 5]

let res = numbers.pop()

console.log(numbers); //after pop() output:-[1, 2, 3, 4]

console.log(res); // pop() returns removed element output:- 5

 array.shift()

 Used:- shift() method removes the first element from an array.

Arguments:-  shift() method has 0 arguments or no arguments.

Returns:- This method returns the removed element from the array.

Affects:-  This method affects the original array.

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

console.log(numbers); // before shift()  output :- [1, 2, 3, 4, 5]

let result = numbers.shift();

console.log(numbers); // after shift() output :- [2, 3, 4, 5]


console.log(result); // returns removed element from the array output:- 1

array.push()

Used: - push() method adds new elements at the end of the array.

Arguments: - this method accepts n number of arguments, where


arguments are the new elements added to the array.

Returns: this method returns the updated length of an array.

Affects:- push() method affects original array

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

console.log(numbers); //before push() output:- [1, 2, 3, 4]

let result = numbers.push(10, 11, 12, 50);

console.log(numbers); // after push() output :- [1, 2, 3, 4, 10, 11, 12, 50]

console.log(result); // this method returns updated array length output:-


8

array.unshift()

Used:- unshift method adds new elements at the beginning of an array.

Arguments:- this method accepts n number of arguments, where


arguments are the new elements added to the array.

Returns:- this method returns updated array length.

Affect:- this method affects the original array.


let numbers = [100, 200, 300, 400, 500];

console.log(numbers); // before unshift() output:- [100, 200, 300, 400,


500]

let result = numbers.unshift(90, 91, 92, 93, 94, 95, 96);

console.log(numbers); //after unshift() output:- [90, 91, 92, 93, 94, 95,
96, 100, 200, 300, 400, 500]

console.log(result); // method returns updated array length output:- 12

array.splice(position, delete, add.....)

Used:- splice() method is used to add or delete the elements from an


existing array based on the index position.

Arguments:- this method takes n number of arguments,

the first argument: where the first argument is the index position from
where you want to add or delete the elements.

The second argument specifies the number of elements you want to


delete,

From the third argument all the arguments are the new elements added
to the array,

Returns:- this method returns an array of removed elements.

Affects:- this method affects the original array.

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];

console.log(numbers); // before splice() output:-[1, 2, 3, 4, 5, 6, 7, 8, 9]

let result = numbers.splice(2, 3, "arun", 'karana');


console.log(numbers); // after splice() output:-[1, 2, 'arun', 'karana', 6, 7,
8, 9] from 2nd index 3 elements are deleted[3,4,5] and arun and karan
added

console.log(result); // returns an array of removed elements [3, 4, 5]

let numbers2 = [50, 60, 70, 80, 90, 100];

console.log(numbers2.splice(3)); // If you have passed only one


argument, it deletes the elements from that index until the end of an
array. output :- [80, 90, 100]

let numbers3 = [100, 200, 300, 400, 500, 600];

console.log(numbers3.splice(2, 0, 'new', 'elements')); ] // You don't want


to remove any elements pass second argument as 0

console.log(numbers3); // output:-  [100, 200, 'new', 'elements', 300,


400, 500, 600

array.fill(new element, start position, end position)

Use: -This method fills the array with new element in a specified index

Arguments: - This method accepts three arguments

the first argument is the new element you want to fill

the second argument is the start position from where you want to fill

the third argument is the end position till where you want to fill

Affects: - This method affects the original array.

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

console.log(num1); // output before fill [1, 2, 3, 4, 5]

num1.fill() // If you have not passed any arguments this method fills the
whole array with the undefined value.

console.log(num1); //output:- [undefined, undefined, undefined,


undefined, undefined]

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

num2.fill(5) //if you ignore second and third argument then it fills the
new element from 0th index to till the end of an array

console.log(num2); // output:- [5, 5, 5, 5, 5]

let num3 = [200, 300, 400, 500]

num3.fill('ele', 2); // If you have ignored the third argument, it fills the
new element from the start index to till the end of the array

console.log(num3); // output [200, 300, 'ele', 'ele']

let num4 = [12, 13, 14, 15, 16];

num4.fill('ravi', 1, 3);

console.log(num4); // output [12, 'ravi', 'ravi', 15, 16]

array. reverse()

Used:- The reverse() method is to reverse the array of elements.

Argument: this method has no arguments

Returns:- this method returns reversed array

Affects:- affects the original array

let num = [1, 2, 3, 4, 5, 6];

num. reverse();
console.log(num); //output [6, 5, 4, 3, 2, 1]

array.indexOf()

Used:- this method is used to find out the index position of an array
element.

Arguments:- This method accepts two arguments.

The first argument is an array element & the second argument is the
index position from where you want to search.

If you have not passed the second argument, it will start searching from
the 0th index.

If the element is present, it returns the first occurred element's index


position

if the element is not present it returns -1.

Affects:- this method will not affect the original array

let num = [1, 2, 3, 4, 5, 8, 9, 10, 5, 5];

console.log(num.indexOf(5));// output 4

console.log(num.indexOf(5, 5)); // output 8

console.log(num.indexOf(5, -6)); // output 4

console.log(num.indexOf(100)); // output -1

array.lastIndexOf()

Used:- lastIndexOf() method is used to find out the index position of an


element. lastIndexOf() starts checking from the end of an array and
returns the index of the last occurred match.

Arguments: This method accepts two arguments where the first


argument is an element, and the second argument is the index position
from where you want to search

If  you don't pass the second argument, it starts checking from the last
index

Returns:- If the element is present, it returns the last occurred element's


index position.

If the element is not present, it returns -1.

Affects:- this method will not affect the original array.

 let num = [1, 2, 3, 4, 1]

console.log(num.lastIndexOf(1)); // output 4

console.log(num.lastIndexOf(1, 3)); // output 0

console.log(num.lastIndexOf(100)); // output -1

array.includes()

Used:-This method checks whether the element is present or not inside


an array.

Arguments:- This method accepts two arguments, where the first


argument is an array element, and the second argument is the index
position from where you want to search.

Returns:- This method returns a Boolean value. If the element is present


it returns true, else it returns false.

Affects: this method does not affect the original array. */

let str = ['Jspiders', "Qspiders", 'Pyspiders', "Test yantra"];

console.log(str.includes("Test yantra")); // output: true

console.log(str.includes('rajajinagar')); // output : false


array.concat()

Used:- This method is used to add new elements to the array.

Arguments:- This method accepts n number of arguments, where the


arguments, are the new elements added to the array.

Returns: this method returns updated array.

Affect: this method will not affect the original array.

let num1 = [1, 2, 3, 4]

let num2 = [5, 6, 7, 8, 9];

let result = num1.concat(num2, 10, 12, 13);

console.log(result); // output: -[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13]

array.join('*')

join() method converts the array into a string and separates the
elements by a separator.

Arguments: This method takes one argument that argument is a string


which is a separator for each element.

Affects: It does not affect the original array.

let num = [1, 2, 3, 4, 5, 6, 7, 8, 9];

console.log(num.join()); // output 1,2,3,4,5,6,7,8,9 If you have not given


the argument, the default separator is comm

console.log(num.join(" => ")); //output 1 => 2 => 3 => 4 => 5 => 6 => 7 =>
8 => 9

console.log(num.join(' * ')); // output 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9


array.forEach()

Used to:- this method is used to iterate an array of elements and their
indexes.

Argument:- this method accepts one argument.

Where the argument is a callback function, that callback function


accepts three arguments the first argument is the element, the second
argument is the index position, and the third argument is the whole
array.

Returns:- This method returns undefined.

Affects:- This method does not affect the original array.

// Example 1

let num = [12, 23, 45, 56, 78, 89];

num.forEach(callback);

function callback(element, index, array) {

console.log(element);

/* output

12

23

45

56
78

89

*/

// Example

let num2 = [15, 59, 75, 68, 23, 65, 123];

num2.forEach(function (ele, ind, arr) { console.log(ind, ele); })

/* output

0 15

1 59

2 75

3 68

4 23

5 65

6 123

*/

// Example3

let num3 = [1, 2, 3, 4, 5, 6, 7, 8, 9];

num3.forEach(ele => console.log(ele))

/* output
1

*/

array.map()

Used to:-  this method is used to perform some operations on existing


array elements and stores inside an updated array without affecting the
original array

Argument:- this method accepts one argument.

Where the argument is a callback function, that callback function


accepts three arguments the first argument is the element, the second
argument is the index position, and the third argument is the whole
array.

 // Example 1

let num = [1, 2, 3, 4, 5, 6, 7];

let result = num.map(callback);

function callback(ele, ind, array) {

return ele * 2
}

console.log(num); // output:- [1, 2, 3, 4, 5, 6, 7] original array

console.log(result); //output:-  [2, 4, 6, 8, 10, 12, 14] Each array element


is multiplied by 2 and stored inside a new array without affecting the
original array.

// Example 2

let num2 = ['jspider', 'qspider', 'pyspider'];

let result2 = num2.map(function (ele, ind, array) {

return ele.toUpperCase()

})

console.log(result2); // output:- ['JSPIDER', 'QSPIDER', 'PYSPIDER']

array.filter()

Used to:- filter() method is to filter the array of elements  based on a


condition.

Argument:- this method accepts one argument.

Where the argument is a callback function, that callback function


accepts three arguments the first argument is the element, the second
argument is the index position, and the third argument is the whole
array.

Returns:-  this method returns an array of filtered elements.

Affects:- filter() method does not affect the original array.

         
// Example 1:-

let num = [12, 45, 78, 89, 56, 32, 15, 59, 50];

let result = num.filter(function (ele, index, array) {

            return ele >= 50

})

console.log(result); // output:- [78, 89, 56, 59, 50]

// Example 2:-

let students = ["anil", 'sunil', 'sandesh', 'akash', 'arun'];

let result2 = students.filter(ele => ele.startsWith('a'));

console.log(result2); // output:-  ['anil', 'akash', 'arun']

array.some()

Used to: this method checks whether any one element is passing the
condition or not

Argument:- this method accepts one argument.

Where the argument is a callback function, that callback function


accepts three arguments the first argument is the element, the second
argument is the index position, and the third argument is the whole
array.

Returns:- this method takes one call back function that callback function
passes a condition on array element if any element is passing the
condition this method returns true else it returns false

Affects:- this method does not affect the original array.

// Example1

let ages = [14, 15, 18, 19, 20, 30, 35, 40, 50];

let result = ages.some(function (ele, index, array) {

            return ages >= 60

})

console.log(result); // output:- false

// Example2

        let result2 = ages.some(ele => ele == 30);

        console.log(result2); // output :- true

array.every()

every() method passes a test on each array element. If all the elements
pass a test, then it returns true. else every() method returns false.
Argument:- this method accepts one argument.

Where the argument is a callback function, that callback function


accepts three arguments the first argument is the element, the second
argument is the index position, and the third argument is the whole
array.

Returns:- This method returns a Boolean value

Affects:- This method does not affect the original array.

let num = [150, 250, 350, 450, 550, 50, 650, 750];

let result = num.every(function (ele, index, array) {

return ele > 50

})

console.log(result); // output:- false


array.find()

The find() method returns the value of the first array element that
passes a test function.

Argument:- this method accepts one argument.

Where the argument is a callback function, that callback function


accepts three arguments the first argument is the element, the second
argument is the index position, and the third argument is the whole
array.

Affects:- this method does not affect the original array

    

// Example1:-

let num = [1, 2, 3, 4, 10, 11, 12];

let result = num.find(test)

function test(ele, index, array) {

  return ele > 10

console.log(result); // output:- 11

// Example2:-

let studentName = ["arun", "sathish", "ravi", 'rakesh', 'anand', 'anupama',


'raju'];

let result2 = studentName.find(ele => ele.startsWith('r'));

console.log(result2); // output:- ravi

// Example3:-

let result3 = studentName.find(ele => ele.endsWith('l'));


 console.log(result3); // output:- undefined  if there is no match it
returns undefined

Array.isArray()

Used to:- this method is used to check whether the given data is an
array or not

Argument: this method accepts one argument where the arguments is


any kind of data

Returns: this method returns true if the given argument is an array else
this method returns false

Affects: this method will not affect the original array

let list = [20, 50, 70, 90, 110];

let institute = "Jspider";

let num = 1254687;

console.log(Array.isArray(list)); // output:- true

console.log(Array.isArray(institute)); // output:- false

console.log(Array.isArray(num)); // output:- false


Objects
JavaScript object is a collection of key and value pairs

To represent the JavaScript object, we use object literal {}

key and value must be separated with colon (key: value)

key and value pair must be separated with comm({name:'ravi',age:25})

    

let employee = {

            firstName: "Ravi",

            lastName: "Uppar",

            company: "varroc",

            salary: 450000

    }

accessing full object

console.log(employee); // output:-{firstName: 'Ravi', lastName: 'Uppar',


company: 'varroc', salary: 450000}
read

console.log(employee.firstName); // output:- Ravi

console.log(employee["firstName"]); // output:- Ravi

console.log(employee['salary']); // output:- 450000

console.log(employee.id); // output:- undefined (key is not present


returns undefined)

update

employee.company = "Test Yantra";

employee['salary'] = 600000;

console.log(employee);// updated object {firstName: 'Ravi', lastName:


'Uppar', company: 'Test Yantra', salary: 600000}

creation

employee['designation'] = "Developer";

console.log(employee); //{firstName: 'Ravi', lastName: 'Uppar', company:


'Test Yantra', salary: 600000, designation: 'Developer'}

delete

delete employee.company;

delete employee['salary']

console.log(employee);// output:- {firstName: 'Ravi', lastName: 'Uppar',


designation: 'Developer'}
For(let ele of iterable object){}
for (of) loop - loops through an iterable type of object(array, string,
node list, etc... this loop loops through elements

looping array elements by for(of) loop

let numbers = [100, 200, 300, 400, 500, 600, 700, 800];

for (let number of numbers) {

            console.log(number);
        /* output
 }
        100

        200

        300

        400
        500

        600

        700

        800

        */

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

for (let color of colors) {

console.log(color);

} /* output

        red

        green

        yellow

        black

        blue

        purple */

let students = [

            { sname: "Ravi", age: 25, rollNo: 1, marks: 620 },

            { sname: "Akash", age: 27, rollNo: 2, marks: 320 },

            { sname: "Kalyani", age: 23, rollNo: 3, marks: 520 },

            { sname: "Anand", age: 27, rollNo: 4, marks: 420 }

    ]

        for (let student of students) {

            console.log(student);

        }/*output
        {sname: 'Ravi', age: 25, rollNo: 1, marks: 620}

        {sname: 'Akash', age: 27, rollNo: 2, marks: 320}

        {sname: 'Kalyani', age: 23, rollNo: 3, marks: 520}

        {sname: 'Anand', age: 27, rollNo: 4, marks: 420}

        */

accessing student object properties

for (let student of students) {

            console.log(student.name);

} /*output

        Ravi

        Akash

        Kalyani

        Anand

        */

   

looping String elements by for(of) loop

let string = "Abdul Kalam";

for (let char of string) {

            console.log(char);

}/* output

    A
    b

    d

    u

    l

    

    K

    a

    l

    a

    m

        */

For( of ) never loops through JavaScript object because object is not


iterable

let chair = {

            company: "Neel Kamal",

            material: "plastic",

            type: "office chair",

            price: 5000

    }

for (let prop of chair) {

            console.log(prop);

        } // output:-Uncaught TypeError: chair is not iterable

For(let key in object){}


For(in) this loop can be loops through array and object

Whenever it is looping through array it loops through indexes of array


Whenever it is looping through Object it loops through keys of object

//  Looping with array (loops through indexes)

let studentList = ['Bhagat singh', "subhash chandra bose", 'Vivekanand',


"Abdul Kalam", "Vinobha bhave", "Chandra shekhar azad"]

for (let index in studentList) {

            console.log(index);

} /*output

        0

        1

        2

        3

        4

        5

         */

accessing array values by for (in) loops

for (let index in studentList) {

            // console.log(studentList["index"]); wrong way returns


undefined

            //  console.log(studentList.index);   wrong way returns undefined

            console.log(studentList[index]);

        } /* output

        Bhagat singh

        subhash chandra bose

        Vivekanand

        Abdul Kalam

        Vinobha bhave

Chandra shekhar azad */


Looping with object(loops through keys)

let chair = {

            company: "Neel Kamal",

            material: "plastic",

            type: "office chair",

            price: 5000

    }

        for (let key in chair) {

            console.log(key);

        }/ *output:-
        company

        material

        type

        price

        */

accessing object values by for (in) loops

for (let key in chair) {

            console.log(chair[key]);

    } /*output

        Neel Kamal

        plastic

        office chair

        5000
        */

Date
Whenever working with Dates, use the new Date() object.

There are four ways to create a Date object

        1.new Date()

        2.new Date(full year,


month,date,hours,minutes,seconds,milliseconds)

        3.new Date(milliseconds)

        4.new Date("string dates")

1. new Date() this object creates a new date object with the current time
and date

let currentDate = new Date();

console.log(currentDate); // output:- Sat Aug 06 2022 23:11:51


GMT+0530 (India Standard Time)

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

Date objects are static, the computer's time runs

2. new Date(full year,month,date,hours,minutes,seconds,milliseconds)

this object creates new date object with specified time and date this
object accepts 7 parameters in a same order

let specifiedDate = new Date(2010, 11, 30, 05, 33, 45, 300);

console.log(specifiedDate); //Thu Dec 30 2010 05:33:45 GMT+0530


(India Standard Time)

fullYear = pass four-digit number to set year. If you parsed two digits or
only one digit, JavaScript interprets it by prefixing 19.

let date1 = new Date(3, 01, 13, 10, 25, 13, 100);

console.log(date1);//Fri Feb 13 1903 10:25:13 GMT+0521 (India


Standard Time) one digit year(3) interpreted as 1903

let date2 = new Date(10, 01, 13, 10, 25, 13, 100);

console.log(date2);// Sun Feb 13 1910 10:25:13 GMT+0530 (India


Standard Time) two digits year(10) interpreted as 1910

Month:- JavaScript starts counting months from 0 to 11.

0  = January, 11  = December

let date3 = new Date(2010, 0, 20, 12, 25, 10, 300);

console.log(date3); // output:- Wed Jan 20 2010 12:25:10 GMT+0530


(India Standard Time)

let date4 = new Date(2020, 11, 20, 05, 12, 02, 310);

console.log(date4); // output:- Sun Dec 20 2020 05:12:02 GMT+0530


(India Standard Time)

specifying month higher than range will not give any error just  it will
overflow to next year

let date5 = new Date(2000, 14, 02, 25, 02, 100);

console.log(date5); // output:- Sat Mar 03 2001 01:03:40 GMT+0530


(India Standard Time)
Date:- JavaScript starts counting dates from 1 to 31

specifying a date higher than 31 will not give an error, overflow to the
next month

let date6 = new Date(2010, 02, 33, 12, 02, 18, 620);

console.log(date6); // output:- Fri Apr 02 2010 12:02:18 GMT+0530


(India Standard Time)

Hours:- JavaScript starts counting hours from 0 to 23

specifying an hour higher than 23 will not give an error, overflow to the
next day

Minutes:- JavaScript starts counting minutes from 0 to 59

specifying minutes higher than 59 will not give an error, overflow to the
next hour

Seconds:- JavaScript starts counting Seconds from 0 to 59

specifying seconds higher than 59 will not give an error, overflow to the
next minutes

 let date7 = new Date(2010, 10, 01, 24, 60, 70, 00);

console.log(date7); // output:- Tue Nov 02 2010 01:01:10 GMT+0530


(India Standard Time)
It is not mandatory to pass all the seven parameters while creating a
specified date object.

We can skip parameters  until the date the skip parameter will be stored
as default values

let date7 = new Date(2010, 10);

console.log(date7); //  output:- Mon Nov 01 2010 00:00:00 GMT+0530


(India Standard Time)

3. new Date(milliseconds)

this object creates a new date object with milliseconds. This object
accepts only one parameter is milliseconds

JavaScript stores date as a number of milliseconds since January 01,


1970, 00:00:00 UTC (Universal Time Coordinated).

let date8 = new Date(2000);

console.log(date8); // output:- Thu Jan 01 1970 05:30:02 GMT+0530


(India Standard Time)

4. new Date(string date)

there are three date formats in string date

1.ISO date  new Date("yyyy-mm-dd") --JavaScript prefers ISO


date

let isoDate1 = new Date("2010-02-12");

console.log(isoDate1); // output:- Fri Feb 12 2010 05:30:00 GMT+0530


(India Standard Time)

let isoDate2 = new Date("2010-02-12T02:25:32Z") // we can specify


time also by separating date and time with capital T  and Z specifies
UTC time

let isoDate3 = new Date("2003-02") // works

console.log(isoDate3); // output:- Sat Feb 01 2003 05:30:00


GMT+0530 (India Standard Time)

let isoDate4 = new Date("2018") // Works

console.log(isoDate4); //output :- Mon Jan 01 2018 05:30:00


GMT+0530 (India Standard Time)

2.Short date -> new Date("mm/dd/yyyy")

let shortDate = new Date("02/25/2007");

console.log(shortDate); // output:- Sun Feb 25 2007 00:00:00


GMT+0530 (India Standard Time)

3.Long date -> new Date("mm dd yyyy") or new Date("dd mm yyyy ")

let longDate1 = new Date("jan 05 2021");

console.log(longDate1); // output:- Tue Jan 05 2021 00:00:00


GMT+0530 (India Standard Time)

let longDate2 = new Date("January 25 2001");

console.log(longDate2); // output:- Thu Jan 25 2001 00:00:00


GMT+0530 (India Standard Time)

let longDate3 = new Date("25 January 2006");

console.log(longDate3); // output :- Wed Jan 25 2006 00:00:00


GMT+0530 (India Standard Time)

let longDate4 = new Date("25,jan,2004");


console.log(longDate4); // output:- Sun Jan 25 2004 00:00:00
GMT+0530 (India Standard Time)

 /* to get information from existing date object */

let birthDate = new Date(2010, 02, 25, 03, 25, 56, 300);

console.log(birthDate.getFullYear()); // output:- 2010

console.log(birthDate.getMonth()); // output:- 2

console.log(birthDate.getDate()); // output 25

console.log(birthDate.getHours()); // output 3

console.log(birthDate.getMinutes()); // output 25

console.log(birthDate.getSeconds()); // output 56

console.log(birthDate.getMilliseconds()); // output 300

/* setting existing date object */

let myDate1 = new Date("1992-07-08T02:12:56Z");

myDate1.setFullYear(1991);

myDate1.setMonth(05);

myDate1.setDate(17);

myDate1.setHours(07);

myDate1.setMinutes(55);

myDate1.setSeconds(01);

console.log(myDate1); // output:- Mon Jun 17 1991 07:55:31 GMT+0530


(India Standard Time)
// setTime() method

let myDate2 = new Date("5/02/2021");

console.log(myDate2); // output Sun May 02 2021 00:00:00


GMT+0530 (India Standard Time)

let result = myDate2.setTime(10000000) //A numeric value


representing the number of elapsed milliseconds since midnight,
January 1, 1970 GMT.

console.log(result); // output:- 10000000  setTime() sets date object in


milliseconds from January 1, 1970 GMT.

You might also like