[go: up one dir, main page]

0% found this document useful (0 votes)
15 views81 pages

Javascript

The document provides an overview of JavaScript, including its syntax, data types, variables, and functions. It covers essential programming concepts such as control statements, loops, error handling, and the Document Object Model (DOM). Additionally, it discusses advanced topics like promises, async/await, and object-oriented programming in JavaScript.

Uploaded by

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

Javascript

The document provides an overview of JavaScript, including its syntax, data types, variables, and functions. It covers essential programming concepts such as control statements, loops, error handling, and the Document Object Model (DOM). Additionally, it discusses advanced topics like promises, async/await, and object-oriented programming in JavaScript.

Uploaded by

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

E

H
T .
F T
O EN
E M
G P
A O
U L
G E
N EV
A
L D
E B
H E
T W
"
N
S I
A E
O L
T O
R
D
E L
R A

T
R R
E G

P
F E

I
E T
R IN

CR F
E
N S
T IT

S
O F
O
S

A
I E
T US

AV I
R C
P
A

J
C E
S B
A
V B"
JA E
W
WHAT THE HACK IS JAVASCRIPT
• A web –based programming language.
• Add interactive behavior to webpages.
• Build web and mobile application.
• Develop games
• JavaScript is a lightweight, interpreted
programming language.
• Complementary to and integrated with
HTML.
• Open and cross-platform.
JAVASCRIPT -SYNTAX
JavaScript can be implemented using JavaScript statements that are placed within
the <script>... </script> HTML tags in a web page.

<script ...>
JavaScript code
</script>

<script language="javascript " type="text/javascript">


JavaScript code
</script
YOUR FIRST JAVASCRIPTCODE
<html>
<body>
<script
language="javascript"type="text/javascript
">
<!--
d o c u m e n t . w r i t e ( " H e l l o Wo r l d ! " )
//-->
</script>
</body>
</html>
JAVASCRIPT IN EXTERNAL FILE
//HTML FILE
<html>
<body>
<script src=“xyz.js”></script>
BROWSE
</body> R HTML
</html> PARSE
R JS

/ / j a v a s c r i p t fi l e
Console.log(“I like pizza”);
W i n d o w. a l e r t ( “ I l o v e p i z z a ” ) ;
JAVASCRIPT DATATYPES
These are the type of values that can be represented and
manipulated in a programming language.

JavaScript allows you to work with three primitive data


types:
 Numbers, e.g., 123, 120.50 etc.
 Strings of text, e.g. "This text string" etc.
 Boolean, e.g. true or false.
JAVASCRIPT VARIABLES
• A variable is container for storing data.
• A variable behaves as if it was the value that it
contains.
Two step
1.Declairation (var , let , const )
2. Assignment Operator

SYNTAX
let student=“Akash”;
Console.log(student);
ARITHMETIC EXPRESSIONS
Arithmetic expression is a combination of
oprands (value, variable ,etc…)
operator (+,-,*,/,%)
that can be evaluated to a value.
ex. Y = X + 5;

Example
let student =20;
student=student + 1;
console.log(student ,”here is o/p”);
SCOPE
//for let
let a=10;
{
let a ='A'
console.log(a)
}
console.log(a)
//let var
var a=10;
{
var a ='A'
console.log(a)
}
console.log(a)

//es6 var avoid it may create lots of bugs


AUGUMENT ASSIGNMENT OPERATOR
let student =10

1. student * =2; // student= student *2;


2. student + =2; // student= student +2;
3. student - =2; // student= student -2;
4. student % =2; // student= student %2;
5. student / =2; // student= student /2;

Operator Precedence:
6. Parenthesis
7. Exponents
8. Mul and div
9. Add and sub

Q: 1+2*(3+4);
HOW TO ACCEPT USER INPUT
FIND OUT CIRCUMFERENCE OF CIRCLE

FIND OUT HYPOTENUSE OF RIGHT ANGLE TRIANGLE


JAVASCRIPT STRING METHODS
PREDEFINED COMMON MATH
FUNCTION
DICE ROLLING PROJECT
METHOD CHAINING
Calling one method after another in one
continuous line of code.
IF STATEMENT
A basic form of decision making, if condition
is true then do something and if condition
false then not do any thing.
let age=15;
If(age>18){
Console.log(“eligible”);
}
else{
Console.log(“not eligible”);
}
(if,elseif,else)
CHECKED PROPERTY
SWITCH CASE
It is a selection based decision making statement.
LOGICAL OPERATOR
AND OPERATOR :
The logical AND operator ( && ) returns true if both operands are true
and returns false otherwise.

OR OPERATOR :
The logical OR operator ( || ) returns the boolean value true if either or
both operands is true and returns false otherwise.

NOT OPERATOR :
The logical NOT( ! ) operator negates the operand – that is, it returns the
opposite of the operand. If the operand is true , it returns false . And if it
is false , it returns true .

Note: we can check


multiple
Condition at a time.
LOOPING CONTROL STATEMENT
It is basically use to iterate a piece of code repeatedly.
1. FOOR LOOP
SYNTAX :
1 2 4
for(initialization ; condition check ; inc/dec){
3 //body
}
NESTED LOOP
A loop inside another loop

BREAK STATEMENT: CONTINUE


STATEMENT:
the break command ends
the loop and moves The continue statement
control to the next skips some lines of code
command outside the inside the loop and
loop continues with the next
iteration.
LOOPING CONTROL STATEMENT
2. WHILE LOOP :
It is entry control loop or pre test loop ,your code will
not execute
until it finds the condition true.

SYNTAX:
LOOPING CONTROL STATEMENT
It is exit control loop and post test loop ,If condition is not true
Still it will execute code once.
SYNTAX :
PRACTICE
*
* * *
**
* * * ****
* * * ******
* * *

* * * *
* *
* * *
* * * * *
* * * * *
FUNCTIONS
Define code once and use it many times to perform
some task called function.
Non parameterized :

parameterized :
CONVERT TEMPRATURE
RETURN STATEMENT
Returns a value back to the place where you invoked a
function.

TERNARY OPERATOR
This is alternate for if else
SYNTAX: CONDITION ? Exp if True : Exp if False;
ASSIGNMENT
TEMPLATE LITERALS
 Template literals are delimited with (`) Instead of double or
single quotes.
 Allows embedded variables and expressions.
ARRAYS
Think of its as a variable that can store
multiple value.
let fruit=“APPLE”;
let fruit =[“APPLE” ,”MANGO”,
“ORANGE”];
ARRAYS OPERATIONS
LOOP THROUGH AN ARRAY

5
INBUILT FUNCTIONS
2D ARRAYS
AN Array of Arrays
SPREAD OPERATOR
The spread operator (...) in JavaScript is a versatile syntax used
for several purposes, primarily for working with arrays and
iterable objects. Here's how it can be used and here where
zero or more arguments are expected.

const arr1 = [1, 2, 3];


const arr2 = [4, 5, 6];

const concatenated = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]


SPREAD OPERATOR
REST PARAMETER
Represents an indefinite number of parameter.
(PACK ARGUMENTS INTO AN ARRAY)
REST PARAMETER

function sum(…number){
let total=0;
for(let number of number){
total+=number
}
return total;
}
OBJECT
A Group of properties and methods
1.PROPERTIES : What an object has.
2,Method : What an object can do.
USE: To access properties and method.
THIS KEYWORD
Reference to a particular object the object depends on the
immediate context.
CLASS
• A blueprint for creating objects define what properties and methods
they have .
• Use a constructor for unique properties
CONSTRUCTOR
A special method of a class accept arguments and assign
properties.
STATIC KEYWORD
Static keyword belongs to the class, not the
objects.
Properties :Useful for fixed caches ,fixed
configuration.
INHERITANCE
A child class can inherit all the methods and properties from
another class.
GrandParen
t

Parent

me
SUPER KEYWORD
Super keyword refers to the parent class ,commonly used to
invoke constructor
Of a parent class.
ANONYMOUS OBJECT
Object without a name not directly referenced less syntax ,no
need for unique name.
FILTER & REDUCE
.filter() method is used to create a new array containing only the elements
that satisfy a given condition.
Eg:
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4, 6]
Eg:
const users = [ { name: "Alice", active: true },
{ name: "Bob", active: false },
{ name: "Charlie", active: true } ];
const activeUsers = users.filter(user => user.active);
console.log(activeUsers);

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


const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15

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


const product = numbers.reduce((acc, num) => acc * num, 1);
console.log(product); // 120
ERROR
Object with a description of something went wrong.

TYPES OF ERROR
• Can’t open a file
• Lose connection
• User type incorrect type
• TypeError
ARROW FUNCTION
TRY ,CATCH AND FINALLY
try block : we put those lines of code in try block ,may
cause exception.

catch block : It is use to handle the exception.

finally block: It is used to placed the imported


statement ,if there is exception in your code or
not it will always execute.
SET TIMEOUT()
Invokes a function after a number of milliseconds .
Note: asynchronous function doesn’t pause execution.
SET INTERVAL()
Invoke a function repeatedly after a number of
milliseconds.
DATE
The date object is used to work with dates and times.
SYNCHRONOUS CODE
In an ordered sequence step by step linear instructions.(Start
now , finish now)

ASYNCHRONOUS CODE
Out of sequence .(Start now , finish sometime later).
PROMISE
In JavaScript , A promise is a good way to handle asynchronous
operations . It is
Used to find out if the operation successfully completed or not.
A promise may have one of three states.
1. Pending
2. Fulfilled
3. Rejected
CREATING A PROMISE
To create a promise object, we use the Promise() constructor.

let promise = new Promise(function(resolve, reject) {


//do something
});

The Promise() constructor takes a function as an argument.


The function also accepts two functions resolve() and
reject(). If the promise returns successfully, the resolve()
function is called. And, if an error occurs, the reject()
function is called.
USING A PROMISE
then() method :
The then() method is used with the callback
when the promise is successfully fulfilled or
resolved.

catch() method :
The catch() method is used with the callback
when the promise is rejected or if an error
occurs.

finally() method :
The finally() method gets executed when the
promise is either resolved successfully or
rejected.
PROMISE
ASYNC
Async always returns a promise.
Makes a function return a promise.
async function abc(){
return “hello”;
}
AWAIT
Makes an async function wait for a promise.
DOM (DOCUMENT OF MODEL)
What is DOM?
• Definition:
• DOM stands for Document Object Model.
• Represents a webpage structure as a tree
of objects.
• Explanation:
• Each HTML element is a node.
• JavaScript can change these nodes.
DOM (DOCUMENT OF MODEL)
WHY IS DOM IMPORTANT?

• Key Points:
• Without DOM, web pages can't change after
loading.
• DOM allows JavaScript to:
• Update existing elements.
• Add new elements dynamically.
• Remove elements based on user actions.

• Examples of Interactions:
• Clicking a button can change text.
• Adding or removing paragraphs dynamically.
THE WINDOW OBJECT
•Definition:

•The window object is the main interface


for JavaScript in the browser.
•Functions and Properties:
•Holds all JavaScript-related properties
and methods.
•Examples:

// Displays an alert box


•window.alert("Hello!");
•console.log(window.innerWidth); // Logs the browser width
HOW TO SELECT ELEMENTS

Method What It Does Example


document.getElement-
getElementById Finds one element by ID
ById("title")
getElementsByClass- Finds all elements by document.getElements-
Name class ByClassName("btn")
Finds all elements by document.getElements-
getElementsByTagName
tag name ByTagName("p")
Finds the first matching document.querySe-
querySelector
element lector(".box")
Finds all matching ele- document.querySelect-
querySelectorAll
ments orAll(".box")
SELECTING AN ELEMENT
html
<p id="demo">Hello, World!</p>
<script>
var element =
document.getElementById("demo");
console.log(element.textContent); //
Output: Hello, World!
</script>
•Explanation: Accessing the content of a
specific <p> element.
)

CHANGING CONTENT (UPDATING


ELEMENTS

Property What It Does Example


Changes the HTML element.innerHTML
innerHTML
inside an element = "<b>New</b>";
element.textCon-
Changes only the
textContent tent = "Updated
text
Text";
Changes the visible element.innerText
innerText
text = "Changed!";
EXAMPLE – UPDATING CONTENT
Code Example:

html
<p id="demo">Click the button!</p>
<button onclick="updateText()">Click Me</button>
<script>
function updateText()
{
document.getElementById("demo").textContent = "Text Updated!";
}
</script>

•Explanation: Clicking the button updates the text within the <p> element
HOW TO ADD NEW ELEMENTS?

Method What It Does


createElement Creates a new element
Adds the new element to an
appendChild
existing one
Inserts HTML at specific posi-
insertAdjacentHTML
tions
EXAMPLE – ADDING ELEMENTS

html
<div id="container"></div>
<button onclick="addElement()">Add</button>

<script>

function addElement()
{
var newParagraph = document.createElement("p");

newParagraph.textContent = "This is a new paragraph!";

document.getElementById("container").appendChild(newParagraph); }

</script>

•Explanation: Clicking the button adds a new <p> element inside the container <div> .
REMOVING ELEMENTS

Method What It Does

Removes a child element from


removeChild
its parent

remove Directly removes an element

<p id="demo">Click to remove me</p>


<button
onclick="removeElement()">Remove</button>
<script>
function removeElement()
{ var element =
document.getElementById("demo");
element.remove(); }
</script>
FORM VALIDATION
<form onsubmit="return validateForm()">
<input type="text" id="name" placeholder="Enter
your name">
<input type="email" id="email" placeholder="Enter
your email">
<button type="submit">Submit</button>
</form>
<script>
function validateForm() {
var name =
document.getElementById("name").value;
var email = document.getElementById("email").value;
if (name == "" || email == "")
{ alert("All fields must be filled out!");
return false; }
return true; }
</script>
EVENT
Event is just an announcement by browser to get
attention
Types of events
• Click
• Double click
• Scroll

Each event requires an action


{ moniterEvents(documents); }
EXAMPLE
EVENT TARGET
Event target is the entity receives the event it
may have an eventListner (it has an action)

Eg:
<p>----------</p>
<button>-----------</button>
<h1>-------------</h1>

removeEventListn
addEventListner()
er()

element
SYNTAX
<event-target>.addEventListner(
<event-type>,<function-
action>)
)
Program
PHASES OR LIFECYCLE OF EVENTS
DEFAULT ACTION

//<a href="xyz.html" id="anchor">click</a>


//*html code
let anchor=document.getElementById("anchor");
anchor.addEventListener('click',function(even
t){
event.preventDefault();
anchor.textContent="hello java"
})
AVOIDING TO MANY LISTENER
EXAMPLE
// // <div>
<p>first</p>
//
// <p>second</p>
<p>third</p>
//
// <p>forth</p>
</div>
{ function alertp(event)
alert("you have
clicked "+
event.target.textContent
) }
let
a=document.querySelector
All('p');
for(let
i=0;i<a.length;i++)
{ let a1 =a[i];
PROJECT (SNAKE GAME §)

You might also like