...

Javascript

Introduction to JavaScript

JavaScript is used as a frontend as well as backend.

-Front end: React JS

-Back end: Nodejs and Expressjs

-Database: MongoDB

Definition:

            JavaScript is a scripting language that is used to add or provide functionality to our webpage.

·        Scripting language:

o   Means that each and every code written can read, analyzed and executed in the browser itself.


History of JavaScript

·        Earlier in 1990’s a company named Netscape wanted to build a Scripting language for their browser that is Netscape Navigator.

·        They hired a person called ‘Brandon Eich’ and asked him to develop a Scripting language.

·        Later he developed Scripting language within 10 Days and named it as ‘Mocha’ in the year 1995.

·        Later it was named as livescript, later for marketing strategy they named as “JavaScript”


 

*Why JavaScript is called as interpreted language

          JavaScript is called interpreted language because it reads the code line by line and executed, If at all it finds any error it will stop the execution then and there itself and will not move to the next line, it displays runtime error.


*Key Features of JavaScript(imp).

·        It is called as a scripting language.

·        Each and every operation done through JavaScript can be read, analyzed and executed in the browser end itself.

·        It is also called as weakly typed language:   
In your JavaScript code even if you miss the semicolon it will not give you error.
example: console.log(“something”)

·        One more example for weakly typed language is we don’t need to specify the type of data or the variable declaration keyword
ex:      let a=10
             console.log(a)

·        It is also called as dynamically typed language:
If you declare any variable and assign any numerical value to that variable , later we can change that to either string value , boolean value etc.
ex:       let a=10
             a=”naveen”
             console.log(a)//Naveen

·        It is a synchronous single threaded language (Interpreted language):
It will read the code line by line, If at all any error it will stop the execution then and there itself

·        High level programming language:
It can be easily understood by browser and programmer.

·        It is object-oriented programming language:
It is referred as object oriented programming language because it supports the principles of the object oriented programming like inheritance, polymorphism, encapsulation etc.

 


Ways of adding JavaScript to html document

There are 2 ways of adding Java Script

·        Internal Java Script

·        External Java Script


internal JavaScript

·        It refers to writing the JS Code in the same html file.

·        We use <script></script> which should be placed just below the ending of <body></body>.

·        JS code should be written inside the <script></script>.

Example:

<body>

Hello world

<script>

console.log(“This is internal JavaScript”)

</script>

</body>


external java script

·        Maintain a separate Java Script file with .js extension.

·        Link the external JS file with the html document by the help of
 <script src = “  ”></script> attribute.


JavaScript comments

Comments are the block of code i.e. not executed on the browser.

There are 2 types of comments in Java Script,

·        Single line comment //

·        Multiline comment /*    */




JavaScript engine:

 

·        Each and every browser has a JS Engine which is capable of understanding the JS Code and gives the output in the browser’s console.

·        When the JS File is executed on the browser, the browser sends the JS File to JS Engine.

·        In this process the JS File is first sent to the Parser, Parser stores the original code into tree like structure known as AST (abstract syntax tree/ abstract structured tree) & divides the code into parts (Tokens) & sends them one by one to the Compiler.

·        The Compiler checks the syntax errors & then converts the source code into Binary Code (0’s & 1’s) & sends to the Interpreter.

·        The Interpreter checks the Binary Code line by line and executes each line at a time then sends it to the Processor.

·        The Processor converts the Binary Code into Human Readable Format & prints the output on the Console.

 

 

SOME OF THE BROWSERS AND THEIR JS ENGINE

Browser Name (Engine Name)

·        Internet Explorer & Microsoft Edge (Chakra)

·        Mozilla Firefox (Spider Monkey)

·        Chrome (V8)

·        Brave (Blink + V8)

·        Opera (kraken)

 


Tokens:

Tokens are the smallest unit of a programming language.

In tokens we have keywords, identifiers and literals.

1.     Keywords.

·        Predefined words (or) the reserved keywords .

·        Should be written In lowercase
example: if, else, for, let, var, const…..

2.     Identifiers.

·        These are the names given to the components like variables, functions etc

·        Cannot start with numbers(but it can have a number in between )

·        Except dollar($) and underscore(_), no other special character is allowed.
example: name, age, skills, a1, b1…….

3.     Literals

·        These are the data(or )the values which is used in JavaScript programs.

·        There are 7 datatypes (or) the values that you can assign in JavaScript.

                                                              i.      Number

                                                            ii.      Boolean

                                                         iii.      Null

                                                          iv.      Undefined

                                                            v.      Big Int

                                                          vi.      Symbol()

                                                       vii.      String

A yellow rectangular object with black text

Description automatically generated


Datatypes:

            There are mainly two types of datatypes in general.

·        Primitive datatypes.

·        Non-primitive datatypes.

Primitive datatypes:

1.     Number:

o   It represents both integer and floating point numbers(decimal numbers).

o   Example: var a=10;
                     var b=20;
                     console.log(a,b)

2.     String:

o   It represents a sequence of charecters.

o   We can store a string of the character in the variable which returns string.

o   Example: var a=”naveen”;
                     var b=”r”;
                     console.log(a,b);

3.     Boolean:

o   It represents a logical value either true or false

o   Example: var a=true;
                     var b=false;
                     console.log(a,b);

4.     Undefined:

o   It represents a uninitialized (or) absence of a value for a variable.

o   Example: var a;
                     console.log(a);//output:Undefined

5.     Null:

o   It represents intentional absence of any object value

o   Example: Example: var a=null;
                     console.log(a);

6.     Bigint:

o   JavaScript has a precision upto 17 digits so now if you want to store large value without rounding off we can go with bigint.

o   Example: var c=12344556688977889978899380823n;
                     var d=Bigint(12344556688977889978899380823n)
                     console.log(c,d);
                     output:// 12344556688977889
                                         12344556688977889978899380823n

7.     Symbol():

o   It is mainly used to generate unique ids for an object.

o   Example: var c=Symbol(“”);
                     console.log(c);//Symbol()

Type of:

            The “typeof” operator is used to determine the datatype of a variable.

o   Var a=10;

o   Var b=”T”

o   Var c=false

o   Var d=null

o   Var e;

o   Var f=12345686970070049395939234n

o   Var g=symbol();

 

o   Console.log(typeof a);//number

o   Console.log(typeof b);//string

o   Console.log(typeof c);//Boolean

o   Console.log(typeof d);//Object

o   Console.log(typeof d);//undefined

o   Console.log(typeof e);//Bigint

o   Console.log(typeof f);//Symbol()

 


Scopes

·        Scope is a region of your code where a variable can be accessed or modifeied .

·        In JavaScript we have 3 main scope in general.

1.     Global Scope.

2.     Local scope/Function scope.

3.     Block scope.

Global Scope:

·        Variables declared outside any function or block have global scope.

·        They can be accessed from any part of the code including functions.

 

// var b=20;

// let c=30;

// const d=40;

// console.log("iam outside funciton & block");

// console.log(b);

// console.log(c);

// console.log(d);

// function f(){

//     console.log("im inside fuction")

//     console.log(b);

//     console.log(c);

//     console.log(d);

// }

// f()

 

// {

//     console.log("im inside block")

    // console.log(b);

    // console.log(c);

    // console.log(d);

// }

Note: Here var, let, const are used to declare the variables which act as variable declaration keywords.

            As the introduction of let and const in es6(ecma script 6) which was released in 2015, they introduced a new scope called script scope.

            Script scope is very much similar to the global scope but only let and const keywords fall in script scope whereas var falls in global scope.

 

Local Scope/Function scope:

·        Variables declared inside a function have local scope they are only accessible within that function and not accessible outside the function, as well as inside the block.

 

// function f(){

//  var b=20;

// let c=30;

// const d=40;

// }

 

// console.log("im outside funtion")

// console.log(b);

// console.log(c);

// console.log(d);

// {

//     console.log("im outside funtion and inside block")

//     console.log(b);

//     console.log(c);

//     console.log(d);

// }

 

Note: Variables declared inside the functions are referred to as local variables & are accessible only inside the function or block gives “uncaught reference error”.

 

Block Scope:

·        Variables declared with let and const are limited to the block where they are defined.

·        Blocks are enclosed by curly braces({ })

 

// {

//     var b=20;

//     let c=30;

//     const d=40;

// }

// console.log("im outside block")

// console.log(b);//only this executes

// console.log(c);

// console.log(d);

 

Note: variables declared with var keyword doesn’t have block scope.

 

 


Hoisting in variables

·        Hoisting is the process of moving the declarations to the top.

(Or)

·        It is the process of utilizing the variables before declaration.

 

* Note that only the declarations are moved to the top but not the initialization

* Hoisting is achieved in var & gives the value as undefined.

 

Example:

// console.log(a);

// var a=10;//undefined

 

 

* Hoisting is possible in the case of let and const but the value is not initialized because of TDZ & gives you reference error

Example:

// console.log(a);//Uncaught syntax error: cannot access ‘a’ before initialization

// const a=10;

// (or)

// let a=10;

 

 

Temporal dead zone(TDZ):

            It it the time duration between creation of a variable and its utilization.

* Only let and const come under TDZ.


Execution context

·        Execution context in JavaScript is like a container that holds the information about the environment in which your code is running.

·        It includes variables, functions, and the scope of your code, helping JavaScript to keep track of whats happening as it executes the code.                                                                                                                                                                                                                                                      

 

Program for Execution context

 

console.log("hello");

function a(){

b()

console.log("INSIDE A");    

}

function b(){

 c()

console.log("INSIDE B");    

}

function c(){

 

console.log("INSIDE C");    

}

a()

 

 

 

 

 

 

 

console.log("start");

let a=()=>{

    console.log("A function executed");

}

function b(){

    var val1=10;

    let val2=20;

    console.log(val1+val2);

    console.log("B function executed");

}

b();

a();

 

closures:

·        closures are the functions that can access to the variables from an outer function even if outer function has finished executing.

// function outer(){

//     let b=20;

//     function inner(){

//         console.log(b);

//     }

//     inner();

// }

// outer();

 


Difference between var let and const

var

Let

const

Variables declared with var keyword falls under global space

Variables declared under let keyword falls under block scope

Variables declared under const keyword falls under block scope

Declaration without initialization is possible

Example:

                    var a;

                    console.log(a);

                     //undefined

Declaration without initialization Is possible

Example:

                    let a;

                    console.log(a);

                     //undefined

Declaration without initialization is not possible but declaration & initialization should be done on the same line.

Example:

                    const c;

                    console.log(c);

                    //uncaught syntax error missing initialize in const declaration const c=10;

Reinitialization is possible.

 

var a=10;

console.log(a);//10

a=false;

console.log(a);//false

Reinitialization is possible.

 

let a=10;

console.log(a);//10

a=100;

console.log(a)//100

Reinitialization is not possible.

 

const pi=3.14;

console.log(pi);//3.14

pi=10.14;

console.log(pi);//uncaught type error assignment to constant variable.

 

Redeclaration is possible.

 

var a=10;

console.log(a);//10

var a;

console.log(a);//false

 

Redeclaration is not possible.

 

let a=10;

console.log(a);//10

let a;

console.log(a)//uncaught syntax error: identifier has already been declared

Redeclaration is not possible.

 

const a=10;

console.log(a);//10

const a;

console.log(a)//uncaught syntax error: identifier has already been declared

Hoisting is possible and is initialized with default value undefined

 

 

Example:

console.log(a);

Var a=10;

//undefined

Hoisting is possible but the value is not initialized because of the temporal dead zone(TDZ)

 

Example:

console.log(a);

let a=10;

//Uncaught reference error cannot access ‘a’ before initialization

Hoisiting is possible but the value is not initialized because of the temporaldead zone(TDZ)

 

Example:

console.log(a)

const a=10;

//Uncaught reference error cannot access ‘a’ before initialization

 


Operators

Operators are the predefined symbols used to perform a specific task.

Operands

Operands are the values upon which the operation is performed

A diagram of a number and operator

Description automatically generated

There are 5 types if operators in javascript they are

·        Arthematic operator(+,-,*,/,%)

·        Comparison operator/Relational operator(>,<,>=,<=,==,!=,===)

·        Assignment operator(=,+=,-=,*=,/=,%=)

·        Logical operator(&&,||,!)

·        Conditional operator

//ARTHEMATIC OPERTATORS(+,-,*,/,%)

 

//ADDITION

// console.log(2+2);//4

// console.log(2+"2");//22

// console.log(typeof(2+"2"));//string

// console.log(2+"html");//2html

// console.log(2+2+"html");//4html

// console.log(2+2+"html"+2);//4html2

// console.log(2+true);//3

// console.log(2+false);//2

// console.log(2+ +"2");//4

// console.log(typeof+"2");//number

 

//SUBTRACTION

// console.log(1-1);//0

// console.log(1-"1");//0

// console.log(typeof(1-"1"));//number

// console.log(1-true);//0

// console.log(1-false);//1

// console.log(1-"abc");//NaN

// console.log("20"-"abc");//NaN

// console.log(typeof("20"-"abc"));//number

 

//MULTIPLICATION

// console.log(2*2);//4

// console.log(2*"2");//4

// console.log(typeof(2*"2"));//number

// console.log(2*true);//2

// console.log(2*false);//0

// console.log(2*"abc");//NaN

// console.log(typeof(2*"abc"));//number

 

//DIVISION

// console.log(2/2);//1

// console.log(2/"2");//1

// console.log(typeof(2/"2"));//number

// console.log(2/true);//2

// console.log(2/false);//Infinity

// console.log(2/"abc");//NaN

 

//MODULUS

// console.log(2%2);//0

// console.log(2%"2");//0

// console.log(typeof(2%"2"));//number

// console.log(2%true);//0

// console.log(2%false);//NaN

// console.log(2%"abc");//NaN

 

//COMPARISION OPERATORS(>,<,>=,<=,==,!=,===)

 

// let p=1;

// let q=2;

// let r="1";

// console.log(p>q);//false

// console.log(p>r);//false

// console.log(q>r);//true

// console.log(p>=q);//false

// console.log(p>=r);//true

// console.log(p<r);//false

// console.log(p<=r);//true

// console.log(q!=r);//true

// console.log(r!=p);//false

// console.log(r==p);//true

// console.log(r==q);//false

// console.log(r===p);//false

 

//ASSIGNMENT OPERATORS(+=,-=,*=,/=,%=)

// let a=10

// let b=20

// let c="30"

//  //+=

// console.log(a+=b);//30

// console.log(a+=c);//3030

// console.log(a+=true);//3030true

// console.log(a+=false);//3030truefalse

 

//-=

// console.log(a-=b);//-10

// console.log(a-=c);//-40

// console.log(a-=true);//-41

// console.log(a-=false);//-41

 

//*=

// console.log(a*=b);//200

// console.log(a*=c);//6000

// console.log(a*=true);//6000

// console.log(a*=false);//0

 

// /=

// console.log(a/=b);//0.5

// console.log(a/=c);//0.0166666666666666

// console.log(a/=true);//0.0166666666666666

// console.log(a/=false);//Infinity

 

// %=

// console.log(a%=b);//10

// console.log(a%=c);//10

// console.log(a%=true);//0

// console.log(a%=false);//NaN

 

// LOGICAL OPERATOR(&&,||,!)

 

// let a = 10;

// let b = 30;

// let c = "10";

// let d = 5;

 

// console.log(a>d && b>a && d<=a);//true

// console.log(a===c && c>a && b>=d);//false

// console.log(a==c && a===c);//false

// console.log(a<c || a<=d || a==c); //true

// console.log(!(a===c));//true

 

//TERNARY OPERATOR/CONDITIONAL OPERATOR

 

// let amount =340;

// let output = amount>300?"go to movie":"go and eat biryani"

// console.log(output);// go to movie

 

 

What is NaN

NaN stands for not a number

·        It is a special value that is used to represent the result of a invalid or an unrepresented mathematical operation.

Example:

 

// console.log(0/0);//NaN

// console.log(1-"abc");//NaN

// console.log("abc"*"20");//NaN

 

Difference between (==) &(===)

(==)

It compares only the values irrespective of the datatypes.

Example: // console.log(1=="1");//true

(===)

It compares both the values as well as the datatype.

Example: // console.log(1==="1");//false

 

Note:

->1+”1” àstring

->1-“1” ànumber

->1*“1” ànumber

->1/“1” ànumber

->1%“1” ànumber

 

 

 

 


Decision statements

Decision statements are used to execute a statement based on the condition there are 4 main types of decision statements

·        If

·        If-else

·        Else-if

·        Switch case

1.If

Syntax: /*

syntax for if

if(condition){

    /code to be executed

}

*/

 

 

Example: // if

 

// let person = true

// if(person){

//     console.log("requirements will be provided");

// }

 

 

2.if-else

Syntax: /*

syntax for if-else

if(condition){

    /code to be executed if condition satisfied

}

else{

    /code to be executed if condition fails

}

*/

 

Example: //if-else

 

// let husband=true;

// if(husband){

//     console.log("DO NOT ENTER THE HOUSE");

// }

// else{

//     console.log("YOU CAN ENTER INSIDE");

// }

 

 

3.else-if

Syntax: /*

syntax for else-if

if(condition){

    /code to be executed

}

else if(condition 2){

    /code to be executed

}

else{

    /code to be executed if condition fails

}

*/

 

 

 

Example: //else-if

 

// let amount = 400;

// if(amount>300){

//     console.log("CHICKEN BIRYANI");

// }

// else if(amount>200 && amount <300){

//     console.log("VEG PALAV");

// }

// else if(amount>100 && amount<200){

//     console.log("curd rice with waterbottle");

// }

// else{

//     console.log("noru mooskoni intiki velu");

// }

 

 

4.switch-case

Syntax: /*

syntax for switch case

switch(value/expression){

    case val1:

        /code

        break;

    case val2:

        /code

        break;

    default :

        /code

}

*/

 

Example: //switch case

 

// let girlage =18

// switch(true){

//     case (girlage>=30):

//         console.log("Already too late for marriage");

//         break;

//     case (girlage>=25 && girlage<30):

//         console.log("perfect age for marriage");

//         break;

//     case (girlage>=18 && girlage<25):

//         console.log("not intrested");

//         break;

//     default:

//         console.log("CHILD");

// }


Loops

Loops are used to perform a specific task repeatedly based on a condition.

There are three main loops in javaScript

·        For loop

·        While loop

·        Do while loop

1.For loop:

Syntax: /*

syntax for for loop

        (1)            (2)      (4)

for(initialization,condition,updation){

    /code (3)

}

*/

 

 

Example: // for

 

// for(let i=1;i<=100;i++){

//     console.log("hello world")

// }

 

 

2.while loop:

Syntax: /*

syntax for while loop

(1)initialization

(2)while(condition)

{

(3)/code to be executed

(4)updation

}

*/

 

Example: // while

 

// let j=1;

// while(j<=100){

//     console.log("hello world");

//     j++;

// }

 

3.Do while loop:

Syntax: /*

syntax for do while loop

(1)initialization

do{

(2)/code to be executed

(3)updation

}while(condition)

     (4)

*/

 

Example:

// do while

 

// let i=1;

// do{

//     console.log("hello world");

//     i++;

// }while(i<=5)

 


Strings

·        Strings are basically the text or the sequence of charecters.

·        In javascript anything which is enclosed with(“”) double quotes or (‘’) single quotes or(``) back ticks.

To create a string we have two ways

1.String Literal way:

Example: // string literal way

// let a="hello";

// console.log(a);//hello

// console.log(typeof a);//string

 

 

2.using string constructor object:

Example: // string constructor way

// let str=new String("hello")

// console.log(str);//string:{hello}

// console.log(typeof str);//object

 

 

String interpolation/String templates/template.

            The process of writing a variable or logical statement inside a string is called as string interpolation.

string interpolation can be achieved by using backticks (` `) or(‘ ’)or(“ ”).

Example:

// let name="ravi"

// let loc="Hyderabad"

// console.log(`my name is ${name} and iam from ${loc}`);//my name is ravi and iam from Hyderabad

 

We can access the string using their indexes

Indexes in strings start with ‘0’

Example: /*

let str ="H e l l o"

          | | | | |

          0 1 2 3 4

let a="hello";

console.log(a[1]);//e

console.log(a[0]);//h

console.log(a[4]);//o

console.log(a[-1]);//undefined

console.log(a[10]);//undefined

*/

 

To access the total length of the string we have length property.

Example:

 // let a="hello";

// console.log(a.length);

 

Note:

·        length starts from 1

·        Accessing string using negative index will return undefined.

 

String Methods

1) charAt()

2) charCodeAt()

3) toLowerCase()

4) toUpperCase()

5) repeat()

6) replaceAll()

7) indexOf()

8) lastIndexOf()

9) slice()

10) substring()

11) concat()

12) replace()

13) split()

14) trim()

15) trimStart()

16) trimEnd()

17) includes()

18) startsWith()

19) endsWith()

 

1.charAt(index)

·        It returns the character at the specified index.

Example:

// charAt()

// let str="hope you enjoyed holidays";

// console.log(str.charAt(0));//H

// console.log(str.charAt(10));n

// console.log(str.charAt(str.length-1));//24

 

2.charCodeAt()

·        It returns the ASCII value of the element

Example: // charCodeAt()

// let str="hope you enjoyed holidays";

// console.log(str.charCodeAt(2));//80

// console.log(str.charCodeAt(str.length-3));//65

 

3.toLowerCase() & toUpperCase()

Example: //toUpperCase() and toLowerCase()

// let str="hope you enjoyed holidays";

// console.log(str.toLowerCase());//hope you enjoyed holidays

// console.log(str.toUpperCase());//HOPE YOU ENJOYED HOLIDAYS

 

4. repeat()

·        repeat() is used to create a new string by repeating the original string a specified No.of times.

Example: // repeat(count)

// let str="abc"

// console.log(str);//abc

// console.log(str.repeat());//gives empty

// console.log(str.repeat(1));//abc

// console.log(str.repeat(2));//abcabc

 

5. replace()

·        replace() is used to replace a specified substring or pattern with another substring.

·        it replaces only the first occurrence in the given string.

·        It is case sensitive.

Example:

// replace(oldstring,newstring)

// let a="hi hello hello how are you"

// console.log(a);//hi hello hello how are you

// console.log(a.replace("hello","hey"));//hi hey hello how are you

// console.log(a.replace("hello","hey"));//hi hey hey how are you

 

6.replaceAll()

·        It is similar to replace()method but it replaces all the occurrences of the specified substring or the pattern.

Example: // replaceAll(oldstring,newstring)

// let a="hi hello hello how are you"

// console.log(a);//hi hello hello how are you

// console.log(a.replaceAll("hello","hey"));//hi hey hey how are you

// console.log(a.replaceAll(/hello/gi,"hey"));//hi hey hey, how are you

 

7.indexOf()

·        It is used to find the position of a substring within a string.

·        It starts searching from left to right

·        Negative indexes are converted into ‘0’

·        Case sensitive

·        Index starts from ‘0’

Example: // indexOf(charecter,startindex)

// console.log(a.indexOf("hello"));//-1

// console.log(a.indexOf("Hello"));//3

// console.log(a.indexOf("hello",3));//3

// console.log(a.indexOf("hello",-200));//3

 

8.lastIndexOf()

·        It is used to find the last occurrence of a specified substring within a string.

·        Here the negative index is converted to zero.

·        Indexes starts from ‘0’

·        Case sensitive

Example: // lastIndexOf(charecter,startindex)

// console.log(a.lastIndexOf("hello"));//-1

// console.log(a.lastIndexOf("Hello"));//9

// console.log(a.lastIndexOf("hello",8));//0

// console.log(a.lastIndexOf("hello",-1));//0

 

9.slice()

·        Slice method is used with string to extract a portion of the string(substring) and create a new string.

·        It takes negative values

·        If the start index is greater than the end index it returns empty

·        Index starts from ‘0’

·        Avoids last charecter

Example: // slice(startindex,endindex)

// let str="Moye Moye";

// console.log(str.slice(o));//Moye Moye

// console.log(str.slice(4));//Moye

// console.log(str.slice(2,6));//ye M

// console.log(str.slice(6,2));//""

// console.log(str.slice(-4));//Moye

 

10.substring()

·        Substring method is similar to slice method i.e it extracts a portion of the string and creates a new string.

·        It does not take negative indices, but it is converted to zero.

·        If start index is greater than end index, it will swap the indices.

·        Index starts from ‘0’

Example: // substring(startindex,endindex)

// let str="Moye Moye";

// console.log(str.substring(o));//Moye Moye

// console.log(str.substring(4));//-Moye

// console.log(str.substring(4,6));//M

// console.log(str.substring(6,4));//M

// console.log(str.substring(-4));//Moye Moye

// console.log(str.substring(-4,-2));//" "

// console.log(str.substring(2,-4));//mo

 

11.concat()

·        It is used to combine 2 or more strings and create a new string.

·        We can concatenate multiple strings by providing them as a separate arguments.

Example: // concat(string,string)

// let a="html"

// let b="css"

// console.log(a.concat(b));//HTMLCSS

// console.log(a.concat(a," ",b));//HTML CSS

// let c="Javascrpt"

// console.log(a.concat(a," ",b," ",c));//HTML CSS Javascript

 

 

12.trim(),trimStart(),trimEnd()

·        trim() method is used to remove the white spaces from the both the ends of the string.

·        trimStart() is used to remove the white spaces only from the beginning of the string.

·        trimEnd() is used to remove the white spaces only from the ending of the string.

 

Example: // trim(),trimStart(),trimEnd()

// let exm="      Hi hello everyone      "

// let originallen=exm.length//29

// console.log(exm.trim());//"Hi hello everyone"

// console.log(exm.trimStart());//"Hi hello everyone      "

// console.log(exm.trimEnd());//"      Hi hello everyone"

 

13.includes()

·        It checks whether the specified string is present in the original string.

·        If present it returns true, else it returns false.

·        Position is by default set to ‘0’, and its case sensitive.

Example: // includes(string,position)

// let str="hi hello how are you"

// console.log(str.includes("hi"));//true

// console.log(str.includes("Hi"));//false

// console.log(str.includes("e"));//true

// console.log(str.includes("hi",3));//false

 

14.startsWith()

·        It is used to check whether the specified string starts with the given original string.

·        If it starts with it returns true else false.

·        It is case sensitive.

·        Indices start from ‘0’.

Example: // startsWith(string,position)

// let str="Hey There How Are You";

// console.log(str.startsWith("Hey"));//true

// console.log(str.startsWith("hey"));//false

// console.log(str.startsWith("H"));//true

// console.log(str.startsWith("There"));//false

// console.log(str.startsWith("There",4));//true

 

15.endsWith()

·        It is used to check whether the specified string ends with the given original string.

·        If it ends with, it returns true else false.

·        It is case sensitive.

·        It takes length from 1.

Example: // endsWith(string,position)

// let str="Hey There How Are You";

// console.log(str.endsWith("Hey"));//false

// console.log(str.endsWith("hey"));//false

// console.log(str.endsWith("?"));//true

// console.log(str.endsWith("Hey",3));//true

// console.log(str.endsWith("Hey",4));//false

 

 

16.split()

·        This method is used to split the string into an array of substrings based on the separator symbol specified and also the limit.

Example: // split(separator,limit)

// let ex="Hey Hello Ok";

// let amp="Hey-Hello-Ok"

// console.log(ex.split(""));//['Hey','','Hello','','Ok']

// console.log(amp.split("-"));//['Hey','Hello','Ok']

// console.log(ex.split());//'Hey Hello Ok'

// console.log(amp.split());//'Hey-Hello-Ok'

// console.log(ex.split(""));//splits each and every charecter of the string

// console.log(amp.split());//splits each and every charecter of the string

// console.log(ex.split("",2));//['Hey','Hello']

// console.log(amp.split("-",2));//['Hey','Hello']

 

 


Arrays:

·        Array is a collection of both homogeneous and heterogeneous type of data.

                                                        i.            Homogeneous- similar type of data.

                                                      ii.            Heterogeneous- Different type of data.

·        Arrays are indicated by the symbol square braces[]

·        To access individual elements of the array we use indexes.

·        Index always starts with zero .

 

Ways to create array :

·        There are two ways of creating an array

o   Array literal way

Example

//!Array literal way

// let name1 = ["hello",10,true];

// console.log(name1);//[]

// console.log(typeof name1);

 

·        Array constructor object

Example:

// let demo = new Array("hello",20,true)

// console.log(demo);

// let demo1= new Array(5);

// demo1[0]="hello"

// demo1[1]="mic"

// demo1[2]="testing"

// demo1[3]=1

// demo1[4]=2

// console.log(demo1);

 

Accesing array elements(Indexing and length)

·        - array elements can be accessed through their index values which should be passed into the square braces[]

·        -We cannot access array elements through negative index values

·        -to find the total number of elements inside an array we have length property

·        example

Multidimensional array (Nested array)

 

Methods to ADD or DELETE the elements of an array either starting or ending of an array.

·        Push() Method:

o   It is used to add the elements at the end of an array

Example:

// push():adds the element at the ending of the array

// let arr=["KKR",'RR','SRH']

// console.log(arr);//[ 'KKR', 'RR', 'SRH' ];

// arr.push('CSK','DC','LSG')

// console.log(arr);//[ 'KKR', 'RR', 'SRH', 'CSK', 'DC', 'LSG' ]

 

·        Pop() Method:

o   It is used to remove the last elements of an array.

o   In simple words it removes the elements from the ending of an array

Example:

 //pop():removes the last element from an array

// arr.pop();

// console.log(arr);//[ 'KKR', 'RR', 'SRH', 'CSK', 'DC' ]

o    

·        Unshift() method:

o   It is used to add the elements at the beginning of the array.

Example:

//unshift():adds the element at the beginning of the array

let arr=["brs",'bjp','congress']

console.log(arr);//[ 'brs', 'bjp', 'congress' ]

arr.unshift("psp","js")

console.log(arr);//[ 'psp', 'js', 'brs', 'bjp', 'congress' ]

·        Shift() method:

o   It is used to remove the element from the beginning of the array.

Example:

// shift():remove the element from the beginning of the array

let arr=[ 'psp', 'js', 'brs', 'bjp', 'congress' ]

arr.shift()

console.log(arr);//[ 'js', 'brs', 'bjp', 'congress' ]

arr.shift()

console.log(arr);//[ 'brs', 'bjp', 'congress' ]

Array methods

·        tostring()

o   it is used to convert given array into string

example:

 //tostring():

let arr=["A","B","C"]

console.log(arr);

let converted = arr.toString(arr)

console.log(converted);

console.log(typeof converted);

·        concat():

o   it is used to combine one or more arrays

example:

//concat():

let arr19=["hello",'how','are','you']

let arr2=['am','fine','how','are','you?']

 arr3=['had','your','lunch?']

let merged = arr1.concat(arr2,arr3)

console.log(merged)

let newmerged=arr1.concat("Bagunnava?")

console.log(newmerged);

·        join():

o   it is used to convert the array elements to a string by combining the array elements with the specified separator in between.

example:

 //join()

let arrnew=["a","b",'c']

console.log(arrnew);

console.log(arrnew.join("*"));

console.log(arrnew.join(" "));

console.log(arrnew.join(" 😊 "));

·        at():

o   it returns the array element for the specified index.

o   it can also take negative index value.

o   If the index value is not allocated for a element it returns “undefined”

example

//at()

let arr=["html",'css','java']

console.log(arr);

console.log(arr.at(0))

console.log(arr.at(2));

console.log(arr.at(10));

console.log(arr.at(-1));

 

 

·        flat():

o   it is used to convert the multidimensional array to a single dimension based on the depth level

example:

 //flat():

let arr=[1,2,3,[4,[5,[6,[7,[8,]]]]]]

console.log(arr);

console.log(arr.flat());

console.log(arr.flat(2));

console.log(arr.flat(Infinity))

·        delete

o   it removes the element from the given array and leaves empty space that is “undefined”.

o   Since it leaves the empty spaces using it is not preferred, alternatively you can go with pop or shift methods.

Example:

//delete:

let arr=["html",'css','java'];

console.log(arr);

delete arr[2]

console.log(arr);

 

·        isArray():

o   This method is used to check whether the specified value is an array or not.

o   If it is array it returns true else false

Example:

//isArray():method   

// let arr=['puri','dosa','vada','uthapam','chapathi']

// let arr1=['Chicken biryani ','Raagi mudde','Natu kodi']

// let arr2=[[

//     1,2,3,4,5,6

// ]]

// let arr3="[1,2,3,4,5,6]"

// console.log(Array.isArray(arr));//true

// console.log(Array.isArray(arr1));//true

// console.log(Array.isArray(arr2));//true

// console.log(Array.isArray(arr3));//false

·        reverse()

o   This method is used to convert the given array In reverse order

Example:    

//reverse():method

// let arr=['puri','dosa','vada','uthapam','chapathi']

// let arr2=[1,2,3,4,5,6,7,8,9,10]

// console.log(arr2.reverse());//[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

// let reverse = arr.reverse();

// console.log(reverse);//[ 'chapathi', 'uthapam', 'vada', 'dosa', 'puri' ]

·       sort():

o   It is used to arrange the given array based on the first digit of a number


Example:

// sort():method

// let numb=[30,10,100,40,50,90,12]

// console.log(numb.sort());//[10, 100, 12, 30, 40,  50, 90]

// let arr=[1,300,20,true,"name"]

// console.log(arr.sort());//[ 1, 20, 300, 'name', true ]

 

·        slice():method

o   This method is used to extract the portion if the array and returns a new array.

o   It will not affect the original array.

o   It starts iterating from left to right while extracting the array elements.

o   It can take negative(-ve) index values.

o   If start index is greater than end index it returns empty array.

Example:

// slice(): method

// let arr=['rahul','monty','Asnan','abbas','Hari prashanth','shankar','yasin','Hariharan','Shiva','sharath']

// console.log(arr);//['rahul', 'monty', 'Asnan', 'abbas', 'Hari prashanth', 'shankar', 'yasin', 'Hariharan', 'Shiva', 'sharath']

// console.log(arr.length);//10

// console.log(arr.slice(0));//['rahul', 'monty', 'Asnan', 'abbas', 'Hari prashanth', 'shankar', 'yasin', 'Hariharan', 'Shiva', 'sharath']

// console.log(arr.slice(3,8));//['abbas', 'Hari prashanth', 'shankar', 'yasin', 'Hariharan']

// console.log(arr.slice(0,-4));//['rahul', 'monty', 'Asnan', 'abbas', 'Hari prashanth', 'shankar']

// console.log(arr.slice(5,0));//[]

// console.log(arr.slice(-2,0));//[]

// console.log(arr.slice(1,1));//[]

// console.log(arr);//['rahul', 'monty', 'Asnan', 'abbas', 'Hari prashanth', 'shankar', 'yasin', 'Hariharan', 'Shiva', 'sharath']

 

·        Splice():method

o   It is used to add or delete the elements of an array.

o   It will affect the original array .

o   It can take negative value for the start index but not for the delete count.

o   Syntax:
splice(startindex, delete count, items to be added)

Example:

//splice():method

// let arr=['panipuri','samosa','cutlet','pavbhaji','Dahi puri']

// console.log(arr);//['panipuri','samosa','cutlet','pavbhaji','Dahi puri']

// console.log(arr.length);//5

// console.log(arr.splice(1,1,"Bhelpuri"));//[ 'samosa' ]

// console.log(arr);[ 'panipuri', 'Bhelpuri', 'cutlet', 'pavbhaji', 'Dahi puri' ]

// console.log(arr.splice(1,1,"Bhel puri","sev puri"));//['samosa']

// console.log(arr);//['panipuri', 'Bhel puri', 'sev puri', 'cutlet', 'pavbhaji', 'Dahi puri']

// console.log(arr.splice(3,0,"kachori"));//[]

// console.log(arr);//['panipuri', 'samosa', 'cutlet', 'kachori', 'pavbhaji', 'Dahi puri']

// console.log(arr.splice(-2,3,"gulab jamun"));// ['pavbhaji', 'Dahi puri']

// console.log(arr);//['panipuri', 'samosa', 'cutlet', 'gulab jamun']

 

·        Includes():method

o   This method is used to check whether the element is present in the array or not.

o   If the element is present it returns true else it returns false.

o   This method takes the second value as index from where it will start searching for the element.

Example:

//includes():Method

let arr=["water","mango","grapes","watermelon","muskmelon"]

console.log(arr.includes("water"));//true

console.log(arr.includes("grapes"));//true

console.log(arr.includes("mango",2));//false

console.log(arr.includes("mango",-4));//true

console.log(arr.includes("mango",-1));//false       

 

·        indexOf():method

o   This method returns the index for the given element.

o   If the element is present in the array it returns its index else it returns -1.

o   It iterates from left to right direction.

o   It takes the second value as the start index from where it will start searching for the element from left to right side.

Example:

 //indexOf():method

let arr=["chiken pakora","Fish Fry","potato chips","Peanut masala"]

console.log(arr.indexOf("Fish Fry"));//1

console.log(arr.indexOf("Moong dal"));//-1

console.log(arr.indexOf("Fish Fry",0));//1

console.log(arr.indexOf("Fish Fry",2));//-1

console.log(arr.indexOf("Fish Fry",-1));//-1

console.log(arr.indexOf("Fish Fry",-3));//1

 

·        lastIndexOf():method

o   This method returns the index for the given element.

o   If the element is present in the array it returns its index else it returns -1.

o   It iterates from right to left direction.

o   It takes the second value as the start index from where it will start searching for the element from left to right side.

Example:

//lastIndexOf():method

let arr=["chiken pakora","Fish Fry","potato chips","Peanut masala"]

console.log(arr.lastIndexOf("Fish Fry"));//1

console.log(arr.lastIndexOf("Moong dal"));//-1

console.log(arr.lastIndexOf("Fish Fry",0));//-1

console.log(arr.lastIndexOf("Fish Fry",2));//1

console.log(arr.lastIndexOf("Fish Fry",-1));//1

console.log(arr.lastIndexOf("Fish Fry",-3));//1

 

Array Higher order methods:

·        1)forEach():method

o   it is a higher order method which is used to iterate upon the array elements and perform a specific operation

o   it takes a callback function as its argument and which in turn takes 3 values i.e element,index and array

element

// 1)forEach():method

// let arr=["telangana","AP","karnataka","Maharastra"];

// arr.forEach(display)

// function display(element,index,array){

//     console.log(element);

// }

o   forEach() method cannot return the values it returns undefined

example:

// let arr=["telangana","AP","karnataka","Maharastra"];

// let output = arr.forEach((a,b,c)=>{

//     return a

// })

// console.log(output);//undefined

o   multiplying each element of array by 2

example:

 // multiplying each element of array by 2

// let arr2=[10,20,30,40,50];

// arr2.forEach((ele)=>{

//     console.log(ele*2);

// })//can be converted into implicit as .>>>> arr2.forEach((ele)=>console.log(ele*2))

o   extracting data from nested array

example:

// let arr =[

//     ["r",24,1,"student"],

//     ["S",23,1,"student"],

//     ["V",23,0,"Director"]

// ]

// arr.forEach((ele)=>console.log(ele[0]))

 

·        2)map():method

o   It is a higher order method which is used to iterate upon the array elements and perform a specific operation

o   It takes a callback function as it argument and which in turn takes 3 values i.e element,index and array.

o   It returns an array

Example:

// let arr=["dilshuknagar",'kphb','panjagutta','jntu']

// let branches = arr.map(ele,index,array)=>{

         return ele;

})

// console.log(branches);// when return is used in map method we get an array

o   Map method return the array of values

Example:

 // let arr=["dilshuknagar",'kphb','panjagutta','jntu']

// let branches = arr.map(ele=>ele)

// console.log(branches);// when return is used in map method we get an array

o   Multiplying each element of array by 2

Example:

 // let arr2=[10,20,30,40,50]

// console.log(arr2.map(ele=>ele*2))//here the returned value is multiplied and stored inside of an array and displayed

 

·        3)filter():method

o   It is a higher order method which is used to iterate upon the array elements and perform a specific operation

o   It is mainly used to filter out the values of an array

o   It takes a callback function as its argument and which in turn takes 3 values i.e element,index and array.

o   It return an array with the values which  only satisfy the condition

Example:

 // let arr=[30,100,20,56,32]

// arr.filter(

//     (ele,ind,array)=>{

//         console.log(ele>50);

//     })

// let out= arr.filter((ele)=>ele>30)

// console.log(out);

 

·        4)reduce():method

o   This method is used to reduce the array elements into a single value using a reducer function(callback function).

o   Reduce method takes 2 arguments.

§  Reducer function(callback function)

§  Initial value (stored in the accumulator)

o   The reducer function takes 4 values that is

§  Accumulator

§  Element

§  Index

§  Array

Example:

//4)reduce():method

//using for loop

// let arr=[1,2,3,4,5,6,7,8,9,10]

// let sum1=0;

// for(let i=0;i<=arr.length-1;i++){

//     sum1+=arr[i]//sum1=sum1+arr[i]

// }

// console.log(`The sum using for loop is ${sum1}`);

 

//using reduce method

// let newoutput =arr.reduce(

//     (sum2,element,index,array)=>{

//         return sum2=sum2+element//we can use sum2+=element

//     }

// )

// console.log(`the sum using the reduce method is ${newoutput}`);

 

//using reduce method with initial value

// let newoutput1 =arr.reduce(

//     (sum2,element,index,array)=>{

//         return sum2=sum2+element//we can use sum2+=element

//     },5

// )

// console.log(`the sum using the reduce method is ${newoutput1} and initial value is 5`);

 

·        5)some():method

o   It iterates over the array elements and checks if atleast one of the array element satisfy the condition, if atleast one of the element satisfies the condition it returns true else false.

Example:

//5)some():method

// let arr1=[10,20,30,40,50]

// let output1=arr1.some(

//     (element)=>element>40//if one of the element satisifes then returns true else false(implicit return arrow function is used dont get confused)

// )

// console.log(output1);//true

 

·        6)every():method

o   It iterates over the array elements and checks if all of the array elements satisfy the condition only then it returns true else false.

Example:

//6)every():method

// let arr2=[10,20,30,40,50]

// let out2=arr2.every(

//     (element)=>{

//         return element>4//if every element satisifes condition then only it returns true else false

//     }

// )

// console.log(out2);

 


Objects

·        Objects are used to store the data in the form of key value pairs.

·        The combination of key value pair is called a property.

·        In JavaScript objects are denoted by curly braces ({}).

·        There are two ways of creating an object

o   Literal way.

Example: //literal way

// let biodata={

//     name:"karthik",

//     age:27,

//     dob:"28-05-1997",

//     job:"doctor",

//     salary:300000,

//     exGirlFriend:true,

//     futuregoals:["visiting bali","earning 400000"],

//     healthissues:null,

//     willingtomarry:()=>{

//         console.log("eagerly waiting");

//     }

// }

// console.log(biodata);

 

o   Constructor object.

Example: //construtor way

// let biodata2 = new Object();

// biodata2.name="raj"

// biodata2.age=27

// biodata2.dob="28-05-1997"

// biodata2.job="doctor"

// biodata2.salary=300000

// biodata2.exGirlFriend=true

// biodata2.futuregoals=["visiting bali","earning 400000"]

// biodata2.healthissues=null

// biodata2.willingtomarry=()=>{

//     console.log("eagerly waiting");

// }

// console.log(biodata2);

 

Accessing the properties of an object

·        There are two ways through which we can access the object properties.

o   1)Dot notation

o   2)Box notation

// let simple={

//     name:"abc",

//     age:19,

//     isSingle:false,

//     fun:()=>{

//         console.log("Specify something");

//     }

// }

Dot notation

Box notation

// console.log(simple.name);

// console.log(simple.age);

// console.log(simple.isSingle);

// simple.fun();

 

// console.log(simple["name"]);

// console.log(simple["age"]);

// console.log(simple["isSingle"]);

// simple["fun()"];

// //here when dealing with the functions in box notation we will not get the correct result.

 

 

 

 

 

 

Dealing with const keyword

Arrays:

·        Modification of individual elements is possible:

Example:

 // const arr=["tmr",'is','html','mock']

// arr[2]="css"

// console.log(arr);//Output:new array

 

·        Reassigning new array is not possible

// const arr=["tmr",'is','html','mock']

 

//reassigning entire array is not possible

// arr=["tmr","is","css","mock"]

// console.log(arr);//Output:Error

 

 

Objects:

·       Modifying Individual properties is possible.

Example:
// const obj={

//     name:"ravi",

//     age:24

// }

//modifying individual properties is possible

// obj.name="ravi M"

// console.log(obj);

Object Properties and methods

1.     Delete:

·        It is used to delete the specific property of an object

·        Example:

let obj={

name:"abc",

age:24,

place:"hyd"

}

 

delete obj.place;

2.     Object,keys()

·        It is used to extract the key names of an object inside an array

Example:

let obj={

    name:"abc",

    age:24,

    place:"hyd"

}

console.log(Object.keys(obj));

 

Output: [name,age,place]

3.     Object.values()

·        It is used to extract the values of the object inside an array

Example:

 let obj={

    name:"abc",

    age:24,

    place:"hyd"

}

console.log(Object.values(obj));

 

output :[abc,24,hyd]

4.     Object.entries()

·        It returns an array of array(nested array) which consists of both Object keys and values.

Example:

let obj={

    name:"abc",

    age:24,

    place:"hyd"

}

 

console.log(Object.entries(obj));

 

output: [

            [“name”,”abc”],

            [“age”,24],

            [“place”,”hyd”]

]

 

5.     Object.fromEntries:

·        It converts back array of array into object.

Example:

/*

let arr=[

            [“name”,”abc”],

            [“age”,24],

            [“place”,”hyd”]

]

Console.log(Object.fromEntries(arr));

*/

Output: {

    name:"abc",

    age:24,

    place:"hyd"

}

6.     Object.assign():

·        This method is mainly used to copy the properties of one object and place into another object.

·        Copying properties from one single object.

Example:

//@ copying properties from one single object

// let obj={}

// let newobject = Object.assign(obj,biodata);

// console.log(newobject);

 

// let newobject = Object.assign({},biodata);

// console.log(newobject);

·        Copying properties from multiple objects.

Example:

//@ copying from multiple objects

// let obj={

//     place:"hyderabad",

//     name:"Rahul"

// }

// let newobj=Object.assign({},biodata,obj)

// console.log(newobj);

 

·        Converting array to an object.

Example:

 //@ converting array into an object

// let arr=["hyderabad","secunderabad","gachibowli","kukatpally"]

// let newOB=Object.assign({},arr)

// console.log(newOB);

·        Conveting a String to an object.

Example:

//@ converting String to an object

// let string="hello"

// let Nobj=Object.assign({},string)

// console.log(Nobj);

 

7.     Object.seal():

·        This method prevents from adding and deleting of the properties into the object, but modification of the existing property is possible.

·        Addition of the property is not possible.

Example:

 // let obj={

//     name:"rahul",

//     age:20

// }

// console.log(obj)

// Object.seal(obj)

 

//@addition of the property is not possible

// obj.place="Hyderabad"

// console.log(obj);

 

·        Modification of the property is not possible.

Example:

//@Modification of the property is possible

// obj.name="tharun"

// console.log(obj.name);

·        Deletion of the property is not possible.

Example:

 //@deletion of the property is not possible

// delete obj.name;

// console.log(obj);

8.     Object.freeze():

·        This method is used to prevent addition, modification and deletion of the properties from an object.

·        Addition of a property is not possible.

Example:

 // let obj={

//     name:"rahul",

//     age:20

// }

// console.log(obj)

// Object.freeze(obj)

 

//@addition of the property is not possible

// obj.place="Hyderabad"

// console.log(obj);

·        Modification of the property is not possible.

Example:

//@Modification of the property is not possible

// obj.name="tharun"

// console.log(obj.name);

·       Deletion of the property is not possible.

Example:

 //@deletion of the property is not possible

// delete obj.name;

// console.log(obj);

 

 

 

Addition

Modification

deletion

Object.seal

Object.freeze

 


Functions

·        Functions are the block of code that is used to perform a specific task

·        It improves the readability of the code

·        For a function to execute we need to call the function

·        It increases the reusability of the code by calling the function multiple times

·        There are two types of functions in general

o   Function declaration

o   Function expression

Function declaration

·        It is also known as general function,common function,naming function etc

Syntax:

 

/*

function identifier(parameters){

    /code

}

identifier(arguments)

*/

 

Example:

// function display(){

//     console.log(hello)

// }

// display()

 

Behavior of function

 

//* Function without parameter and without return keyword

 

// function add(){

//     console.log(2+2);

// }

// add();

 

//* Function without parameter and with return keyword

 

// function print(){

    //     return "name"

    // }

    // // console.log(print());

    // let result = print();

    // console.log(result);

   

   

//* Function with parameter and without return keyword

 

// function add(a,b){

    //     console.log(a+b);

    // }

    // add(5,3)//8

 

//* Function with parameter and with return keyword

 

// function multiply(a,b){

//     return a*b

// }

// console.log(multiply(5,3));//15

 

// missing argument

 

// function display(a,b){

//     console.log(a+b);

// }

// display(10)//NaN

 

//passing extra arguments

 

// function extra(a,b){

//     console.log(a*b);

// }

// extra(10,20,30)

 

Function expression

·        It provides a way for creating a function without specifying the name(Identifier) for the function.

·        To execute this kind of function store them in a variable & invoke the function with the variable name.

 

Anonymous function:

·        The function which doesn’t have any name are referred to as Anonymous function.

Syntax:

/*

variable_name = function(){

    /code to be executed

}

variable_name()

*/

 

Example:

//anonymous function

//  let anonymous = function(){

//     console.log("hello world");

//  }

//  anonymous()

 

Arrow function:

·        Arrow function does not have function keyword aswell as function name.

·        They were introduced in ES6 version.

Syntax:

/*

variable_name =()=>{

    /code to be executed

}

variable_name()

*/

 

Example:

//Arrow function

 

// let arrow = ()=>{

//     console.log("this is an arrow function");

// }

// arrow();

 

Types of arrow functions:

·        There are two types of arrow functions based on return keyword

1.Explicit return Arrow function

·        In explicit return arrow function we want to specify the return keyword

Example: //EXPLICIT RETURN ARROW FUNCTION

// let result=(a,b)=>{

//     return a*b;

// }

// console.log(result(10,20));

 

2.Implicit return Arrow function

·        Whenever there is one line of code to be executed then there is no need of parenthesis() and return keyword

Example:

//IMPLICIT RETURN ARROW FUNCTION

// let result=(a,b)=>a*b;

// console.log(result(10,20));

 

//example2

// let b= ()=>console.log("hello");

// b();

 

 

 

 

Behavior of arrow function

 

·        Single parameter:

o   When a Arrow function is having single parameter then parenthesis is optional

 

Example :

//single parameter

// let c = val =>val

// console.log(c("Name it is"));// when implicit arrow function contains single parameter then the paranthesis can be removed and still you will get the output

 

·        No parameter:

o   When arrow function is not having any parameter then parenthesis replaced by underscore

 

Example:

//no parameter

// let b=_=>console.log("hello");

// b()// when implicit arrow function has no parameters the paranthesis can be replaced with underscore and still you will get the same output

 

 

3.Immediate Invoked function expression(IIFE)

·        Function after declaration is immediately invoked.

·        It is only called once.

Example:

// (function(){

//     console.log("hello world");

// })();

 

// (()=>{

//     console.log("How are you");

// })();

 

// (function display(){

//     console.log("this is IIFE");

// })();

 

 


Higher order functions (vimp)

·       higher order functions are the functions which take another function as its argument and return a new function.

·       The function which is being passed as an argument to higher order function is called callback function.

 

Example:
//HIGHER ORDER FUNCTIONS

 

let add = (a,b)=>{

    return a+b;

}

 

let sub = (a,b)=>{

    return a-b;

}

 

let common = (a,b,task)=>{

    return task(a,b)

}

console.log(common(10,20,add));

console.log(common(500,27,sub));

 

/* A function which takes another function as its argument and return a new function is called higher order function

   "And the function which is given as an argument to this higher order function is called callback function "

   Its like supermarket consisting of different sections of items and when required instead of going to specific individual shops we

   just visit the supermarket

   */


Hoisting in functions

·       It is the process of moving the declrations of functions to the top of the scope.

·       (or) Accessing the functions even before its declaration

 

Example

//hoisting in functions

 

simple()  //output = simple

function simple(){

    console.log("simple");

}

 

// in funtion expression

 

simple2()//ReferenceError: Cannot access 'simple2' before initialization

let simple2 =()=>{

    console.log("hello this is testing function expression if hoisting is done or not ");

}

 

 

Note:

Hoisting is done in functions.

·       Function declaration – will get the output.

·       Function expression – value is not initialized.

 


Function currying (Vimp)

·       It is the process of transforming a function taking multiple arguments into nested series of functions each taking single argument.

 

Each taking single argument.

Math Object

·         Math is an object that provides mathematical functions and constants that allows to perform various mathematical operations like rounding numbers, finding maximum and minimum number, generating random numbers etc.

·         To access the value of pi under the math object there is a property called PI

Example: //PI

console.log(Math.PI);//3.141592653589793

 

some of the methods present under the math object are :

§  max():

o   It is used to find the maximum number from the given range of values.

Example: //max()

// let max=Math.max(10,2,3,4,5,199)

// console.log(max);//199

§  min():

o   it is used to find the minimum number from the given range of values.

Example: //min()

// let min=Math.min(10,2,3,4,5,199)

// console.log(min);//2

§  ceil():

o   This method returns the next upcoming integer for the specified number.

Example: //ceil()

// console.log(Math.ceil(2.3));//3

// console.log(Math.ceil(4.9));//5  

// console.log(Math.ceil(3.1));//4

// console.log(Math.ceil(-2.1));//-2

// console.log(Math.ceil(2.00001))//3

§  floor():

o   This method returns the previous integer value for the specified number.

Example:

//floor()

// console.log(Math.floor(2.3));//2

// console.log(Math.floor(4.9));//5

// console.log(Math.floor(3.1));//3

// console.log(Math.floor(-2.1));//-3

// console.log(Math.floor(2.00001));//2

 

§  round():

o   This method performs the rounding operation based upon certain conditions.

Ø  If the value is greater than or equal to (.5) decimal part then it returns the next integer value

Ø  If the value is less than (.5) with respect to the decimal part then it returns the previous integer value

Example:

//round()

// console.log(Math.round(2.3));//2

// console.log(Math.round(4.9));  //5

// console.log(Math.round(3.1));  //3

// console.log(Math.round(-2.1));  //-2

// console.log(Math.round(2.00001));//2

§  abs():

o   This method converts the negative value to a positive value.

Example:

//abs(){RETURNS POSITIVE VALUE}

// console.log(Math.abs(-3));//3

// console.log(Math.abs(5));//5

// console.log(Math.abs(0));//0

// console.log(Math.abs(-0));//0

§  trunc():

o   This method is used to remove the decimal part for a number.

Example: //trunc(){REMOVES THE DECIMAL FROM THE NUMBER}

// console.log(Math.trunc(5.2));//5

// console.log(Math.trunc(-3.12));//-3

// console.log(Math.trunc(5));//5

// console.log(Math.trunc(-0));//-0

§  sign():

o   This method checks whether the number is positive or a negative number.

Ø  If positive it returns 1

Ø  If negative it returns -1

Ø  If 0 it returns 0

Ø  If -0 It returns -0

Example:

//sign(){TELLS WEATHER THE VALUE IS POSITIVE OR NEGATIVE}

// console.log(Math.sign(-5));//-1

// console.log(Math.sign(5));//1

// console.log(Math.sign(0));//0

// console.log(Math.sign(-0));//-0

// console.log(Math.sign(-5.3));//-1

§  pow():

o   This method finds the power value and returns as a result.

Example:

//Pow()

// console.log(Math.pow(2,3));//8

// console.log(Math.pow(5,2));//25

// console.log(Math.pow(5,10));//9765625

// console.log(Math.pow(-5,2));//25

// console.log(Math.pow(-5,-2));//0.04

§  sqrt():

o   it is used to find the square root value for the given number.

o   It cannot take negative values.

Example: //sqrt()

// console.log(Math.sqrt(4));//2

// console.log(Math.sqrt(25));//5

// console.log(Math.sqrt(10));//3.1622776601683795

// console.log(Math.sqrt(-10));//NaN

§  cbrt():

o   it is used to find the cube root value for the given number.

o   Here we can use negative values.

Example: //cbrt()

// console.log(Math.cbrt(8));//2

// console.log(Math.cbrt(125));//5

// console.log(Math.cbrt(20));//2.7144176165949063

// console.log(Math.cbrt(-10));//-2.154434690031884

§  sin(),cos() and tan():

o   These methods return the sin,cos and tan values for the specified angle.

o   Angle can be either degree or radian.

o   By default, these methods take the values in radians.

o   To convert radians into degree multiply the radian value with (Pi/180)

Example: //sin(),cos() and tan()

let piby180=Math.PI/180

 

sin()

// console.log(Math.sin(0*piby180));//0

// console.log(Math.sin(30*piby180));//0/4999999999999

 

Cos()

// console.log(Math.cos(45*piby180));//0.7071067811865476

// console.log(Math.cos(60*piby180));//0.5000000000000001

// console.log(Math.cos(90*piby180));//6.123233995736766e-17 ~ 0 (use round() to get round off value)

 

tan()

// console.log(Math.tan(0*piby180));//0

// console.log(Math.tan(30*piby180));//0.5773502691896257

 

§  random():

o   This method generates a random value between the range 0 to 1.

Example: //Random()

//console.log(Math.random())

o   Generating random numbers between the range of 0-6

Example: //*generating the random values till range 0-6

console.log(Math.floor(Math.random()*6))

console.log(Math.ceil(Math.random()*6))

console.log(Math.trunc(Math.random()*6))

 

o   Generating random numbers between the range 100-200

Example:

//generating random number between the range 100-200

console.log(Math.floor(Math.random()*100)+100)

 


Date Object

·         Date is an inbuilt constructor object that allows to get the date and the time.

Example: let date=new Date()

console.log(date);

 

//!Date Methods

// console.log(date.getDate());

// console.log(date.getMonth());

// console.log(date.getFullYear());

// console.log(date.getDay());

// console.log(date.toDateString());

 

// date.setDate(28)

// date.setMonth(1)

// date.setFullYear(2024)

// console.log(date);

 

//!Timemethods

// console.log(date.getHours());

// console.log(date.getMinutes());

// console.log(date.getSeconds());

// console.log(date.getMilliseconds());

// console.log(date.getTime());//{Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC}

 

// date.setHours(14)

// date.setMinutes(70)

// date.setSeconds(14)

// date.setMilliseconds(142)

// console.log(date.getMilliseconds());

// console.log(date);

 


For-in and for-of loop

These are the loops that are used to iterate upon the Strings, arrays and object. Based on some condition.

// let str="tommorow is css mock just assume guys";

// let arr=["kkr","srh","rr"]

// let obj={

//     name:"virat kohli",

//     age:37,

//     hasAttitude:true

// }

 

1.     for-in loop

·        it is one of the loop that is used to iterate upon the string and arrays based on the index value and iterate upon the object based on key value.

Syntax:

// for(variable in string/Array/object)

//     {

//     -------------

//     -------------

// }

·        Examples:

Values:

// let str="tommorow is css mock just assume guys";

// let arr=["kkr","srh","rr"]

// let obj={

//     name:"virat kohli",

//     age:37,

//     hasAttitude:true

// }

 

String:

// for(let val in str){

//     console.log(val);//return the index value of string from starting charecter to ending charecter

// }

 

Arrays:

// for(let val in arr){

//     console.log(val);//o/p 0,1,2 as there are 3 elements in array

// }

 

Object:

// for(let val in obj){

//     console.log(val);//output:name,age,hasAttitude-> based on key

// }

 

2.     for-of loop

·         it is one of the loop that is used to itereate upon each character of string and each element of array.

·         Object is not iteratable.

Syntax

// for(variable of string/Array/object)

//     {

//     -------------

//     -------------

// }

·        Examples:

Values:

// let str="tommorow is css mock just assume guys";

// let arr=["kkr","srh","rr"]

// let obj={

//     name:"virat kohli",

//     age:37,

//     hasAttitude:true

// }

 

Strings:

// for(let val of str){

//     console.log(val);//returns each charecter of the string.

// }

 

Arrays:

// for(let val of arr){

//     console.log(val);//output:kkr srh rr

//     }

Objects:

// for(let val of obj){

//     console.log(val);//Uncaught TypeError: obj is not iterable

// }

 

Spread operator & Rest parameter.

·        These both are features in ES-6 version of javascript that involves the use of three dots(…) based on the type of using it.

 

1.     Spread operator:

o   It is mainly used to copy or merge the values form one or more arrays (or) objects.

Example:

// Arrays

// copying elements of one array into another

// let arr1=[1,2,3,4,5,6]

// let arr2=[...arr1,7,8,9,10]

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

 

// combining two or more arrays

// let arr1=[1,2,3,4,5,6]

// let arr2=[7,8,9,10]

// let arr3=[...arr1,...arr2]

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

 

// spread operator can be placed anywhere in an array

// let arr1=[1,2,3,4,5]

// let arr2=[6,...arr1,7,8,9,10]

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

 

//Objects

// copying properties from one object into another

// let obj1={

//     name:"ravi",

//     age:24

// }

// let obj2={

//     ...obj1,

//     place:"hyderabad"

// }

// console.log(obj2);//output:{ name: 'ravi', age: 24, place: 'hyderabad' }

 

// combining two or more objects

//  let obj1={

//     name:"ravi",

//     age:24

// }

// let obj2={

//     place:"hyderabad"

// }

// let obj3={

//     ...obj1,

//     ...obj2

// }

// console.log(obj3);//output:{ name: 'ravi', age: 24, place: 'hyderabad' }

 

2.     Rest parameter:

o   It is used to gather the function arguments into an array

o   Rest parameter should always written at the last of parameter list.

Example:

// function display(a,b,c,...rest){

//     console.log(a,b,c,...rest);

// }

// display(1,2,3,4,5,6,7,8)//output:1 2 3 4 5 6 7 8

 

// accessing arguments without passing parameters

// function hello(){

//     console.log(arguments);

// }

// hello(1,2,3,4,5)//output:[Arguments] { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }

 

//converting array into an object

// let arr=[1,2,3,4,5,6]

// let rest=Object.assign({},arr)

// console.log(rest);//output:{ '0': 1, '1': 2, '2': 3, '3': 4, '4': 5, '5': 6 }

// (or)

// let obj={...arr}

// console.log(obj);//output:{ '0': 1, '1': 2, '2': 3, '3': 4, '4': 5, '5': 6 }

o   Note:
 . . .  used in the function parameter are referred to as rest parameters apart from that it is referred to as spread operator.

 

 


Use strict.

·        It is a keyword which tells the browser to strictly check the piece of code and display the errors whenever necessary.

Example: //!Example1:

// "use strict"

// a=10;

// console.log(a);

 

//!Example2:

// "use strict"

// function hello(){

//     a=true;

//     console.log(a);//uncaught Reference error: a is not defined

// }

// hello()

 

// "use strict"

// function display(a,b,b){

//     console.log(a+b+b);//uncaught Syntaxerror : Duplicate parameter name not allowed in this context

// }

// display(10,20,30)

 

SetTimeout and setInterval

·        These are the higher order functions which are used to perform a specific task after the specified duration of time.

·        Here the time duration should be specified in milliseconds.

·        These are the asynchronous operations which take some time to perform the task.

SetTimeout():

·        SetTimeout is a function used to execute a specified function or piece of code once after a specified delay(in milliseconds).

·        It takes two parameters: a function or code to execute and the delay in milliseconds.

·        Syntax:
/*setTimeout((){
code to be executed
},timeduration);*/

Example: // setTimeout(()=>{

//     console.log("setTimeout:Please father call your friend")

// },10000)

 

ClearTimeout()

·        clearTimeout is a function used to cancel a timeout set with setTimeout before the specified function is executed,

·        it takes one parameter:the identifier of the timeout you want to cancel which is returned by setTimeout.

Example: //!clearTimeout()

// let time1=setTimeout(()=>{

//     console.log("setTimeout:please father call your friend");

// },5000)

 

// setTimeout(()=>{

//     clearInterval(time1)

//     console.log("cleared in 3s");

// },3000)

SetInterval()

·        setInterval is a function used to repeatedly execute a specified function or code at a specified interval (in milliseconds) until it is stopped.

·        It takes two parameters: a function or code to execute and the interval between executions in milliseconds.

·        Syntax:
/*const intervalid =setInterval(()=>{
             //code to be executed
},timeduration);*/

Example: // setInterval(()=>{

//     console.log("setInterval:Please father call your friend")

// },5000)

clearInterval()

·        clearInterval is a function used to stop the interval execution set by setInterval.

·        It takes one parameter: the identifier of the interval you want to stop, Which is returned by setInterval.

Example: //!clearInterval()

// let count=0

// let time=setInterval(()=>{

//     console.log("I love you");

//     count++;

//     if(count==5){

//         clearInterval(time);

//         console.log("cleared after 5 times");

//     }

// },3000)

 

 



Full javascript course Documented By Ravi Prakash Mathi