0% found this document useful (0 votes)
4 views110 pages

JavaScript Notes PDF

JavaScript, introduced in 1995, is a lightweight, object-oriented scripting language that enables dynamic interactivity on web pages and is supported by all major browsers and operating systems. Key features include weak typing, case sensitivity, and the ability to create both client-side and server-side applications. The document covers various aspects of JavaScript, including syntax, variables, control structures, loops, and built-in methods, along with examples and exercises for practical understanding.

Uploaded by

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

JavaScript Notes PDF

JavaScript, introduced in 1995, is a lightweight, object-oriented scripting language that enables dynamic interactivity on web pages and is supported by all major browsers and operating systems. Key features include weak typing, case sensitivity, and the ability to create both client-side and server-side applications. The document covers various aspects of JavaScript, including syntax, variables, control structures, loops, and built-in methods, along with examples and exercises for practical understanding.

Uploaded by

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

JavaScript Introduction

▪ Introduced in the year 1995.


▪ Light-weight Object Oriented Scripting Language.
▪ Enables dynamic interactivity on web pages.
Features-
▪ Almost every popular web browser supports JavaScript as they provide built-in
execution environments.
▪ The syntax and structure of the JavaScript is almost similar to the C programming
language. Thus, it is a structured programming language.
▪ JavaScript is a weakly typed language, means there is no need to declare the type
of a variable before using it.
▪ It is an interpreted language and case sensitive scripting language.
▪ JavaScript is supportable by almost every operating system available nowadays,
including, Windows, macOS, Linux, etc.
Prepared by: Amitabh Srivastava
JavaScript Applications
Apart from its features we can build anything on our HTML page with
JavaScript that will be supported by every browser.

Some of the JavaScript applications are:


❑ Client-side validation,
❑ Dynamic drop-down menus,
❑ Displaying date and time,
❑ Displaying pop-up windows and dialog boxes (like an alert dialog
box, confirm dialog box and prompt dialog box),
❑ Displaying clocks, Calendar, etc.
Prepared by: Amitabh Srivastava
First JavaScript Program
▪ The <script> tag in HTML is used to define the client-side script. The <script>
tag contains the scripting statements, or it points to an external script file.

▪ The value of type attribute is text/javascript is the content type that provides
information to the browser about the data. It is the default type value.

▪ The document.write() function is used to display dynamic content through


JavaScript. Here, document is an inbuilt object and write() is the method of the
document object.

Example-
<script type="text/javascript">
document.write("Welcome to the world of JavaScript");
</script> Prepared by: Amitabh Srivastava
document.write()
▪ document.write() in JavaScript is a function that is used to display some text in the browser
window.

▪ When document.write() function is used after the HTML is fully loaded, it will delete all the
contents of an existing HTML document and will show only contents that are inside
the document.write() function.

▪ We can concatenate strings by using “+” operator.


document.write("My roll number is " +10);

▪ We can do arithmetic operations and display them in our result.


document.write("Sum of 5+5= " + (5+5));

▪ Tags are easily interpreted as HTML elements.


document.write("<h2>This is a HTML content</h2>");
Prepared by: Amitabh Srivastava
Where To Put JavaScript Code
We can put our JavaScript code in various places like:

• Between the body tag of html

• Between the head tag of html

• In .js file (external javaScript)

• In inspection mode (ctrl+shift+i)

Comments in JavaScript-
To make any line of JavaScript as a comment, use double slash ( // ). If you want to
make multiple lines as a comment,Prepared
use by: /*Amitabh
andSrivastava
*/.
External JavaScript
We can create external JavaScript file and embed it in many html pages.
It provides code re-usability because single JavaScript file can be used in several html pages.
An external JavaScript file must be saved by .js extension.
Example-
sample.html: sample.js:

Prepared by: Amitabh Srivastava


console.log()
▪ All modern browsers have a web console for debugging.
▪ To open web console window press ctrl + shift + j in the browser.
▪ The console.log() method is used to print messages/variables to the
console.
Example-

Prepared by: Amitabh Srivastava


console.table()
▪ The console.table() method is used to print data in table format to
the console.
Example- Output-

Prepared by: Amitabh Srivastava


JavaScript Variables
A JavaScript variable is simply a name of storage location.
By default, the variable has assigned a special value ’undefined’ if no value is assigned to
it.
Variable name must start with a letter (a to z or A to Z), underscore ( _), or dollar( $ ) sign.
After first letter we can use digits (0 to 9), for example ‘value1’.
JavaScript variables are case sensitive, for example ‘a’ and ‘A‘ are different variables.
Example-

Prepared by: Amitabh Srivastava


Exercise
Write a JavaScript program to swap two variables without using third variable?
Assume x = 31 and y = 15.
Display your result in the console window.

Solution-

Prepared by: Amitabh Srivastava


Local Vs. Global Variables
There are two types of variables in JavaScript: local variable and global variable.
Example-
Here, variable ‘x’ outside the function will be
considered as a global variable and hence
function b() can easily access it and calculate the
sum as-
5 + 50 = 55.

But, variable ‘x’ inside function a() is a local


variable and its scope is limited to that function
only and hence function b() cannot access the
value of a local variable defined under different
function.
Prepared by: Amitabh Srivastava
Const Keyword
▪ The const declaration creates a read-only reference to a value.
▪ The value of a constant cannot change through re-assignment, and it can't be re-
declared.
▪ The following rules are TRUE for a variable declared using the const keyword-
• Constants cannot be reassigned a value.
• A constant cannot be re-declared.
• A Constants must be initialized during its declaration.

Example-
const x = 10
x = 12 // will produce error ‘Assignment to constant variable’

Prepared by: Amitabh Srivastava


Typecasting: string to int
▪ Typecasting means conversion of one data type into another.
Example-
This code will actually do the concatenation of
numbers instead of performing addition
operation.
Because, the prompt() method always creates a
string variable.

We need to parse/type-cast the values entered by the user from string type to an integer type.

Prepared by: Amitabh Srivastava


Typecasting: string to float
▪ Conversion of String to Float type.

Example-

Prepared by: Amitabh Srivastava


Typecasting: number to string
▪ Conversion of Number (integer/float) to String type.

Example-

Prepared by: Amitabh Srivastava


Conditional Statements: if
▪ The conditional statement will perform some action for the specific condition.
▪ If the condition meets then the particular block of action will be executed otherwise it will execute
another block of action that satisfies that particular condition.
▪ In JavaScript we have if...else blocks to control the flow of our program on condition basis.
Example-
If we do not provide the curly braces ‘{‘ and ‘}’
after if( condition ) then, by default, if statement will
consider the immediate one statement to be inside its
block.

Prepared by: Amitabh Srivastava


Conditional Statements: else
▪ The if statement tells us that if a condition is true, it will execute a block of statements and if the
condition is false, it won’t.
▪ But what if we want to do something else if the condition is false. Here comes the else statement.
▪ We can use the else statement with the if statement to execute a block of code when the condition
is false.
Example-

Prepared by: Amitabh Srivastava


Conditional Statements: nested
A nested if is an if statement that is the target of another if or else.
Nested if statements mean one if statement inside another if statement.
Example-

Prepared by: Amitabh Srivastava


Conditional Statements: ladder
▪ With the help of if-else-if ladder statement, we can decide among multiple options.
▪ In this ladder, if statements are executed from top to down.
▪ As soon as one of the conditions controlling the if is true, the statement associated with that if is
executed, and the rest of the ladder is bypassed.
▪ If none of the conditions is true, then the final else statement will be executed.
Example-

Prepared by: Amitabh Srivastava


Switch Case
The switch case statement is also used for decision making purposes.
Scenario- Consider a situation when we want to test a variable for hundred different values and
based on the test, we want to execute some tasks. Using an if-else statements for this purpose will be
less efficient over switch case statements and also it will make the code look messy.
Syntax-
switch(expression) • Expression can be of numbers or strings type.
{ • Statements inside the case executes whose case value matches
case value1: with the expression. Duplicate case values are not allowed.
statement1;
break; • The default statement is optional. If the expression passed to
case value2: switch does not matches with value in any case, then the statement
statement2; under default will be executed.
break;
. • The break statement is used inside the switch to terminate a
.
case valueN: statement sequence.
statementN;
break;
• The break statement is optional. If omitted, execution will
default: continue on into the next case.
statementDefault;
Prepared by: Amitabh Srivastava
}
Switch Case: Example

Prepared by: Amitabh Srivastava


Let Vs. Var
The scope of ‘let’ is limited to the curly braces while the variables declared using
‘var’ can be access outside its defined scope.

Example-1: Example-2:

It will give error while accessing ‘x’ outside.

Prepared by: Amitabh Srivastava


Exercise-1
Write a program that accepts a number from user and prints if it is an Even or Odd?

Solution-

Prepared by: Amitabh Srivastava


Exercise-2
Write a program to find out largest of two numbers?

Solution-

Prepared by: Amitabh Srivastava


Exercise-3
Write a program to find out
largest of three numbers?

Logic-

• num1 is the largest if num1>num2 and


num1>num3.

• num2 is the largest if num2>num3.

• Else print num3 as largest.

Prepared by: Amitabh Srivastava


Exercise-4
Write a program to check whether a number is between start and end range?

Solution-

Prepared by: Amitabh Srivastava


Exercise-5
Write a program to check whether an entered number is EVEN or ODD?
Display your result inside <H1> tag using innerHTML method like, “12 is EVEN” or “3 is ODD”.

Prepared by: Amitabh Srivastava


Loops
▪ Looping in programming languages is a feature which facilitates the execution of
a set of instructions repeatedly while some condition evaluates to true.
▪ There are three types of loops in JavaScript.
1. for loop 2. while loop 3. do-while loop

Entry-Controlled loops: In this type of loops the test condition is tested before
entering the loop body. For Loop and While Loop are entry-controlled loops.

Exit-Controlled Loops: In this type of loops the test condition is tested or evaluated
at the end of loop body. Therefore, the loop body will execute at least once,
irrespective of whether the test condition is true or false. do – while Loop is an exit-
controlled loop. Let’s explore each of these loops one by one with examples.
Prepared by: Amitabh Srivastava
While Loop
▪ While loop allows code to be executed repeatedly based on a given Boolean
condition.

▪ It should be used if number of iterations is not known.


Syntax- Example-
while(Boolean condition)
{
Statements to be executed...;
}

Prepared by: Amitabh Srivastava


While loop: Exercise-1
Write a program to display Even and Odd numbers from 1 to 20 in font-size 22px?
All the numbers should be in same line and Even numbers in Blue color and Odd numbers in
Red color. Refer the below output.

Prepared by: Amitabh Srivastava


While loop: Exercise-2
Write a program to display ODD numbers from 1 to 20 in font-size 22px? At the end, also display
the sum of all ODD numbers.

Prepared by: Amitabh Srivastava


While loop: Exercise-3
Write a program to display the number of digits in a given number? Also display the sum of all
digits?

Prepared by: Amitabh Srivastava


For Loop
▪ Unlike a while loop, a for statement includes the initialization, condition and
increment/decrement in one line thereby providing a shorter, easy to debug
structure of looping.

Syntax-
for (initialization condition; testing condition; increment/decrement)
{ Example-
Statements to be executed...
}

Prepared by: Amitabh Srivastava


For loop: Exercise-1
Write a program to display the table of a number entered by the user?
Solution-

Prepared by: Amitabh Srivastava


For loop: Exercise-2
Write a program to display all the multiples of 3 and 5 from 1 to 30? Show your result in console
window.
Solution-

Prepared by: Amitabh Srivastava


For loop: Exercise-3
Write a program to create a table by taking number of rows and columns from the user? Also
print numbers in sequence in every cell. Refer below figure.

Prepared by: Amitabh Srivastava


For loop: Exercise-3: Code

Prepared by: Amitabh Srivastava


Break Statement
▪ The break statement is used to jump out/exit from a loop.
▪ It breaks the loop and continues executing the code after the loop.
▪ It is also used to jump out from a switch() statement.

Example-

Prepared by: Amitabh Srivastava


== and === Operators
▪ Double equals (==) operator compares the datatypes of the operands and if they are different,
then the JavaScript Engine automatically converts one of the operands to be the same as the
other one in order to make the comparison possible.
▪ Triple equals (===) operator, while comparing the variables, first checks if the types differ. If
they do, it returns false. If the types match, then it checks for the value. If the values are same, it
returns true.

Example-

Prepared by: Amitabh Srivastava


Continue Statement
▪ The continue statement jumps over one iteration in the loop.
▪ It breaks the current iteration of the loop and continues executing the next iteration in
the loop.

Example-

Prepared by: Amitabh Srivastava


Do-while Loop
▪ do-while loop is similar to while loop with only one difference and that is, it checks for
the condition after the first iteration of the loop statements.
Syntax-
do
{
Statements to be executed... Example-
}
while (condition);

Prepared by: Amitabh Srivastava


For-in Loop
▪ For-in loop in JavaScript is used to iterate over properties of an object having
values in key-value pair.

Example-

Prepared by: Amitabh Srivastava


Loops: Practice-1
Write a program to print the following star pattern after asking the no. of rows from the user?
Also print the row number at the beginning of each row.

Enter number of rows: 7 Solution-

Prepared by: Amitabh Srivastava


Loops: Practice-2
Write a program to print the following number’s pattern after asking the no. of rows from the
user?
Enter number of rows: 7 Solution-

Prepared by: Amitabh Srivastava


Methods of String Object
▪ charAt()- returns character at given index.

▪ charCodeAt()- returns the ASCII value of the character at given index.

▪ indexOf()- returns the index of given character. If not found, returns -1.

▪ toLowerCase()- converts the string to lowercase.

▪ toUpperCase()- converts the string to lowercase.


Prepared by: Amitabh Srivastava
Methods of Math Object
▪ Math.abs()- It returns the absolute value without +ive or -ive sign.
console.log(Math.abs(-7)); //returns 7
▪ Math.ceil()- It returns the smallest integer greater than or equal to the value we pass.
console.log(Math.ceil(4.2)); //returns 5
▪ Math.floor()- It returns the largest or equal integer that is less than the given value.
console.log(Math.floor(4.7)); //returns 4
▪ Math.min()- It returns the minimum value from the supplied parameters.
console.log(Math.min(12,34,27.5, 200, 7, 11, 45)); //returns 7
▪ Math.max()- It returns the maximum value from the supplied parameters.
console.log(Math.max(12,34,27.5, 280, 67, 11, 45)); //returns 280
▪ Math.random()- It returns a random number between 0(inclusive) and 1(exclusive).
console.log(Math.random()); //returns random no. between 0 and 1
▪ If you want to generate random number between 0 and 9:
console.log(Math.floor(Math.random() * 10)); //returns random no. between 0 and 10.
Prepared by: Amitabh Srivastava
Methods of Date Object

Prepared by: Amitabh Srivastava


Date.now()
▪ JavaScript date.now() method is used to return the number of milliseconds
elapsed since January 1, 1970, 00:00:00 UTC.
▪ Since now() is a static method of Date object, it will always be used as
Date.now().

Syntax- let d = Date.now()

Example-

Prepared by: Amitabh Srivastava


Assignment
1. Write a JavaScript code to convert the first letter of every word in
Uppercase in the text given? You can use only toUpperCase()
method and not any other method.
var text = “hello, let’s do the coding!”;
Output- newText = “Hello, Let’s Do The Coding!”

2. Write a JavaScript code to print the reverse of a given number? You


cannot use any built-in methods except parseInt().
var num = 1234567;
Output- rev_num = 7654321 (this ‘rev_num’ must be of type number)
Prepared by: Amitabh Srivastava
Assignment-1: Solution
▪ Converting first letter of each word to uppercase.

Prepared by: Amitabh Srivastava


Assignment-2: Solution
▪ Reverse of a given number.

Prepared by: Amitabh Srivastava


JavaScript Arrays
▪ In JavaScript, an array is a single variable that is used to store multiple elements.
▪ It is used when we want to store list of elements and access them by a single variable.
▪ An array can store multiple values of different data types.
▪ There are basically two ways by which we can declare an array-
var myarray = []; // method 1
var myarray = new Array(); // method 2
Example by method-1: Example by method-2:

Prepared by: Amitabh Srivastava


Accessing Array Values
▪ With the help of index numbers we can access the values of an array.
▪ Index number of an array starts from 0.
▪ To find out the length of an array we have length property.
▪ Length of an Array is always one more than the highest index of an Array.
Length of an Array = highest index + 1.
Example-

Prepared by: Amitabh Srivastava


Accessing Array Values
▪ We can also access the elements of an array by using loops.
▪ For example, if we want to access all the items of an array, we can use either for loop or while
loop.
Example-

▪ OR, we can use join() method to display array elements-

Prepared by: Amitabh Srivastava


Practice-1
Write a program to print Even numbers in given array and create new array of sorted even numbers?
Given array-
arr = [ 13, 58, 23, 45, 26, 48, 100, 66 ]
Solution-

To sort the numbers properly use the following syntax.

Ascending order-
newarr.sort(function(a, b){return a-b})

Descending order-
newarr.sort(function(a, b){return b-a})

Prepared by: Amitabh Srivastava


Adding & Removing Elements
▪ Adding an element to the end of an array-
books.push("Two States");

▪ Adding an element to the beginning of an array-


books.unshift("Two States");

▪ Removing an element from the end of an array-


books.pop();

▪ Removing an element from the beginning of an array-


books.shift();
Prepared by: Amitabh Srivastava
In-between Insert / Deletion
Syntax:
Array.splice(start_index, deleteCount, [insert_item1, insert_item2, …]);

▪ delete 3 elements starting from index 1-


books.splice(1, 3);

▪ insert 3 elements starting from index 1-


books.splice(1, 0, "a", "b", "c");

▪ delete 2 elements starting from index 1 and add 3 elements-


books.splice(1, 2, "book1", "book2", "book3");
Prepared by: Amitabh Srivastava
Checking for an Array
To check whether a variable is an array, use Array.isArray() method.

Prepared by: Amitabh Srivastava


More Array Methods
▪ To determine the presence of an element in an array, we can use the include()
method. If the element is found, the method returns true, and false otherwise.
Example-

▪ The reverse() method reverses the elements' positions in the array so that the last
element goes into the first position and the first one to the last place.
Example-

Prepared by: Amitabh Srivastava


Array: Spread Operator
▪ Spread operators allow us to expand an array or object into its individual
elements.

▪ Spread operators are written using three consecutive dots (...), and they provide
us an easy way to break up an array or an object into its individual elements.

▪ Example-1: Example-2: converting string into array

Prepared by: Amitabh Srivastava


Merging via Spread Operator
▪ Example-1:

▪ Example-2: finding maximum number

Prepared by: Amitabh Srivastava


Array: Rest Operator
▪ The rest operator is essentially the opposite of the spread operator.
▪ It allow us to collect multiple elements into a single array or object.
▪ This is useful if number of arguments is not known a function may receive, and
you want to capture all of them as an array.

▪ Example-

Prepared by: Amitabh Srivastava


Array: Exercise-1
Write a program to convert all the array values in Uppercase? Let the array be-
arr1 = ["Node.js", "WEBTechnologies", "React-JS", "Python" ]

Solution-

Prepared by: Amitabh Srivastava


Array: Exercise-2
Write a program to delete all occurrences of a given element?

Prepared by: Amitabh Srivastava


Array: Exercise-3
Swap the case of each character of a string?

Prepared by: Amitabh Srivastava


JavaScript eval() method
▪ The eval() function in JavaScript is used to evaluate the expression.
▪ It evaluates the specified string as JavaScript code and executes it.
Example-

Prepared by: Amitabh Srivastava


Array Prototype Constructor
▪ The JavaScript array prototype constructor is used to allow to add new methods
and properties to the Array() object. If the method is constructed inside Array
object, then it will be available for every array.
Example-

Prepared by: Amitabh Srivastava


Array: Exercise-4
Create a JavaScript array prototype constructor to count string length?

Solution-

Prepared by: Amitabh Srivastava


Functions
▪ A function is a set of statements that take inputs, do some specific computation, and produces
output.
▪ Instead of writing the same code again and again at different places, we can write such repeated
statements inside a function and call that function.
▪ In JavaScript there are built-in functions as well as user-defined functions.
▪ To create/define a function, the keyword function is used.
Syntax-

function function_Name(Parameter1, Parameter2, ..)


{
statement...1;
statement...2;
statement...N;
[return statement / value;] // optional
} Prepared by: Amitabh Srivastava
Calling A Function
▪ After defining a function, the next step is to call it to make use of the defined function.
▪ We can call a function by using the function name separated by the value of parameters enclosed
between parenthesis and a semicolon at the end.
Syntax-
functionName( Value1, Value2, ..);
Remember- The number of parameters in defined function and in calling function must be same.

Example-

Prepared by: Amitabh Srivastava


Calling Function on Event
▪ We can also do that when user clicks on a button only then a specific function should
run.

Example-

Prepared by: Amitabh Srivastava


getElementById()
Scenario-
▪ An HTML has a text field and
we want that when visitor fill
its name in that text field and
clicks on the button, only then
showMsg() function should
call with a welcome message
containing the entered name by
the user/visitor.
▪ We need to pass the value
entered in a text field from
HTML form to JavaScript
function.
▪ JavaScript has
getElementById() method to
collect the value of specific
form element.
Prepared by: Amitabh Srivastava
JavaScript Events
▪ The change in the state of an object is known as an Event.

▪ When JavaScript code is included in HTML, it reacts over these events and allow
us to execute required code or set of statements.

▪ This process of reacting over the events is called Event Handling.

▪ JavaScript handles the HTML events via Event Handlers.

▪ Events are part of the Document Object Model (DOM) and every HTML
element contains a set of events which can trigger JavaScript Code.

▪ For example, when user clicks on an object in a browser, the “OnClick” Event
Handler is called. So you can easily add some code or set of codes to this
“OnClick” event which you want toby:execute
Prepared when this event occurs.
Amitabh Srivastava
JavaScript Event Types
➢ Mouse events-
▪ onClick, onMouseOver, onMouseOut, etc.

➢ Keyboard events-
▪ onKeyUp, onKeyDown.

➢ Form events-
▪ onFocus, onBlur, onSubmit, etc.

➢ Document evets-
▪ onLoad, onResize, etc. Prepared by: Amitabh Srivastava
JavaScript Event: Example-1

Prepared by: Amitabh Srivastava


Multiple Statements in One Event
▪ Multiple lines of code can also be write inside the onClick event attribute by
separating them using a semicolon.

Example-
onClick='x=2+5;alert("Sum of 2 and 5 is: "+x)'

OR, by using back-tick-


onClick='x=3+5;alert(`Sum of 3 and 8 is: ${x}`)'

Prepared by: Amitabh Srivastava


EventListener
▪ An EventListener is a procedure in JavaScript that waits for an event to occur.

▪ The simple examples of an event is a user clicking the mouse or pressing a key on the
keyboard.

So, there is an in-built function in JavaScript called addEventListener() which takes two
parameters, first is the event to listen for, and a second argument to be called whenever
the described event occurs.

Syntax-
element.addEventListener(event, listener / handler function);

Prepared by: Amitabh Srivastava


EventListener: Example-1

Prepared by: Amitabh Srivastava


EventListener: Example-2
▪ We can write our whole function in the place of second parameter in
addEventListener() method.

Example-

Prepared by: Amitabh Srivastava


EventListener: Example-3
▪ Change text using addEventListener()-

Prepared by: Amitabh Srivastava


EventListener: Exercise-1
Create a HTML file to display the current date when user clicks on the button? The
date should be displayed in the format March 3, 2024.
Solution-

Prepared by: Amitabh Srivastava


EventListener: Exercise-2
Create a HTML file to enter any number in a text filed and display its table in a <div>
element?
Solution-

Prepared by: Amitabh Srivastava


Collecting Form Data
▪ To collect the values of a Form, we need to fulfil below requirements-
✓ Assign some name to the Form using name attribute in <form> tag.
✓ Use the syntax formname.fieldname/field-id.value to get the field value.
Example-1:

Prepared by: Amitabh Srivastava


Collecting Form Data: Example-2

Prepared by: Amitabh Srivastava


Form Validation: HTML

Prepared by: Amitabh Srivastava


Form Validation: JavaScript

Prepared by: Amitabh Srivastava


ES6- startsWith() / endsWith()
▪ startsWith() method is used to check if a string begins with the characters of a specified string. It
returns true if a string begins with the characters of a specified string, otherwise returns false.
Syntax- String.startsWith(searchString [,position])
• searchString is the characters to be searched for at the start of this string.
• position is an optional parameter that determines the start position to search for
the searchString. It defaults to 0.

▪ endsWith() method is used to check if a string ends with the characters of another string. It
returns true if a string ends with the characters of a specified string, otherwise returns false. It is
also a case-sensitive method.
Syntax- String.endsWith(searchString [,length])
• searchString is the characters to be searched for at the end of the string.
• length is an optional parameter that determines the length of the string to search. It defaults
to the length of the string.
Prepared by: Amitabh Srivastava
Example: StartsWith() / endsWith()

Prepared by: Amitabh Srivastava


ES6- repeat()
▪ The string.repeat() is an in-built function in JavaScript ES6 which is used to
build a new string containing a specified number of copies of the string on which
this function has been called.

Syntax- string.repeat(count);
▪ count is an integer value which represents the number of times to repeat the
given string. The range of the integer count is from zero (0) to infinite times.

Example-

Prepared by: Amitabh Srivastava


ES6- for...of Loop
▪ For… of loop introduced in ES6 to iterate the built-in objects.
▪ In each iteration, a property of the iterable object is assigned to the variable.

Example-

Prepared by: Amitabh Srivastava


ES6- Accessing Index
▪ To access the index of the array elements inside the loop, we can use the for…of
statement with the entries() method of an array.
▪ The entries() method returns a pair of [index, element] in each iteration.

Example-

Prepared by: Amitabh Srivastava


Anonymous Function
▪ An anonymous function is a function that does not have any name.

▪ These functions are often defined inline and can be assigned to a variable or
passed as an argument to another function.

▪ Example-

Prepared by: Amitabh Srivastava


Callback Function
▪ We can pass a function as an argument to another function.
▪ This function that is passed as an argument inside of another function is called a
callback function.
▪ Example-

Prepared by: Amitabh Srivastava


ES6- Arrow Function
A normal function in JavaScript- Can be written as-

An arrow function-
Syntax- function_variable = (arguments) => {
statements;
return value; }

Prepared by: Amitabh Srivastava


Arrow Function to Sort an Array
Sort an array using normal way-

Sort an array using arrow function-

Prepared by: Amitabh Srivastava


Arrow Function to Check Length
Using normal function-

Using Arrow function-

Prepared by: Amitabh Srivastava


Arrow Function to Calculate Average

Prepared by: Amitabh Srivastava


Arrow Function: Exercise
Write an arrow function to display the table of an entered number?

Solution-

Prepared by: Amitabh Srivastava


Example Code-1: Image Swap

Prepared by: Amitabh Srivastava


Example Code-2: Hide/Show Data

Prepared by: Amitabh Srivastava


Example Code-3: Toggle Dark Mode

Prepared by: Amitabh Srivastava


Example Code-4: Countdown Timer

Prepared by: Amitabh Srivastava


Example Code-5: Running Clock

Prepared by: Amitabh Srivastava


Exercise
Create a HTML file to display running clock with toggle button to start & stop
the clock?
Solution-

Prepared by: Amitabh Srivastava


Node JS
▪ Node.js is an open-source server side runtime environment built on Chrome's
V8 JavaScript engine.

▪ It comes under MIT License- free s/w license originated at Massachusetts


Institute of Technology.

▪ It provides an event driven, asynchronous(non-blocking) I/O and cross-platform


runtime environment for building highly scalable server-side application using
JavaScript.

▪ It uses JavaScript to build entire server-side application.

▪ Node.js can be used to build different types of applications such as command


line application, web application, real-time
Prepared chat application, etc.
by: Amitabh Srivastava
Installing Node.js
▪ Go to the official website https://nodejs.org/ and download the current version of node.js.
▪ After downloading, just double click on the file and it will start the installation of Node.js on
your machine.
▪ Once installed, you can check it with the following command-

▪ It will also install ‘npm’ and ‘npx’ utility commands. To check whether ‘npm’ (Node Package
Manager) is installed correctly, just give-

▪ And, to check whether ‘npx’ is installed correctly, just give-

Prepared by: Amitabh Srivastava


Node.js Console/REPL
▪ Node.js comes with virtual environment called REPL (Node shell).

▪ REPL stands for Read-Eval-Print-Loop. It provides a quick and easy way to test
simple Node.js/JavaScript code.

▪ To launch the REPL (Node shell), open command window/terminal and


type ’node’.

▪ It will change the prompt to > in the command window/terminal.

Prepared by: Amitabh Srivastava


Using Node.js Console/REPL
▪ You can now test pretty much any Node.js/JavaScript expression in
REPL. 10 + 20 will display 30 immediately in new line.

▪ The + operator also concatenates strings as in browser's JavaScript.

▪ You can also define variables and perform some operation on them.

Prepared by: Amitabh Srivastava


Multi-line Expression in REPL
▪ If you need to write multi-line JavaScript expression or function then just
press Enter whenever you want to write something in the next line as a
continuation (continuity mode) of your code.

▪ The REPL terminal will display three dots (...), it means you can continue
on next line. Write .break to get out of continuity mode.

Prepared by: Amitabh Srivastava


Executing File in Node.js
▪ You can execute an external JavaScript file by executing the node
filename command. For example, the following executes the file
node1.js on the command prompt/terminal and displays the result.

▪ To Execute this node1.js file, go


to the directory where you saved
the file and give the following
command-

Prepared by: Amitabh Srivastava

You might also like