JavaScript notes
JavaScript notes
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
Console.log is used to log (print) a message to the console
lege
Col
console.log(“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++) {
console.log("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
str.length
String Indices
e
`this is a template literal`
lleg
a Co
n
String Interpolation
Ap
To create strings by doing substitution of placeholders
str.toUpperCase( )
lege
str.toLowerCase( )
Col
pna
A
str.trim( ) // removes whitespaces
String Methods in JS
str.slice(start, end?) // returns part of string
lege
Col
str1.concat( str2 ) // joins str2 with str1
pna
A
str.replace( searchVal, newVal )
str.charAt( 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
arr.forEach( callBackFunction )
lege
l
*A callback is a function passed as an argument to another function.
a Co
arr.forEach( ( val ) => {
console.log(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
arr.map( callbackFnx( value, index, array ) )
Ap
let newArr = arr.map( ( val ) => { n
return val * 2;
})
Some More Array Methods
Filter
ge
Eg: all even elements
olle
let newArr = arr.filter( ( ( 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
document.getElementById(“myId”)
olle
Selecting with class
na C
Ap
document.getElementsByClassName(“myClass”)
document.getElementsByTagName(“p”)
DOM Manipulation
Query Selector
lege
ol
document.querySelector(“#myId / .myClass / tag”)
C
//returns first element
pna
A
document.querySelectorAll(“#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
node.style
DOM Manipulation
Insert Elements let el = document.createElement(“div“)
ge
node.append( el ) //adds at the end of node (inside)
le
Col
node.prepend( el ) //adds at the start of node (inside)
pna
A
node.before( 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.