[Go to site: main page, start]

0% found this document useful (0 votes)
2 views78 pages

Java Script

JavaScript (JS) is a programming language used to create interactive and dynamic web pages. It includes concepts such as variables, data types, operators, conditional statements, loops, and functions, allowing developers to manipulate data and control program flow. The document also provides examples of JS syntax and practical exercises for users to practice their skills.

Uploaded by

svsam0208
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)
2 views78 pages

Java Script

JavaScript (JS) is a programming language used to create interactive and dynamic web pages. It includes concepts such as variables, data types, operators, conditional statements, loops, and functions, allowing developers to manipulate data and control program flow. The document also provides examples of JS syntax and practical exercises for users to practice their skills.

Uploaded by

svsam0208
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

What is JavaScript?

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

JS is used to make web pages interactive, dynamic, and functional.

Input (code) Computer browser Output


1st JS Code
[Link] is used to log (print) a message to the console

[Link](“NFSU Dharwad Campus”);

• To run JavaScript file, an html file is created


• Create a script tag at the end of the body tag
• Link js file to the html using the following command:
<script src=“[Link]”> </script>
Variables in JS
Variables are containers for data
In JavaScript, variables are defined using three keywords: var, let, and const.

radius

14

memory
let, const & var
var : Variable can be re-declared & updated. A global scope 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.


Variable Rules
Variable names are case sensitive; “a” & “A” is different.

Only letters, digits, underscore( _) and $ is allowed. (not even space)

Only a letter, underscore( _) or $ should be 1st character.

Reserved words cannot be variable names.


Data Types in JS
Primitive Types : Number, String, Boolean, Undefined, Null, BigInt, Symbol
Example // 7. Array (special type of object)
let fruits = ["Apple", "Banana", "Mango"];
// 1. String firstName: "Atul", // 8. Function
let name = "Avinash"; lastName: "Gupta", let greet = function() {
age: 30 return "Hello, World!";
// 2. Number }; };
let age = 25; //
integer // 9. Symbol (unique identifier)
let price = 99.99; // let uniqueId = Symbol("id");
floating-point
// 10. BigInt (for very large numbers)
// 3. Boolean let bigNumber =
let isStudent = true; 1234567890123456789012345678901234567890n;
let isGraduated = false;
// Output everything
// 4. Undefined [Link]("String:", name);
let notAssigned; // [Link]("Number:", age, price);
default is undefined [Link]("Boolean:", isStudent, isGraduated);
[Link]("Undefined:", notAssigned);
// 5. Null [Link]("Null:", emptyValue);
let emptyValue = null; [Link]("Object:", person);
[Link]("Array:", fruits);
// 6. Object [Link]("Function call:", greet());
let person = { [Link]("Symbol:", uniqueId);
[Link]("BigInt:", bigNumber);
Let‘s Practice
Qs1. Create a const object called “product” to store information shown in the picture.
Let‘s Practice
Qs1. Create a const object called “product” to store information shown in the picture.
Comments in JS
Part of Code which is not executed
Operators in JS
Used to perform some operation on data

Arithmetic Operators

+, -, *, /
Modulus (%)

Exponentiation (**)

Increment (++)

Decrement (--)
Operators in JS
Assignment Operators

= += -= *= %= **=
Operators in JS
Comparison Operators

Equal to == Equal to & type === used to check value and type, for eg. let x=5;
and let x =‘5’ will be different; false will be returned.

Not equal to != Not equal to & type !=== Returns true if values are not equal OR types
are different. Returns false only if both value
and type are same.

>, >=,<, <=


Operators in JS
Logical Operators

Logical AND &&

Logical OR ||

Logical NOT !
Conditional Statements
To implement some condition in the code

if Statement
Conditional Statements
if-else Statement
Conditional Statements
else-if Statement
Operators in JS
Ternary Operators

condition ? true output : false output


alert and prompt

alert displays a simple dialog box with a message and an OK button. For e.g. -

alert("Welcome to JavaScript!");

prompt() displays a dialog box that asks the user for input. It always returns the input as a string,
even if the user enters a number. For e.g.-

let name = prompt("Enter your name:");


typeof(name); // string
alert("Hello, " + name + "!");

Typecasting (Number(), parseInt(), parseFloat()) is needed when working with numbers to avoid
errors like string concatenation instead of arithmetic.
Let‘s Practice
Qs1. Get user to input a number using prompt(“Enter a number:”). Check if the number is a
multiple of 5 or not.
Let‘s Practice
Qs1. Get user to input a number using prompt(“Enter a number:”). Check if the number is a
multiple of 5 or not.
Let‘s Practice
Qs2. Write a code which can give grades to students according to their scores:
80-100, A
70-89, B
60-69, C
50-59, D
0-49, F
Let‘s Practice
Qs2. Write a code which can give grades to students according to their scores:
80-100, A
70-89, B
60-69, C
50-59, D
0-49, F
Loops in JS
Loops are used to execute a piece of code again & again

for Loop

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

[Link]("NFSU Dharwad");

}
Loops in JS
Infinite Loop : A Loop that never ends
Loops in JS
while Loop
Initialization
while (condition) {

// do some work

}
Loops in JS
do-while Loop

Initialization
do {

// do some work

} while (condition);
Loops in JS
The for...of loop in JavaScript is used to iterate over iterable objects such as arrays,
strings, maps, sets, and more. It gives you the values directly (not the indexes/keys).

for-of Loop
let numbers = [10, 20, 30];

for (let val of strVar) { for (let num of numbers) {


[Link](num);
//do some work }

}
Loops in JS
The for...in loop in JavaScript is used to iterate over the enumerable properties (keys) of an object.
Unlike for...of (which gives values), for...in gives you the property names (keys/indexes).

for-in Loop Output:

for (let key in objVar) {

//do some work

}
Let‘s Practice
Qs1. Print all even numbers from 0 to 100.
Let‘s Practice
Qs2.
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.
Let‘s Practice
Qs2.
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.
Strings in JS
String is a sequence of characters used to represent text. String in JS is immutable.

Create String

let str =“NFSU Dharwad“;

String Length

[Link]

String Indices

str[0], str[1], str[2]


Template Literals in JS
A way to have embedded expressions in strings

`this is a template literal`

String Interpolation

To create strings by doing substitution of placeholders

`string text ${expression} string text`


String Methods in JS
These are built-in functions to manipulate a string

[Link]( )

[Link]( )

[Link]( ) // removes starting and ending whitespaces


String Methods in JS
[Link](start, end?) // returns part of string [end character is not included]

let text = "JavaScript"; let lastPart = [Link](-6);


[Link](lastPart); // "Script" (last 6 characters)
let result = [Link](4);
[Link](result); // "Script" (from index 4 to end) let middle = [Link](-6, -3);
[Link](middle); // "Scr" (indexes from end -6 to -4)

[Link]( str2 ) // joins str2 with str1

[Link]( searchVal, newVal )

[Link]( idx )
Let‘s Practice
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 =“nfsudharwad” , username should be “@nfsudharwad11”


Let‘s Practice
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 =“nfsudharwad” , username should be “@nfsudharwad11”
Arrays in JS
Collections of items (is a mutable object which is a collection of homogeneous data elements).

Create Array

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

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

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


Arrays in JS
Array Indices

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

0 1 2 3 4
Looping over an Array
Print all elements of an array
Let‘s Practice
Qs. For a given array with marks of students ->[85, 97, 44, 37, 76, 60]. Find the average marks of
the entire class.
Let‘s Practice
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 in JS
Array Methods // Start with an array of fruits
let fruits = ['apple', 'banana', 'cherry'];

[Link]('grape');
Push( ) : add to end (can insert more than one [Link]('After push():', fruits);
elements) // Output: After push(): [ 'apple', 'banana', 'cherry', 'grape' ]

let lastFruit = [Link]();


Pop( ) : delete from end & return [Link]('Removed element using pop():', lastFruit);
// Output: Removed element using pop(): grape

[Link]('After pop():', fruits);


toString( ) : converts array to string // Output: After pop(): [ 'apple', 'banana', 'cherry' ]

let fruitsAsString = [Link]();


[Link]('After toString():', fruitsAsString);
// Output: After toString(): apple,banana,cherry
Arrays in JS
Array Methods // Let's start with two separate arrays.
const array1 = ['apple', 'banana'];
const array2 = ['cherry', 'grape'];
Concat( ) : joins multiple arrays & returns result const combinedArray = [Link](array2);
[Link]('After concat():', combinedArray);
// Output: After concat(): [ 'apple', 'banana', 'cherry', 'grape' ]

[Link]('kiwi');
Unshift( ) : add to start [Link]('After unshift():', combinedArray);
// Output: After unshift(): [ 'kiwi', 'apple', 'banana', 'cherry',
'grape' ]

const firstElement = [Link]();


shift( ) : delete from start & return [Link]('Removed element using shift():', firstElement);
// Output: Removed element using shift(): kiwi

[Link]('After shift():', combinedArray);


// Output: After shift(): [ 'apple', 'banana', 'cherry', 'grape' ]
Arrays in JS
// Let's start with an array of numbers.
let numbers = [10, 20, 30, 40, 50, 60, 70];

let slicedArray = [Link](2, 5);


[Link]('Original array after slice():', numbers);
Array Methods // Output: Original array after slice(): [ 10, 20, 30, 40, 50, 60, 70 ]

[Link]('New array from slice():', slicedArray);


// Output: New array from slice(): [ 30, 40, 50 ]
Slice( ) : returns a piece of the array. It does
not modify the original array. let removedElements = [Link](3, 2);
[Link]('Original array after splice() deletion:', numbers);
// Output: Original array after splice() deletion: [ 10, 20, 30, 60, 70 ]

[Link]('Elements removed by splice():', removedElements);


slice( startIdx, endIdx ) // Output: Elements removed by splice(): [ 40, 50 ]

[Link](2, 0, 99, 100);


[Link]('Original array after splice() addition:', numbers);
Splice( ) : change original array (add, remove, // Output: Original array after splice() addition: [ 10, 20, 99, 100, 30, 60,
70 ]
replace)
[Link](4, 2, 500);
[Link]('Original array after splice() replacement:', numbers);
splice( startIdx, delCount, newEl1... ) // Output: Original array after splice() replacement: [ 10, 20, 99, 100,
500, 70 ]
Let‘s Practice
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


Let‘s Practice
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 in JS
Block of code that performs a specific task, can be invoked whenever needed
Functions in JS
Function Definition Function Call

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

const sum =( a, b ) =>{

return a +b;

}
Let‘s Practice
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.


Let‘s Practice
Qs. Create a function using the “function”
keyword that takes a String as an argument Qs. Create an arrow function to perform the same task.
& returns the number of vowels in the string.
forEach (method) Loop in Arrays
[Link]( callBackFunction )
ForEach is a method in JavaScript defined for arrays, in which, function can be passed as a argument. These
functions are known as callBackFunction. CallbackFunction execute for each element in the array
*A callback is a function passed as an argument to another function.

// Example array
[Link](function(element, index, array) let numbers = [1, 2, 3, 4, 5];
// Using forEach to print each element
{ [Link](function(num, index) {
// code to run [Link](`Element at index ${index} is ${num}`);
}); });
O/p:
Element at index 0 is 1
Element at index 1 is 2
Element at index 2 is 3
Element at index 3 is 4
Element at index 4 is 5
Let‘s Practice
Qs. For a given array of numbers, print the square of each value using the forEach loop.
Some More Array Methods
Map

Similar to the forEach method but it creates a new array with the results of some operation. The
value its callback returns, are used to form new array.

[Link]( callbackFnx( value, index, array ) )

let newArr =[Link]( ( val ) =>

{return val * 2;

})
Some More Array Methods
Filter

Creates a new array of elements that give true for a condition/filter.


Eg: all even elements

let newArr =[Link]( ( ( val ) =>{

return val % 2 ===0;

})
Some More Array Methods
Reduce Performs some operations & reduces the array to a single value. It returns that single value.

[Link](function(accumulator, currentValue, index, array)


{
// return updated accumulator
•accumulator → stores the result (updated after each step).
}, initialValue);
•currentValue → the current element being processed.
•index (optional).
•array (optional).
•initialValue → starting value for the accumulator.
Let‘s Practice
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.
Let‘s Practice
Qs. We are given array of marks of students. Filter our of the marks of students that scored 90+.
Let‘s Practice
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)
Starter Code
<style> tag connects HTML with CSS

<script> tag connects HTML with JS


<html>
<head>
<title> Website Name </title>
</head>
<body>
<!-- Content Tags -->
</body>
</html>
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.


What is DOM?
• When a web page is loaded, the browser creates a Document Object Model (DOM) of the page
• Using DOM, any document element can be accessed in JS.

• Use [Link]([Link]) to see the details of the document object.


It shows the full object structure in a tree-like format.
• Use [Link]([Link]) to see the content of the body object

• Using JS, any document elements can be changed


dynamically without making any change in original script.
For e.g., [Link]=yellow; will change
body background to yellow without making any change in
script.
DOM Manipulation <body>
<h1 id="heading">Hello World!</h1>
</body>
Selecting with id const heading = [Link]("heading");
[Link] = "DOM Manipulation Successful!";
[Link](“myId”)

<body>
<h1 class="h-class">Hello World!</h1>
Selecting with class <h2 class="h-class">Hello World!</h2>
[Link](“myClass”) </body>
const heading = [Link]("h-class");
heading[0].innerText = “Heading Manipulation Successful!";

Selecting with tag <body>


<p>Hello World!</p>
[Link](“p”) <p>Hello World!</p>
</body>
let paras = [Link](“p");
Paras[0].innerText = “Para Manipulation Successful!";
DOM Manipulation
Query Selector • Returns the first element that matches a selector. If no element matches, it returns null.
• More flexible than getElementById, getElementsByClassName, or getElementsByTagName
because you can use any selector (#id, .class, tag, attribute selectors, etc.).

[Link](“#myId / .myClass / tag”)


//returns first element

[Link](“#myId / .myClass / tag”)


//returns a NodeList
DOM Manipulation
Properties Used to get/set the content of html page.

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


Let‘s Practice
Qs. Create a H2 heading element with text - “Hello JavaScript”. Now, Append “from NFSU Dharwad
Campus” to this text using JS.

Qs. Create 3 divs with common class name - “box”. Access them & add some unique text to each of
them.
Let‘s Practice
Qs. Create a H2 heading element with text - “Hello JavaScript”. Append “from NFSU Dharwad
Campus” to this text using JS.
Let‘s Practice

Qs. Create 3 divs with common class name - “box”. Access them & add some unique text to each of
them.
DOM Manipulation
Attributes

getAttribute( attr ) //to get the attribute value

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

Style access or modify the inline CSS styles

[Link]
Syntax:
[Link] = "value";
DOM Manipulation

Style access or modify the inline CSS styles


[Link]
Syntax:
[Link] = "value"; // propertyName is a CSS property
DOM Manipulation
let el = [Link](“div“)

Insert Elements

[Link]( el ) //adds at the end of node (inside)

[Link]( el ) //adds at the start of node (inside)

[Link]( el ) //adds before the node (outside)

[Link]( el ) //adds after the node (outside)

Delete Element

[Link]( ) //removes the node


Let‘s Practice
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 <p> tag in html, give it a class & some styling. Now create a new class in CSS and try to
append this class to the <p> element. Did you notice, how you overwrite the class name when you add a
new one? Solve this problem using classList.
Let‘s Practice
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.
Let‘s Practice
Qs. Create a <p> tag in html, give it a class & some styling. Now create a new class in CSS and try to
append this class to the <p> element. Did you notice, how you overwrite the class name when you add a
new one? Solve this problem using classList.

You might also like