0% found this document useful (0 votes)
20 views176 pages

Javascript Full Course

JavaScript is a versatile programming language primarily used for web development, enabling both client-side and server-side scripting. It supports various programming paradigms and has a rich ecosystem of frameworks and libraries for building applications. Key features include dynamic behavior, event handling, API integration, and a variety of data types and operators.

Uploaded by

ragulr1109
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)
20 views176 pages

Javascript Full Course

JavaScript is a versatile programming language primarily used for web development, enabling both client-side and server-side scripting. It supports various programming paradigms and has a rich ecosystem of frameworks and libraries for building applications. Key features include dynamic behavior, event handling, API integration, and a variety of data types and operators.

Uploaded by

ragulr1109
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/ 176

JavaScript

JavaScript

JavaScript is a versatile and widely-used


programming language primarily known for its
role in web development. Initially created to
make web pages interactive, JavaScript has
evolved into a powerful language that can be
used for both front-end and back-end
development.
JavaScript was invented by Brendan Eich
in 1995 to add dynamic behavior to static
web pages. It's now used for a variety of
purposes, including building web and
mobile applications, server-side
development, game development, and
more.
Client-Side Scripting: One of JavaScript's
primary functions is to enable client-side
scripting, meaning it runs in the user's
web browser. This allows for dynamic
updates, interactive content, form
validation, and more without needing to
reload the entire page.
Versatility: JavaScript is a versatile
language that supports multiple
programming's, including procedural,
functional, and object-oriented
programming. Its flexibility makes it
suitable for a wide range of tasks and
environments.
Syntax: JavaScript syntax is similar to
other programming languages like Java
and C, making it relatively easy to learn for
those familiar with programming
concepts. It uses curly braces { },
semicolons ; and variable declarations
(var, let, const).
Frameworks and Libraries: JavaScript has
a rich ecosystem of frameworks and
libraries like [Link], Angular, and [Link]
for building complex web applications
efficiently. These tools provide pre-built
components, routing, state management,
and more.
Server-Side Development: With the
introduction of [Link], JavaScript can
now be used for server-side development
as well. [Link] allows developers to build
scalable and high-performance server
applications using JavaScript.
Event Handling: JavaScript enables
interactivity on web pages by responding
to user actions such as clicks, mouse
movements, keyboard inputs, etc. Event
handling allows developers to execute
specific code when certain events occur.
API Integration: JavaScript can interact
with external APIs (Application
Programming Interfaces) to fetch data
from servers, send data, and perform
other operations. This capability enables
developers to create dynamic and data-
driven applications.
Comments

• Single Line Comments


• //
• Multi-line Comments
• Any text between /* and */ will be ignored by JavaScript.
Variables

Variables are containers for storing data


values. You can declare variables using
var, let, or const keywords.

var age = 25;


let name = "John";
const PI = 3.14;
• var: var was the only way to declare variables in
JavaScript before ES6. It has function scope and can be
reassigned.
• let: Introduced in ES6, let is block-scoped and can be
reassigned. Using let can help prevent bugs caused by
variable hoisting and unintended variable modifications.
• const: const is also introduced in ES6 and is used to
declare constants, whose value cannot be reassigned.
properties of a const object can be changed.
Data Types: JavaScript supports various data types including
numbers, strings, booleans, arrays, objects, null, and undefined.
let num = 10; // Number
let text = "Hello"; // String
let a = true; // Boolean
let arr = [1, 2, 3]; // Array
let obj = { key: "value" }; // Object
let n = null; // Null
let u; // Undefined
Operators: JavaScript includes arithmetic,
assignment, comparison, logical, and other
operators for performing operations on values.
let a = 5;
let b = 3;
let sum = a + b; // Addition
let difference = a - b; // Subtraction
let product = a * b; // Multiplication
let quotient = a / b; // Division
let remainder = a % b; // Modulus (Remainder)
• These operators compare two values and return a Comparison
operators: Boolean value indicating whether the comparison is true or
false.

• let a = 10;
• let b = 5;

• [Link](a > b); // Greater than


• [Link](a < b); // Less than
• [Link](a >= b); // Greater than or equal to
• [Link](a <= b); // Less than or equal to
• [Link](a === b); // Equal to
• [Link](a !== b); // Not equal to
• Logical operators: These operators are used to combine multiple
expressions and evaluate them to a single Boolean value.

• && // Logical AND


• || // Logical OR
• ! // Logical NOT
• Assignment operators: These operators assign a value to a
variable.

• let e = 10;
• e += 5; // Equivalent to e = e + 5;
• e -= 3; // Equivalent to e = e - 3;
• e *= 2; // Equivalent to e = e * 2;
• e /= 4; // Equivalent to e = e / 4;
Strings

• Strings are written with quotes.

• let carName1 = "Volvo XC60"; // Double quotes


let carName2 = 'Volvo XC60'; // Single quotes
Quotes
• <p id=“demo” > </p>
• <script>
• let answer1 = "It's alright";
• let answer2 = "He is called 'Johnny‘ ";
• let answer3 = 'He is called “Johnny” ';

• [Link]("demo").innerHTML =
• answer1 + "<br>" + answer2 + "<br>" + answer3;
• </script>
Template String

• <p id=“demo”> </p>


• <script>
• let text = ` He's often called "Johnny“ `;
• [Link]("demo").innerHTML = text;
• </script>
Escape sequence to insert quotes

• <p id="demo"></p>

• <script>
• let text = "We are the so-called \"Vikings\" from the north.";
• [Link]("demo").innerHTML = text;
• </script>
• <script>
• let text = 'It\'s alright.';
• [Link]("demo").innerHTML = text;
• </script>
Escape sequence to insert \

<p id="demo"></p>

<script>
let text = "The character \\ is called backslash.";
[Link]("demo").innerHTML = text;
</script>
Functions
• A JavaScript function is defined with the function keyword,
followed by a name, followed by parentheses ( ).
• Function names can contain letters, digits, underscores, and
dollar signs.
• The parentheses may include parameter names separated by
commas:
(parameter1, parameter2, ...)
• function name(parameter1, parameter2, parameter3) {
// code to be executed
}
• With functions you can reuse code
You can use the same code with different arguments,
to produce different results.
Function Invocation

• The code inside the function will execute when


"something" invokes (calls) the function:
• When an event occurs (when a user clicks a button)
Function Return

• When JavaScript reaches a return statement, the function will stop executing.

<p id="demo"></p>

<script>
[Link]("demo").innerHTML = myFunction(1, 2);

function myFunction(a, b) {
return a * b;
}
</script>
Object
Objects are variables too. But objects can contain many values.
The values are written as name:value pairs (name and value
separated by a colon).
This code assigns many values (apple, red, big) to a variable named
fruits:
<script>
const fruits = {name:”apple", color:“red", size:“big"};
</script>
Object

<p id="demo"></p>

<script>
const person = {
firstName : “Adolf ",
lastName : “Hitler",
age : 50,
eyeColor : "blue"
};

[Link]("demo").innerHTML =
[Link] + " is " + [Link] + " years old.";
</script>
Accessing Object Properties

• You can access object properties in two


ways:

• [Link]

• objectName["propertyName"]
objectName["propertyName"]
<p id="demo"></p>
<script>
const person = {
firstName: “Adolf",
lastName : “Hitler",
id : 5566
};
[Link]("demo").innerHTML =
person["firstName"] + " " + person["lastName"];
</script>
[Link]

<p id="demo"></p>

<script>
const person = {
firstName: “Adolf ",
lastName : “Hitler",
id : 5566
};

[Link]("demo").innerHTML = [Link] + " " +


[Link];
</script>
this Keyword
• In a function definition, this refers to the "owner" of the function. In other words,
[Link] means the firstName property of this object.

<p id="demo"></p>
<script>
const person = {
firstName: “Adolf ",
lastName: “Hitler",
id: 5566,
fullName: function() {
return [Link] + " " + [Link];
}
};
[Link]("demo").innerHTML = [Link]();
</script>
Array [ ]

• Collection of data.
• Arrays are variables that holds multiple values
• There are three category:
• Single dimensional array
• Two dimensional array
• Multi dimensional
Single dimensional array

Array with one row and multiple columns are called single
dimensional array.

n=[1,2,3,4,5,6]
[Link](n)
[Link](n[4])
Multi -dimensional array

Array with multiple rows and multiple columns


are called two dimensional array or bi-
dimensional array.

colours=[[green, red, orange],[black,


yellow, green], [indigo, white]]
Array methods

Array methods in programming languages are built-in


functions that you can use to perform different operations on
arrays, such as adding elements, removing elements,
filtering elements, sorting elements, and more.

Some common array methods include push(), pop(), shift(),


unshift(), splice(),slice(), concat()
Push method - adding elements to the end of an
array

let arr = [1, 2, 3];


[Link](4);
[Link](arr);

Output: [1, 2, 3, 4]
Pop method - removing the last element of an array
let arr = [1, 2, 3];
[Link]();
[Link](arr);

Output: [1, 2]
Shift method - removing the first element of an
array
let arr = [1, 2, 3];
[Link]();
[Link](arr);

Output: [2, 3]
unShift method – adding first element of an array
let arr = [1, 2, 3];
[Link](4);
[Link](arr);

Output: [4,1,2, 3]
Slice method - creating a new array by extracting a section of an
existing array

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


let newArr = [Link](1);
[Link](newArr); // Output: [2, 3,4,5]
• let myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
• let newArray = [Link](1, 5);
• [Link](newArray);

• // Output: [2, 3, 4, 5]
Splice method – removing or replacing existing element of
array

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


let newArr = [Link](2,1,”a”,”b”);
[Link](arr); // Output: [1, 2, ”a”, ”b”, 4, 5]
Concat method - merging two or more arrays
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let newArr = [Link](arr2);
[Link](newArr); // Output: [1, 2, 3, 4, 5, 6]
Join

const fruits = ["apple", "banana", "orange"];


const joinedFruits = [Link](", ");
[Link](joinedFruits);

// Output: apple, banana, orange


Split

const str = "apple, banana, orange";


const splittedFruits = [Link](“, ");
[Link](splittedFruits);

// Output: ["apple", "banana", "orange"]


Filter method - creating a new array with all elements that pass a
certain condition
let arr = [1, 2, 3, 4, 5];
let newArr = [Link](function(element) {
return element % 2 === 0;
});
[Link](newArr); // Output: 2, 4

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


let newArr = [Link](element => element % 2 === 0);
[Link](newArr);
Reduce method - applying a function to each element of the
array to reduce it to a single value
let arr = [1, 2, 3, 4, 5];
let sum = [Link](function(total, element) {
return total+ element;
});
[Link](sum); // Output: 15
Search:
IndexOf method - finding the index of a specific element in an
array
let arr = [1, 2, 3, 4, 5];
let index = [Link](3);
[Link](index); // Output: 2
Find method - finding the first element in an array that satisfies
a condition
let arr = [1, 2, 3, 4, 5];
let element = [Link](function(element) {
return element > 3;
});
[Link](element); // Output: 4
Includes method - checking if an array includes a certain
element
let arr = [1, 2, 3, 4, 5];
let includes = [Link](3);
[Link](includes); // Output: true
some

• let numbers = [1, 5, 12, 8, 3];


• let hasNumberGreaterThan10 = [Link]((num) =>
num > 10);
• [Link](hasNumberGreaterThan10); // Output: true
Sort:
Sort:
Sort method - sorting an array in ascending order
let arr = [3, 1, 5, 2, 4];
[Link]();
[Link](arr); // Output: [1, 2, 3, 4, 5]
Reverse method - reversing the elements of an
array
let arr = [1, 2, 3, 4, 5];
[Link]();
[Link](arr); // Output: [5, 4, 3, 2, 1]
String Method
String Length

• To find the length of a string, use the built-in length property:

• <p id="demo"></p>

• <script>
• let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
• [Link]("demo").innerHTML = [Link];
• </script>
String trim

• let str = " Hello, World! ";


• let trimmedStr = [Link]();
• [Link]("Trimmed string:", trimmedStr);
• trimmedStr = “HeLlO wOrLd”
• let upperCase = [Link]();
• [Link]("Uppercase string:", upperCase);

• // Convert the string to lowercase


trimmedStr = “HeLlO wOrLd”
• let lowerCase = [Link]();
• [Link]("Lowercase string:", lowerCase);
INDEX OF

• // Get the index of the first occurrence of a


character
• trimmedStr = “HeLlo wOrLd”
• let index = [Link]("o");
• [Link]("Index of 'o':", index);
• let trimmedStr = “Hello World”
• let replacedStr = [Link]("World", "Universe");
• [Link]("Replaced string:", replacedStr);

• // Split the string into an array of substrings


• let splitArray = [Link]("");
• [Link]("Split array:", splitArray);
at()

<p id="demo"></p>

<script>
const name = “JavaScript";
let letter = [Link](8);
[Link]("demo").innerHTML =
letter;
</script>
charAt()

<p id="demo"></p>

<script>
var text = "HELLO WORLD";
[Link]("demo").innerHTML =
[Link](0);
</script>
charCodeAt()

<p id="demo"></p>

<script>
let text = "HELLO WORLD";
[Link]("demo").innerHTML =
[Link](4);
</script>
//output 79
substring()

substring(startIndex, endIndex)
const str = "Hello, World!";
[Link]([Link](7, 12));
// Output: World
Search()

• var str = "Hello, World!";


• var pos = [Link]("World");

• [Link](pos); // Output: 7
Number method
toString

Converts any datatype to a string.


<p id="demo"></p>

<script>
let x = 123;
[Link]("demo").innerHTML = [Link]();
</script>
• rounded to a specified number of digits.
• <p id="demo"></p>

• <script>
• let x = 9.6568;
• [Link]("demo").innerHTML =[Link]() +
"<br>" + [Link](2) + "<br>" + [Link](4) + "<br>" +
• [Link](6);
• </script>
• Formats a number using fixed-point notation with a specified number
of decimal places.
• <p id="demo"></p>
• <script>
• let x = 9.656;
• [Link]("demo").innerHTML =
• [Link](0) + "<br>" + [Link](2) + "<br>" + [Link](4) + "<br>"
+[Link](6);
• </script>
• toExponential(): Formats a number using exponential notation.
• // toExponential()
• let num = 1234.56789;
• let numExponential = [Link]();
• [Link](numExponential);

• // Output: "1.23456789e+3“
• "1.23456789e+3" can be read as 1.23456789 x 10^3,
• which is essentially 1234.56789.
[Link](): This method rounds a number to the
nearest integer.
let num = 7.8;
let roundedNum = [Link](num);
[Link](roundedNum);

// Output: 8
• [Link](): This method rounds a number down to
the nearest integer.

• let num = 7.8;


• let flooredNum = [Link](num);
• [Link](flooredNum);

• // Output: 7
• [Link](): This method rounds a number up to the nearest
integer.

• let num = 7.2;


• let ceiledNum = [Link](num);
• [Link](ceiledNum);

• // Output: 8
• [Link](): This method generates a random number
between 0 (inclusive) and 1 (exclusive).

• let randomNum = [Link]();


• [Link](randomNum);
• let numbers = [5, 10, 15, 20, 25];

• let minValue = [Link](...numbers);


• let maxValue = [Link](...numbers);

• [Link](`The minimum value is: ${minValue}`);


• [Link](`The maximum value is: ${maxValue}`);
• //output
• The minimum value is: 5
• The maximum value is: 25
• [Link](): This method returns the base to the exponent
power, that is, base^exponent.

• let base = 2;
• let exponent = 3;
• let result = [Link](base, exponent);
• [Link](result);
• // Output: 8
Ternary operator

• The ternary operator is a shorthand for an if-else statement in


JavaScript. It is a single line expression.

• condition ? expression1 : expression2


• condition is the value that is being
evaluated, expression1 is the value returned if the
condition is true, and expression2 is the value returned if
the condition is false
• // Ternary operator example
• let age = 20;
• let status = (age >= 18) ? "Adult" : "Minor";

• // Output the result


• [Link]("The person is an " + status);
• let temperature = 25;
• let isSummer = true;

• let message = (isSummer && temperature > 30) ? "It's a hot


summer day!" : "It's not a hot summer day.";
• [Link](message);

• // Output: It's not a hot summer day!


Conditional statement

• To perform different actions for different decisions.


• Simple if – ”if”
• Common if – “if - else”
• “else – if”
• Nested if
Simple if – ”if”

Syntax :
if (condition) {

// block of code to be executed if the condition is true

}
Examples

• var a=10
• if (a==10){
• [Link]("true")
• }
• let num = 10;

if (num > 5){
• [Link]("The number is greater than 5");
• }
If – else

• var apple=false;
• if (apple){
• [Link]("apple")
• }
• else{
• [Link]("not apple")
• }
Temperature

const temperature = prompt("Enter the temperature :");

if (temperature > 100)


{
[Link]("It's hot outside!");
}
else
{
[Link]("It's not hot outside!");
}
Even or Odd

const number = prompt("Enter a number:");


if (number % 2 === 0)
{
[Link]("The number is even.");
}
else {
[Link]("The number is odd.");
}
program changes the text color of a paragraph

• const para = [Link]("myPara");

• if ([Link] === "red") {


• [Link] = "blue";
• } else {
• [Link] = "red";
•}
program toggles the visibility of an image

• const img = [Link]("myImg");

• if ([Link] === "none") {


• [Link] = "block";
• } else {
• [Link] = "none";
•}
program changes the background color of a div

• const div = [Link]("myDiv");

• if ([Link] === "green") {


• [Link] = "red";
• } else {
• [Link] = "green";
•}
program changes the text of a button

• const btn = [Link]("myBtn");

• if ([Link] === "Click Me") {


• [Link] = "Button Clicked";
• } else {
• [Link] = "Click Me";
•}
Else –if
• const grade = prompt("Enter your grade:");
• if (grade === "A") {
• [Link]("Excellent!");
• }
• else if (grade === "B") {
• [Link]("Good!");
• }
• else if (grade === "C") {
• [Link]("Average!");
• }
• else if (grade === "D") {
• [Link]("Poor!");
• }
• else if (grade === "F") {
• [Link]("Failed!");
• }
• else { [Link]("Invalid grade."); }
Displaying a message based on a number
• let number = 10;
• if (number > 10) {
• [Link]("The number is greater than 10.“);
•}
• else if (number < 10) {
• [Link]("The number is less than 10.“);
• } else {
• [Link]("The number is equal to 10.");
• }
Changing the background color based on a time

• let currentTime = new Date().getHours();


• if (currentTime >= 6 && currentTime < 12)
{ [Link] = "yellow";
•}
• else if (currentTime >= 12 && currentTime < 18)
{ [Link] = "blue";
•}
• else {
• [Link] = "gray";
• }
new Date()
is a constructor function in JavaScript that creates
a
new Date object,

const date = new Date();


[Link](date);
getDate()

• Returns the day of the month (from 1 to 31) for the


specified date according to local time.

• const date = new Date();


• [Link]([Link]());

• // Output: Current day of the month


getDay():

• Returns the day of the week (from 0 to 6) for the


specified date according to local time.

• const date = new Date();


• [Link]([Link]());

• // Output: Current day of the week


getFullYear():

• Returns the year of the specified date according to


local time.

• const date = new Date();


• [Link]([Link]());

• // Output: Current year


getHours():

• Returns the hour (from 0 to 23) in the specified


date according to local time.

• const date = new Date();


• [Link]([Link]());

• // Output: Current hour


getMinutes():

• Returns the minutes (from 0 to 59) in the specified


date according to local time.

• const date = new Date();


• [Link]([Link]());

• // Output: Current minutes


getMonth():

• Returns the month (from 0 to 11) in the


specified date according to local time.

• const date = new Date();


• [Link]([Link]());

• // Output: Current month


getSeconds()

• Returns the seconds (from 0 to 59) in the


specified date according to local time.

• const date = new Date();


• [Link]([Link]());

• // Output: Current seconds


getTime():

• Returns the number of milliseconds since midnight


Jan 1, 1970, and a specified date.

• const date = new Date();


• [Link]([Link]());

• // Output: Number of milliseconds since Jan 1, 1970


Nested-if
• Nested if statements in JavaScript are used when you need to check
multiple conditions within another conditional block.
• if (outerCondition) {
• if (innerCondition) {
• // code to execute if both outer and inner conditions are true
• } else {
• // code to execute if outer condition is true and inner condition is false
• }
• } else {
• // code to execute if outer condition is false
•}
• let num1 = 10;
• let num2 = 20;

• if (num1 > 5) {
• if (num2 < 15) {
• [Link]("Both conditions are met.");
• } else {
• [Link]("First condition is met, but not the second.");
• }
• } else {
• [Link]("First condition is not met.");
•}
• let temperature = 25;
• let isSummer = true;

• if (isSummer) {
• if (temperature > 30) {
• [Link]("It's a hot summer day!");
• } else {
• [Link]("It's summer but not too hot.");
• }
• } else {
• [Link]("It's not summer.");
•}
• In JavaScript, the increment (++) and decrement (--) operators are
used to modify the value of a variable by 1.
• Types of Increment/Decrement Operators:
• Prefix Increment/Decrement (++x/--x): This type of operator
increments or decrements the variable before returning its value.
For example, ++x increments x and returns the new value.
• let x = 5;
• [Link](++x); // Output: 6
• [Link](x); // Output: 6
• Postfix Increment/Decrement (x++/x--): This type of
operator increments or decrements the variable after
returning its value. For example, x++ returns the current
value of x and then increments it.
• let x = 5;
• [Link](x++); // Output: 5
• [Link](x); // Output: 6
For loop

• The for loop in JavaScript is a control flow statement that


allows you to execute a block of code repeatedly based on
a specified condition.
• for (initialExpression; condition; updateExpression)
•{
• // block of code to be executed
•}
• for (let i = 1; i <= 5; i++) {
• [Link](i);
•}
Iteration:

For loop - iterating over an array using a for loop

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


for (let i = 0; i < [Link]; i++) {
[Link](arr[i]);
}
Sum of series 1 to 10

• let sum = 0;
• for (let i = 1; i <= 10; i++) {
• sum += i;
•}
• [Link](sum);
Odd numbers

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


• if (i % 2 !== 0) {
• [Link](i);
• }
•}
Find the largest number in an array

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


• let max = numbers[0];
• for (let i = 1; i < [Link]; i++) {
• if (numbers[i] > max) {
• max = numbers[i];
• }
•}
• [Link](max);
Counting the number of vowels in a string

• let str = "hello world";


• let vowels = 0;
• for (let i = 0; i < [Link]; i++) {
• if (str[i] === "a" || str[i] === "e" || str[i] === "i" || str[i] === "o"
|| str[i] === "u") {
• vowels++;
• }
•}
• [Link](vowels);
ForEach method - iterating over an array
using forEach method
let arr = [1, 2, 3, 4, 5];
[Link](function(element) {
[Link](element);
});
Map method - creating a new array by mapping each element of
an existing array
let arr = [1, 2, 3, 4, 5];
let newArr = [Link](function(element) {
return element * 2;
});
[Link](newArr); // Output: [2, 4, 6, 8, 10]
While loop

• A while loop in JavaScript is a type of loop that


allows you to execute a block of code as long as a
specified condition is true. The loop will continue to
execute the code block until the condition becomes
false.
Syntax

•while (condition) {
• // code block to be executed
•}
Counting from 1 to 5

• let count = 1;
• while (count <= 5) {
• [Link](count);
• count++;
•}
• Output: 1, 2, 3, 4, 5
Infinite loop

•let i = 0;
•while (true) {
• [Link](i);
• i++;
•}
Empty file name warning

• let fileName = ‘';


• while (fileName === ‘') {
• fileName = prompt('Please enter a filename: ');
•}
• [Link]('Thank you.');
simple game

• let score = 0;
• while (score < 100) {
• [Link]('Score: ' + score);
• score++;
• if (score % 10 === 0) {
• [Link]('You got a bonus!');
• }
•}
• let password = 'correctpassword';
• let attempts = 0;

• while (attempts < 3) {


• let inputPassword = prompt('Enter your password: ');
• if (inputPassword === password) {
• alert('Access granted!');
• break;
• } else {
• attempts++;
• alert('Incorrect password. Try again.');
• }
• }
• if (attempts === 3) {
• alert('Access denied. Too many incorrect attempts.');
• }
Do …. while

• "do-while" loop is similar to a "while" loop, but it


guarantees that the loop's body is executed at least once
before the condition is checked.

• do {
• // code block to be executed
• } while (condition);
• var i = 0;
• do {
• [Link]("Value of i: " + i);
• i++;
• } while (i < 5);
• let num;
• do {
• num = parseInt(prompt("Enter a number:"));
• } while (isNaN(num));
• [Link]("You entered: " + num);
Break, continue , pass

• Break Statement:
• The break statement is used to terminate a loop or a switch
statement. It "breaks" out of the loop or switch and
continues executing the code after the loop or switch.
Breaking out of a for loop:

• for (let i = 0; i < 10; i++) {


• if (i === 5) {
• break;
• }
• [Link](i);
•}

• #Output: 0, 1, 2, 3, 4
Breaking out of a while loop:

• let i = 0;
• while (i < 10) {
• if (i === 5) {
• break;
• }
• [Link](i);
• i++;
• }

• Output: 0, 1, 2, 3, 4
Continue Statement:

• The continue statement is used to skip the current iteration


of a loop and move on to the next iteration
Skipping an iteration in a for loop:

• for (let i = 0; i < 10; i++) {


• if (i === 5) {
• continue;
• }
• [Link](i);
•}
• Output: 0, 1, 2, 3, 4, 6, 7, 8, 9
Skipping an iteration in a while loop:

• let i = 0;
• while (i < 10) {
• if (i === 5) {
• i++;
• continue;
• }
• [Link](i);
• i++;
•}
• Output: 0, 1, 2, 3, 4, 6, 7, 8, 9
Skipping an iteration with a conditional statement:

• for (let i = 0; i < 10; i++) {


• if (i % 2 === 0) {
• continue;
• }
• [Link](i);
•}

• Output: 1, 3, 5, 7, 9
Pass

• for (let i = 0; i < 10; i++) {


• if (i === 5) {
• // pass
• } else {
• [Link](i);
• }
•}
• Output: 0, 1, 2, 3, 4, 6, 7, 8, 9
Switch case

• The switch statement is used to execute different blocks of


code based on the value of a given expression.
• The expression is evaluated, and the code block associated
with the first matching case is executed.
• If no case matches the expression, the default block is
executed.
• The break statement is used to exit the switch statement
and prevent further execution of code blocks.
• let day = "Monday";
• switch (day) {
• case "Monday":
• [Link]("Today is Monday");
• break;
• case "Tuesday":
• [Link]("Today is Tuesday");
• break;
• default:
• [Link]("Today is neither Monday nor Tuesday");
•}
getElementById ……onclick

• <h1 id=“heading”> welcome to my class </h1>


• <button onclick=“change()” > click me </button>
• <script>
• var h1= [Link](“heading)

• function change(){
• [Link]=“Get out”
•}
• </script>
• <div id="myDiv">Hello World!</div>

• <script>
• const myElement =
[Link]("myDiv");
• [Link](myElement); // <div id="myDiv">Hello
World!</div>
• </script>
getElementsByClassName

• <div class="myClass">Hello World!</div>


• <div class="myClass">Hello Again!</div>

• <script>
• const myElements =
[Link]("myClass");
• [Link](myElements); // HTMLCollection of 2 elements
• </script>
getElementsByTagName

• <p>Hello World!</p>
• <p>Hello Again!</p>

• <script>
• const myElements =
[Link]("p");
• [Link](myElements); // HTMLCollection of 2 elements
• </script>
querySelector

• <div id="myDiv" class="myClass">Hello World!</div>

• <script>
• const myElement = [Link]("#myDiv");
• [Link](myElement);
• </script>
createElement

• <script>
• const myDiv = [Link]("div");
• [Link] = "myDiv";
• [Link] = "myClass";
• [Link](myDiv);
• </script>
Creating Attributes

• <script>
• const myDiv = [Link]("div");
• [Link]("id", "myDiv");
• [Link]("class", "myClass");
• [Link](myDiv);
• </script>
querySelectorAll

• <div class="myClass">Hello World!</div>


• <div class="myClass">Hello Again!</div>

• <script>
• const myElements =
[Link](".myClass");
• [Link](myElements);
• </script>
Set Time Out

• The setTimeout method in JavaScript is used to set a timer


that executes a specified function or piece of code after a
specified amount of time has elapsed. It allows you to delay
the execution of a function, making it useful for scenarios
like animations, delays, or timed events.
• setTimeout(callbackFunction, delayInMilliseconds);

delayInMilliseconds: The time delay in milliseconds before
the callbackFunction is executed.
Set Time Out

• function greet() {
• [Link]('Welcome!');
•}

• [Link]('setTimeout example...');
• setTimeout(greet, 2000);

• // Execute greet after 2000 milliseconds (2 seconds)


Displaying a Message After a Delay:

• setTimeout(() => {
• alert("Time's up!"); },
• 3000);
Changing CSS After a Delay:

• const element =
[Link]("myElement");
• setTimeout(() => {
• [Link] = "blue";
• }, 4000);
What is Event Handling?

Event handling in JavaScript is the process of


detecting and responding to user interactions
or system events on a web page. It allows
developers to create dynamic and interactive
user interfaces that respond to user input in
real-time. In JavaScript, events are represented
as objects, and event handling is implemented
through event listeners
Types of Events

• There are various types of events that can be


handled in the DOM (Document Object
Model), including:
• Mouse Events: triggered by mouse interactions,
such as clicking, hovering, or scrolling.
• Keyboard Events: triggered by keyboard
interactions, such as key presses or releases.
• Form Events: triggered by interactions with HTML
form elements, such as submitting a form.
• Window Events: triggered by interactions with the
browser window, such as resizing or closing.
Events (onclick)

• <button onclick="handleClick()">Click me</button>


• <script>
• function handleClick() {
• alert('Button clicked!');
• }
• </script>
What is an Event Listener?:

• An event listener is like an attentive listener that


waits for a specific event to occur on a webpage.
• When the event happens, the event listener "hears"
it and triggers a function or action to respond to
that event.
How Event Listeners Work:

• Event listeners are added to HTML elements, such


as buttons, input fields, or the entire webpage.
• They "listen" for specific events, like clicks, mouse
movements, or key presses, and respond
accordingly
• you can add event listeners using the
addEventListener() method.
• <button id="myButton">Click me</button>
• <script>
• [Link]("myButton").onclick =
function() {
• alert("Button clicked!");
• };
• </script>
Change

<input type="text" id="myInput" onchange="handleChange()">

function handleChange() {
• alert('Input value changed to: ' +
[Link]('myInput').value);
• }

[Link]('myInput').addEventListener('change',
handleChange);
Mouseover

<div onmouseover="handleMouseover()"
id="demo">Hover over me</div>
<script>
function handleMouseover() {
[Link]('demo').innerHTML =
'Mouse over me!';
}
</script>
Keydown

<input type="text" onkeydown="handleKeydown(event)">

<script>
function handleKeydown(event) {
alert('Key pressed: ' + [Link]);
}
</script>
Submit event

<form id="myForm">
<input type="text" name="name" placeholder="Enter your name">
<input type="submit" value="Submit">
</form>
<script>
[Link]('myForm').addEventListener('submit',
function(event) {
[Link]();
alert('Form submitted!');
});
</script>
Type cast

Changes one data type to another data type


String to number:
a=‘10’;
b= Number(a);
[Link](b);
Types of for loop

• For Loop with Initialization Outside:


• let i = 0;
• for (; i < 5; i++) {
• [Link]("The number is " + i);
•}
For Loop with Condition Only:

• let i = 0;
• for (; i < 5;) {
• [Link]("The number is " + i);
• i++;
•}
For Loop with Increment by 2:

• for (let i = 0; i < 10; i += 2) {


• [Link]("The number is " + i);
•}
• The number is 0
• The number is 2
• The number is 4
• The number is 6
• The number is 8
Nested For Loops:
• for (let i = 0; i < 3; i++) {
• [Link]("Outer Loop: " + i);
• for (let j = 0; j < 2; j++) {
• [Link](" Inner Loop: " + j);
• }
• }
• Outer Loop: 0
• Inner Loop: 0
• Inner Loop: 1
• Outer Loop: 1
• Inner Loop: 0
• Inner Loop: 1
• Outer Loop: 2
• Inner Loop: 0
• Inner Loop: 1
For...In Loop:

• The for...in loop in JavaScript is used to iterate over the


properties of an object.
• const person = { name: 'John', age: 30, city: 'New York' };

• for (let property in person) {


• [Link](property + ': ' + person[property]);
•}
• name: John
• age: 30
• city: New York
For...Of Loop:

The for...of loop in JavaScript is used to iterate over


the values of an iterable object like an array.

const fruits = ['apple', 'banana', 'cherry'];

for (let fruit of fruits) {


[Link](fruit);
}
• apple
• banana
• cherry
Class:

• A class in JavaScript is a blueprint or a


template that defines the properties and
methods of an object.

• Object
• An object in JavaScript is an instance of a
class, which is created using the class
blueprint.
• class ClassName {
• constructor(parameters) {
• // Initialize properties
• }

• method1() {
• // Method implementation
• }

• method2() {
• // Method implementation
• }
•}
• const objectName = new ClassName(parameters);
• class Car {
• constructor(brand, model, year) {
• [Link] = brand;
• [Link] = model;
• [Link] = year;
• }
• start() {
• [Link](`${[Link]} ${[Link]} started.`);
• }
• stop() {
• [Link](`${[Link]} ${[Link]} stopped.`);
• }
• }

• const myCar = new Car("Toyota", "Corolla", 2020);


• [Link](); // Output: Toyota Corolla started.
• [Link](); // Output: Toyota Corolla stopped.
• class Person {
• constructor(name, age) {
• [Link] = name;
• [Link] = age;
• }
• greet() {
• [Link](`Hello, my name is ${[Link]} and I am $
{[Link]} years old.`);
• }
•}
• class Student extends Person {
• constructor(name, age, major) {
• super(name, age);
• [Link] = major;
• }

• greet() {
• [Link]();
• [Link](`I am a student of ${[Link]}.`);
• }
•}
• let student = new Student("John", 20, "Computer Science");
• [Link]();

You might also like