0% found this document useful (0 votes)
21 views77 pages

JS_PPT

This document serves as an introduction to JavaScript, covering its basic syntax, variables, data types, operators, conditional statements, loops, arrays, functions, and DOM manipulation. It includes practice sets for hands-on learning and emphasizes the importance of JavaScript in web development alongside HTML and CSS. Additionally, it discusses event handling and the use of event listeners for interactive web applications.

Uploaded by

Yogesh Gavit
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)
21 views77 pages

JS_PPT

This document serves as an introduction to JavaScript, covering its basic syntax, variables, data types, operators, conditional statements, loops, arrays, functions, and DOM manipulation. It includes practice sets for hands-on learning and emphasizes the importance of JavaScript in web development alongside HTML and CSS. Additionally, it discusses event handling and the use of event listeners for interactive web applications.

Uploaded by

Yogesh Gavit
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/ 77

Introduction to

Javascript

Covered by : Arshiya Iram


What is javascript?
JS is a programming language. We use it to give instructions to the computer.

Input (code) Computer Output


Basic syntax

>>> console.log (“Hello World!”);


Comments
Variables
Variable is like a container for the data

ID Name Age

1.1 Raj 18

Memory
Rules of variable
• Variable names are case sensitive : “a” & “A” is different.

• Only letters , digits, underscore(_) and $ is allowed. (Not even


space)

• Only letters, underscore(_) or $ should be first characters.

• Reserved words cannot be variable names.


Reserved words (Keywords)
• break • else • typeof
• case • export • new
• catch • extends • null
• class • false • return
• const
• finally • switch
• continue
• for • this
• debugger
• function • throw
• default
• delete
• if • true

• Do • import • try
• In • void
Var, let & const

var: variable can be re-declared and updated. A global scop variable.

let: variable cannot be re-declared but can be updated. A block scope variable.

const: variable cannot be re-declared or updated. A block scope variable.


Data type
Practice Set 1
Qs1. Create a const object called “product” to store information shown in the picture.
Practice Set 2
Operators

• Arithmetic operators : (+, -, *, /, %, **,++, --)

• Assignment Operators : (=, +=, -=, *=, %=, **=)

• Comparison operators : (==, !=, ===, !==, <, <=, >, >=)

• Logical Operators : (&&, ||, !)


Operator

condition ? true output : false output

age > 18 ? “ adult ” : “ not adult “ ;


How to take input from the user?

>>>prompt (“Enter input: “);


Conditional Statements
To implement some condition in the code
Conditional Statements
Conditional Statements
Practice Set 3

Qs1. Get user to input a number using prompt(“Enter a

number: ”). Check if the number is a multiple of 5 or not.


Practice Set 4
Qs2. Write a code which can give grades to students according
to their scores:
o80-100, A
o70-89, B
o60-69, C
o50-59, D
o0-49, F
Practice Set 5

1. Is the user's age greater than 18?

2. Did the user input a valid email address?

3. Is the temperature above 25 degrees Celsius?

4. Has the user entered a valid username and password?

5. Did the user select "Yes" as their answer?


Strings
String is a sequence of characters used to represent text

let str=“Paarsh Infotech”;

str.length

str[0],str[1],str[2]
Template Literals
A way to have embedded expressions in strings
`this is a template literal`

To create strings by doing substitution of placeholders


` string text ${expression} string text`
String Methods
These are built-in functions to manipulate a string

• str.toUpperCase( )

• str.toLowerCase( )

• str.trim( ) // removes whitespaces


String Methods
• str.slice(start, end?) // returns part of string

• str1.concat( str2 ) // joins str2 with str1

• str.replace( searchVal, newVal )

• str.charAt( idx )
Practice Set 6
Qs1. Prompt the user to enter their full name. Generate a
username for them based on the input. Start username with
@, followed by their full name and ending with the fullname
length.

eg: user name = “arshiyairam” ,


username should be “@arshiyairam02”
Practice Set 7
Qs1. Create a JavaScript program that capitalizes the first letter of each word in a
given sentence. For example, if the input is "hello world", the output should be
"Hello World".

Qs2. Write a JavaScript function that counts the number of vowels (a, e, i, o, u) in a
given string and returns the count. For example, if the input is "hello", the output
should be 2.

Qs3. Write a JavaScript program that takes a sentence as input and returns the
longest word in the sentence. For example, if the input is "The quick brown fox
jumps over the lazy dog", the output should be "jumps".
Loops
Loops are used to execute a piece of code again & again

for (let i = 1; i <= 5; i++) {


console.log(«Paarsh Infotech");
}
Loops

Infinite Loop : A Loop that never ends


Loops

while (condition) {
//do some work
}
Loops

do {
//do some work
} while (condition) ;
Loops

for (let val of strVar) {


//do some work
}
Loops

for (let key in objVar) {


//do some work
}
Practice Set 7

Qs1. Print all even numbers from 0 to 100.

Qs2. Write a program for multiplication table.


Practice Set 8

Qs3. Create a game where you start with any random

game number. Ask the user to keep guessing the game

number until the user enters correct value.


Arrays

Collections of items

let heroes = [ “ironman” , “hulk” , “thor” , “batman” ];

let marks = [ 96, 75, 48, 83, 66 ];

let info = [ “rahul” , 86, “Delhi” ];


Arrays

arr[0], arr[1], arr[2] ....

1 2 3 4 5
Looping over an Array
Print all elements of an array
Practice Set 9
Qs. For a given array with marks of students -> [85, 97, 44, 37, 76, 60]

Find the average marks of the entire class.

Qs. For a given array with prices of 5 items -> [250, 645, 300, 900, 50]

All items have an offer of 10% OFF on them. Change the array to store
final price after applying offer.
Arrays

Push( ) : add to end

Pop( ) : delete from end & return

toString( ) : converts array to string

Concat( ) : joins multiple arrays & returns result


Arrays

Unshift( ) : add to start

shift( ) : delete from start & return

Slice( ) : returns a piece of the array

slice( startIdx, endIdx )

Splice( ) : change original array (add, remove, replace)

splice( startIdx, delCount, newEl1... )


Practice Set 10

Qs. Create an array to store companies -> “Bloomberg” ,

“Microsoft” , “Uber” , “Google” , “IBM” , “Netflix”

a. Remove the first company from the array

b. Remove Uber & Add Ola in its place

c. Add Amazon at the end


Functions
Block of code that performs a specific task, can be invoked whenever
needed

function functionName( ) { functionName( );


//do some work
}

function functionName( param1, param2 ...) {


//do some work
}
Arrow Functions
Compact way of writing a function

const functionName = ( param1, param2 ...) => {


//do some work
}
Practice Set 11

Qs. Create a function using the “function” keyword that


takes a String as an argument & returns the number of
vowels in the string.

Qs. Create an arrow function to perform the same task.


forEach Loop in Arrays
arr.forEach( callBackFunction )
CallbackFunction : Here, it is a function to execute for each element in
the array

*A callback is a function passed as an argument to another function.

arr.forEach( ( val ) => {


console.log(val);
})
Practice Set 12

Qs. For a given array of numbers, print the square of each


value using the forEach loop.
Some More Array Methods

Creates a new array with the results of some operation. The


value its callback returns are used to form new array
arr.map( callbackFnx( value, index, array ) )

let newArr = arr.map( ( val ) => {


return val * 2;
})
Some More Array Methods

Creates a new array of elements that give true for a


condition/filter.
Eg: all even elements

let newArr = arr.filter( ( val ) => {


return val % 2 === 0;
})
Some More Array Methods

Performs some operations & reduces the array to a single


value. It returns that single value.
Practice Set 13
Qs. We are given array of marks of students. Filter our of the marks of
students that scored 90+.

Qs. Take a number n as input from user. Create an array of numbers


from 1 to n.

Use the reduce method to calculate sum of all numbers in the array.

Use the reduce method to calculate product of all numbers in the array.
The 3 Musketeers of Web Dev
HTML CSS JS
(Structure) (Style) (Logic)
Start The Code With Connectivity

<style> tag connects HTML with CSS

<script> tag connects HTML with JS


Window Object

The window object represents an open window in a


browser. It is browser’s object (not JavaScript’s) & is
automatically created by browser.

It is a global object with lots of properties & methods.


DOM

When a web page is loaded, the browser creates a


Document Object Model (DOM) of the page
DOM Manipulation

document.getElementById(“myId”)

document.getElementsByClassName(“myClass”)

document.getElementsByTagName(“p”)
DOM Manipulation

document.querySelector(“#myId / .myClass / tag”)


//returns first element

document.querySelectorAll(“#myId / .myClass / tag”)


//returns a NodeList
DOM Manipulation

• tagName : returns tag for element nodes

• innerText : returns the text content of the element and all its children

• innerHTML : returns the plain text or HTML contents in the element

• textContent : returns textual content even for hidden elements


Homework
Practice Set 14

Qs. Create a H2 heading element with text - “Hello


JavaScript” . Append “from Paarsh Infotech students” to
this text using JS.

Qs. Create 3 divs with common class name - “box” . Access


them & add some unique text to each of them.
DOM Manipulation

• getAttribute( attr ) //to get the attribute value

• setAttribute( attr, value ) //to set the attribute value

• node.style
DOM Manipulation
let el = document.createElement(“div“)

• node.append( el ) //adds at the end of node (inside)

• node.prepend( el ) //adds at the start of node (inside)

• node.before( el ) //adds before the node (outside)

• node.after( el ) //adds after the node (outside)

• node.remove( ) //removes the node


Practice Set 15
Qs. Create a new button element. Give it a text “click me” , background color of

red & text color of white.

Insert the button as the first element inside the body tag.

Qs. Create a tag in html, give it a class & some styling.

Now create a new class in CSS and try to append this class to the element.

Did you notice, how you overwrite the class name when you add a new one?

Solve this problem using classList.


Events
The change in the state of an object is known as an Event
Events are fired to notify code of "interesting changes" that may affect
code execution.

• Mouse events (click, double click etc.)


• Keyboard events (keypress, keyup, keydown)
• Form events (submit etc.)
• Print event & many more
Event Handling
node.event = ( ) => {
//handle here
}

Example
btn.onclick = ( ) => {
console.log(“btn was clicked”);
}
Event Object
It is a special object that has details about the event.

All event handlers have access to the Event Object's properties


and methods.

node.event = (e) => {


//handle here
}

e.target, e.type, e.clientX, e.clientY


Event Listeners
node.addEventListener( event, callback )

node.removeEventListener( event, callback )

*Note : the callback reference should be same to remove


Practice Set 16

Qs. Create a toggle button that changes the screen to dark-


mode when clicked & light-mode when clicked again.

You might also like