JS1 ClassNotes Merged
JS1 ClassNotes Merged
lege
Col
a
Input (code) Computer Output
Apn
use console in any browser or just open one of your projects and use that
the code is not permanent, we can use the up & down arrow to bring back old code
Setting up VS Code
It is a free & popular code editor by Microsoft
lege
Col
pna
A we'll use the chrome developer tools console to write our code
but not for long terms as afterwards we will start to use js file
like we used for css
Our 1st JS Code
[Link] is used to log (print) a message to the console
lege
Col
[Link](“Apna College”);
pna
A
Variables in JS
Variables are containers for data
lege
Col
na
radius
14
Ap
memory
Variable Rules
Variable names are case sensitive; “a” & “A” is different.
lege
l
Only letters, digits, underscore( _ ) and $ is allowed. (not even space)
a Co
Only a letter, underscore( _ ) or $ should be 1st character.
Apn
Reserved words cannot be variable names.
let, const & var
var : Variable can be re-declared & updated. A global scope variable.
lege
ol
let : Variable cannot be re-declared but can be updated. A block scope variable.
C
pna
A
const : Variable cannot be re-declared or updated. A block scope variable.
Data Types in JS
Primitive Types : Number, String, Boolean, Undefined, Null, BigInt, Symbol
lege
Col
pna
A
ge
String
ol le
a C
Number
Follow
Apn
Boolean
Let‘s Practice
Qs1. Create a const object called “product” to store information shown in the picture.
lege
Col
pna
A
Let‘s Practice
Qs2. Create a const object called “profile” to store information shown in the picture.
lege
Col
pna
A
Comments in JS
Part of Code which is not executed
lege
Col
pna
A
Operators in JS
Used to perform some operation on data
e
Arithmetic Operators
+, -, *, /
lleg
a Co
Modulus
Exponentiation Apn
Increment
Decrement
Operators in JS
Assignment Operators
= += -= *= %= **=
lege
Col
pna
A
Operators in JS
Comparison Operators
Equal to ==
ge
Equal to & type
le
===
Not equal to !=
Col
Not equal to & type !==
pna
>, >=, <, <= A
Operators in JS
Logical Operators
lege
Col
a
||
n
Logical OR
Logical NOT ! Ap
Conditional Statements
To implement some condition in the code
if Statement
lege
Col
pna
A
Conditional Statements
if-else Statement
lege
Col
pna
A
Conditional Statements
else-if Statement
lege
Col
pna
A
Operators in JS
Ternary Operators
ge
condition ? true output : false output
olle
na C
Ap
MDN Docs
lege
Col
pna
A
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.
lege
Col
pna
A
Let‘s Practice
Qs2. Write a code which can give grades to students according to their scores:
80-100, A
e
70-89, B
eg
60-69, C
50-59, D
Coll
a
0-49, F
Apn
Loops in JS
lege
l
Loops are used to execute a piece of code again & again
a Co
pn
for Loop
A
for (let i = 1; i <= 5; i++) {
[Link]("apna college");
}
Loops in JS
lege
l
Infinite Loop : A Loop that never ends
a Co
Apn
Loops in JS
lege
ol
while Loop
na C
p
while (condition) {
}
A
// do some work
Loops in JS
lege
ol
do-while Loop
na C
do {
A
// do some workp
} while (condition);
Loops in JS
lege
ol
for-of Loop
na C
p
for (let val of strVar) {
}
A
//do some work
Loops in JS
lege
ol
for-in Loop
na C
p
for (let key in objVar) {
}
A
//do some work
Let‘s Practice
Qs1. Print all even numbers from 0 to 100.
lege
Col
pna
A
Let‘s Practice
lege
ol
Qs2.
C
Create a game where you start with any random game number. Ask the user to keep
na
guessing the game number until the user enters correct value.
p
A
Strings in JS
lege
l
String is a sequence of characters used to represent text
a Co
pn
Create String
String Length
A
[Link]
String Indices
e
`this is a template literal`
lleg
a Co
n
String Interpolation
Ap
To create strings by doing substitution of placeholders
[Link]( )
lege
[Link]( )
Col
pna
A
[Link]( ) // removes whitespaces
String Methods in JS
[Link](start, end?) // returns part of string
lege
Col
[Link]( str2 ) // joins str2 with str1
pna
A
[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.
lege
l
eg: user name = “shradhakhapra” , username should be “@shradhakhapra13”
a Co
Apn
Arrays in JS
Collections of items
Create Array
lege
Col
a
let heroes = [ “ironman”, “hulk”, “thor”, “batman” ];
Apn
let marks = [ 96, 75, 48, 83, 66 ];
lege
Col
pna
0 1 2
A
3 4
Looping over an Array
Print all elements of an array
lege
Col
pna
A
Let‘s Practice
Qs. For a given array with marks of students -> [85, 97, 44, 37, 76, 60]
e
Find the average marks of the entire class.
lleg
a Co
Apn
Let‘s Practice
Qs. For a given array with prices of 5 items -> [250, 645, 300, 900, 50]
e
All items have an offer of 10% OFF on them. Change the array to store final price after
leg
applying offer.
Col
pna
A
Arrays in JS
Array Methods
lege
l
Push( ) : add to end
a Co
Apn
Pop( ) : delete from end & return
lege
l
Concat( ) : joins multiple arrays & returns result
a Co
Unshift( ) : add to start
Apn
shift( ) : delete from start & return
Arrays in JS
Array Methods
lege
ol
Slice( ) : returns a piece of the array
na C
slice( startIdx, endIdx )
Ap
Splice( ) : change original array (add, remove, replace)
lege
ol
a. Remove the first company from the array
na C
Ap
b. Remove Uber & Add Ola in its place
lege
Col
pna
A
Functions in JS
Function Definition Function Call
lege
}
Col
pna
A
function functionName( param1, param2 ...) {
}
Arrow Functions
ge
Compact way of writing a function
olle
a C
const functionName = ( param1, param2 ...) => {
}
//do some work
Apn
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.
lege
Col
na
Qs. Create an arrow function to perform the same task.
Ap
forEach Loop in Arrays
[Link]( callBackFunction )
lege
l
*A callback is a function passed as an argument to another function.
a Co
[Link]( ( val ) => {
[Link](val); Ap n
})
Let‘s Practice
Qs. For a given array of numbers, print the square of each value using the forEach loop.
lege
Col
pna
A
Some More Array Methods
Map
Creates a new array with the results of some operation. The value its callback returns are
used to form new array
lege
Col
a
[Link]( callbackFnx( value, index, array ) )
Ap
let newArr = [Link]( ( val ) => { n
return val * 2;
})
Some More Array Methods
Filter
ge
Eg: all even elements
olle
let newArr = [Link]( ( ( val ) => {
na C
})
return val % 2 === 0;
Ap
Some More Array Methods
Reduce
lege
Col
Performs some operations & reduces the array to a single value. It returns
na
that single value.
Ap
Let‘s Practice
Qs. We are given array of marks of students. Filter our of the marks of students that scored 90+.
lege
Col
na
Qs. Take a number n as input from user. Create an array of numbers from 1 to n.
p
A
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)
lege
Col
pna
A
Starter Code
<style> tag connects HTML with CSS
lege
Col
pna
A
<html>
<head>
<title> Website Name </title>
</head>
<body>
<!-- Content Tags -->
lege
</body>
Col
na
</html>
Ap
Window Object
ge
The window object represents an open window in a browser. It is browser’s object (not JavaScript’s)
lle
& is automatically created by browser.
a Co
n
It is a global object with lots of properties & methods.
Ap
What is DOM?
lege
l
When a web page is loaded, the browser creates a Document Object Model (DOM) of the page
a Co
Apn
DOM Manipulation
Selecting with id
ge
[Link](“myId”)
olle
Selecting with class
na C
Ap
[Link](“myClass”)
[Link](“p”)
DOM Manipulation
Query Selector
lege
ol
[Link](“#myId / .myClass / tag”)
C
//returns first element
pna
A
[Link](“#myId / .myClass / tag”)
//returns a NodeList
DOM Manipulation
Properties
lege
l
tagName : returns tag for element nodes
a Co
innerText : returns the text content of the element and all its children
Apn
innerHTML : returns the plain text or HTML contents in the element
lege
Col
pna
A
Qs. Create 3 divs with common class name - “box”. Access them & add some unique text to each
of them.
DOM Manipulation
Attributes
lege
l
getAttribute( attr ) //to get the attribute value
a Co
pn
setAttribute( attr, value ) //to set the attribute value
Style A
[Link]
DOM Manipulation
Insert Elements let el = [Link](“div“)
ge
[Link]( el ) //adds at the end of node (inside)
le
Col
[Link]( el ) //adds at the start of node (inside)
pna
A
[Link]( el ) //adds before the node (outside)
Delete Element
lege
l
Insert the button as the first element inside the body tag.
a Co
Apn
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.
Events in JS
The change in the state of an object is known as an Event
ege
Events are fired to notify code of "interesting changes" that may affect code execution.
l
Col
pna
A
Mouse events (click, double click etc.)
e
[Link] = ( ) => {
leg
//handle here
ol
}
na C
Ap
example
[Link] = ( ) => {
[Link](“btn was clicked”);
}
Event Object
It is a special object that has details about the event.
lege
All event handlers have access to the Event Object's properties and methods.
Col
[Link] = (e) => {
pna
A
//handle here
}
e
[Link]( event, callback )
lleg
Co
[Link]( event, callback )
a
Apn
*Note : the callback reference should be same to remove
Let‘s Practice
Qs. Create a toggle button that changes the screen to dark-mode when clicked & light-mode
e
when clicked again.
lleg
a Co
Apn
Classes & Objects
lege
Col
pna
A
Prototypes in JS
lege
l
A javaScript object is an entity having state and behavior (properties and method).
a Co
n
JS objects have a special property called prototype.
Ap
We can set prototype using _ _ proto _ _
lege
l
Class is a program-code template for creating objects.
a Co
n
Those objects will have some state (variables) & some behaviour (functions) inside it.
class MyClass {
constructor( ) { ... }
Ap
myMethod( ) { ... }
lege
l
Constructor( ) method is : class MyClass {
a Co
constructor( ) { ... }
initializes object
A
}pn myMethod( ) { ... }
Inheritance in JS
lege
l
inheritance is passing down properties & methods from parent class to child class.
a Co
n
class Parent {
lege
l
The super keyword is used to call the constructor of its parent class to access the parent's
properties and methods.
a Co
Apn
super( args ) // calls Parent‘s constructor
[Link]( args )
Let‘s Practice
lege
l
Qs. You are creating a website for your college. Create a class User with 2 properties, name &
Co
email. It also has a method called viewData( ) that allows user to view website data.
a
Apn
Qs. Create a new class called Admin which inherits from User. Add a new method called
editData to Admin that allows it to edit website data.
Error Handling
try-catch
lege
ol
try {
na C
Ap
} catch ( err ) { //err is error object
}
What this chapter is about?
lege
l
async await >> promise chains >> callback hell
a Co
Apn
Sync in JS
Synchronous
Synchronous means the code runs in a particular sequence of instructions given in the program.
e
Each instruction waits for the previous instruction to complete its execution.
lleg
Co
Asynchronous
na
Due to synchronous programming, sometimes imp instructions get
Ap
blocked due to some previous instructions, which causes a delay in the UI.
Asynchronous code execution allows to execute next instructions
immediately and doesn't block the flow.
Callbacks
ge
A callback is a function passed as an argument to another function.
le
Col
pna
A
Callback Hell
ge
Callback Hell : Nested callbacks stacked below one another forming a pyramid structure.
(Pyramid of Doom)
olle
na C
p
This style of programming becomes difficult to understand & manage.
A
Promises
Promise is for “eventual” completion of task. It is an object in JS.
e
It is a solution to callback hell.
lleg
Co
let promise = new Promise( (resolve, reject) => { .... } )
a
Apn Function with 2 handlers
lege
Pending : the result is undefined
Col
Resolved : the result is a value (fulfilled) resolve( result )
pna
Rejected : the result is an error object reject( error )
A
*Promise has state (pending, fulfilled) & some
result (result for resolve & error for reject).
Promises
ge
.then( ) & .catch( )
olle
C
[Link]( ( res ) => { .... } )
pna
A
[Link]( ( err ) ) => { .... } )
Async-Await
async function always returns a promise.
leg
async function myFunc( ) { .... }
e
Col
na
await pauses the execution of its surrounding async function until the promise is settled.
Ap
IIFE : Immediately Invoked Function Expression
lege
l
IIFE is a function that is called immediately as soon as it is defined.
a Co
Apn