JavaScript Basics: Variables, Functions, and Loops
JavaScript Basics: Variables, Functions, and Loops
Setting up VS Code
JS is a programming language. We use it to give instructions to the computer. It is a free & popular code editor by Microsoft
lege lege
Col Col
a a
Apn Apn
Input (code) Computer Output
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
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
lege lege
Col Col
a a
Apn
[Link](“Apna College”);
Apn
radius
14
memory
e e
Variable names are case sensitive; “a” & “A” is different. var : Variable can be re-declared & updated. A global scope variable.
lleg lleg
o o
Only letters, digits, underscore( _ ) and $ is allowed. (not even space)
C C
let : Variable cannot be re-declared but can be updated. A block scope variable.
a a
Apn Apn
Only a letter, underscore( _ ) or $ should be 1st character.
Reserved words cannot be variable names. const : Variable cannot be re-declared or updated. A block scope variable.
Data Types in JS
e
Primitive Types : Number, String, Boolean, Undefined, Null, BigInt, Symbol
lleg
a Co ege
Apn l l
String
a Co
Apn
Number
Follow
Boolean
lege ege
Col Coll
a a
Apn Apn
Comments in JS Operators in JS
Part of Code which is not executed Used to perform some operation on data
ge ge
Arithmetic Operators
olle +, -, *, /
olle
a C a C
Apn Apn
Modulus
Exponentiation
Increment
Decrement
Operators in JS Operators in JS
Assignment Operators Comparison Operators
ge ge
= += -= *= %= **= == ===
lle lle
Equal to Equal to & type
Co Co
!= !==
a a
Not equal to Not equal to & type
ge ge
if Statement
e e
&&
ll ll
Logical AND
a Co a Co
Apn Apn
Logical OR ||
Logical NOT !
llege llege
a Co a Co
Apn Apn
Operators in JS MDN Docs
Ternary Operators
lege lege
condition ? true output : false output
Col Col
a a
Apn Apn
ge ge
70-89, B
lle lle
60-69, C
Co Co
50-59, D
a a
Apn Apn
0-49, F
ge ge
Loops in JS Loops in JS
olle olle
Loops are used to execute a piece of code again & again Infinite Loop : A Loop that never ends
a C a C
Apn Apn
for Loop
[Link]("apna college");
}
ge ge
Loops in JS Loops in JS
olle olle
C C
while Loop do-while Loop
a a
Apn Apn
while (condition) {
do {
// do some work
// do some work
}
} while (condition);
ge ge
Loops in JS Loops in JS
olle olle
C C
for-of Loop for-in Loop
a a
Apn Apn
for (let val of strVar) { for (let key in objVar) {
} }
ge
Let‘s Practice Let‘s Practice
olle
C
Qs1. Print all even numbers from 0 to 100. Qs2.
ge Apn
a
Create a game where you start with any random game number. Ask the user to keep
lle
guessing the game number until the user enters correct value.
a Co
Apn
ge
Strings in JS Template Literals in JS
olle
String is a sequence of characters used to represent text A way to have embedded expressions in strings
a C
Apn ge
Create String `this is a template literal`
olle
let str = “Apna College“;
a C
Apn
String Length String Interpolation
ge
[Link](start, end?) // returns part of string
ge lle
[Link]( )
lle a Co
Co
[Link]( str2 ) // joins str2 with str1
a Apn
[Link]( )
Apn
[Link]( ) // removes whitespaces
[Link]( searchVal, newVal )
[Link]( idx )
ge
Start username with @, followed by their full name and ending with the fullname length.
ge olle
Create Array
lle a C
Co
eg: user name = “shradhakhapra” , username should be “@shradhakhapra13”
Apn
let heroes = [ “ironman”, “hulk”, “thor”, “batman” ];
pna
A
let marks = [ 96, 75, 48, 83, 66 ];
e e
Array Indices
leg leg
ol ol
arr[0], arr[1], arr[2] ....
a C a C
0 1 2
Apn
3 4
Apn
ge ge
Find the average marks of the entire class. All items have an offer of 10% OFF on them. Change the array to store final price after
olle olle
applying offer.
a C a C
Apn Apn
Arrays in JS Arrays in JS
e e
Array Methods Array Methods
leg leg
ol ol
Push( ) : add to end Concat( ) : joins multiple arrays & returns result
a C a C
Apn Apn
Pop( ) : delete from end & return Unshift( ) : add to start
e e
Array Methods
leg leg
Col Col
Slice( ) : returns a piece of the array a. Remove the first company from the array
a a
Apn Apn
slice( startIdx, endIdx )
b. Remove Uber & Add Ola in its place
Functions in JS Functions in JS
Block of code that performs a specific task, can be invoked whenever needed
Function Definition Function Call
ge ge
function functionName( ) { functionName( );
lle lle
Co o
//do some work
na a C
Apn
}
ege
Compact way of writing a function
ll
Qs. Create a function using the “function” keyword that takes a String as an argument &
Co
returns the number of vowels in the string.
a ge
Apn
const functionName = ( param1, param2 ...) => {
olle
//do some work
a C
Apn
}
Qs. Create an arrow function to perform the same task.
return a + b;
}
forEach Loop in Arrays Let‘s Practice
[Link]( callBackFunction ) Qs. For a given array of numbers, print the square of each value using the forEach loop.
ge
CallbackFunction : Here, it is a function to execute for each element in the array
llege olle
Co C
*A callback is a function passed as an argument to another function.
a a
Ap n Apn
[Link]( ( val ) => {
[Link](val);
})
e e
Creates a new array with the results of some operation. The value its callback returns are Creates a new array of elements that give true for a condition/filter.
eg eg
Eg: all even elements
ll ll
used to form new array
Co Co
na na
[Link]( callbackFnx( value, index, array ) )
Ap Ap
let newArr = [Link]( ( ( val ) => {
})
llege
Qs. We are given array of marks of students. Filter our of the marks of students that scored 90+.
o ge
Reduce
a C lle
Performs some operations & reduces the array to a single value. It returns
Ap n Co
that single value.
a
Apn
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 Starter Code
<style> tag connects HTML with CSS
HTML CSS JS
(structure) (style) (logic) <script> tag connects HTML with JS
llege llege
a Co a Co
Apn Apn
<html>
Window Object
ge
<head>
le
The window object represents an open window in a browser. It is browser’s object (not JavaScript’s)
ol
<title> Website Name </title> & is automatically created by browser.
a C
</head>
ge Apn
<body> It is a global object with lots of properties & methods.
lle
<!-- Content Tags -->
Co
</body>
a
Apn
</html>
llege
o
When a web page is loaded, the browser creates a Document Object Model (DOM) of the page
C
Selecting with id
a ge
Apn le
[Link](“myId”)
a Col
Apn
Selecting with class
[Link](“myClass”)
[Link](“p”)
DOM Manipulation DOM Manipulation
Query Selector Properties
lege lege
ol ol
tagName : returns tag for element nodes
C C
[Link](“#myId / .myClass / tag”)
a a
//returns first element
Apn Apn
innerText : returns the text content of the element and all its children
e
students” to this text using JS.
leg
a Col
Apn
Qs. Create 3 divs with common class name - “box”. Access them & add some unique text to each
of them.
lege lege
ol ol
[Link]( el ) //adds at the end of node (inside)
getAttribute( attr ) //to get the attribute value
a C a C
[Link]( el ) //adds at the start of node (inside)
Apn Apn
setAttribute( attr, value ) //to set the attribute value
[Link]( el ) //adds before the node (outside)
e ge
of white.
leg lle
Events are fired to notify code of "interesting changes" that may affect code execution.
ol Co
Insert the button as the first element inside the body tag.
a C a
Apn Apn
Mouse events (click, double click etc.)
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. Keyboard events (keypress, keyup, keydown)
Did you notice, how you overwrite the class name when you add a new one? Form events (submit etc.)
Solve this problem using classList.
Print event & many more
ge ge
[Link] = ( ) => {
lle lle
//handle here All event handlers have access to the Event Object's properties and methods.
Co Co
}
a a
Apn Apn
[Link] = (e) => {
example
//handle here
[Link] = ( ) => { }
[Link](“btn was clicked”);
}
[Link], [Link], [Link], [Link]
ge ge
when clicked again.
e e
[Link]( event, callback )
Coll Coll
a a
Apn Apn
[Link]( event, callback )
llege
Co
A javaScript object is an entity having state and behavior (properties and method).
a
ge Apn
JS objects have a special property called prototype.
lle
Co
We can set prototype using _ _ proto _ _
pna
A *If object & prototype have same method,
object’s method will be used.
Classes in JS Classes in JS
llege llege
o o
Constructor( ) method is : class MyClass {
C C
Class is a program-code template for creating objects.
a a
Apn Apn
automatically invoked by new constructor( ) { ... }
Those objects will have some state (variables) & some behaviour (functions) inside it.
initializes object myMethod( ) { ... }
class MyClass {
}
constructor( ) { ... }
myMethod( ) { ... }
llege llege
o o
inheritance is passing down properties & methods from parent class to child class. The super keyword is used to call the constructor of its parent class to access the parent's
a C a C
properties and methods.
Apn Apn
class Parent {
}
super( args ) // calls Parent‘s constructor
class Child extends Parent {
[Link]( args )
}
llege ge
try-catch
o
Qs. You are creating a website for your college. Create a class User with 2 properties, name &
a C olle
email. It also has a method called viewData( ) that allows user to view website data.
Apn C
try {
a
Apn
... normal code
ge
Synchronous
olle
async await >> promise chains >> callback hell Synchronous means the code runs in a particular sequence of instructions given in the program.
a C ge
Each instruction waits for the previous instruction to complete its execution.
Apn a Colle
Asynchronous
Apn
Due to synchronous programming, sometimes imp instructions get
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.
lege
A callback is a function passed as an argument to another function.
ege
l l
Callback Hell : Nested callbacks stacked below one another forming a pyramid structure.
Co Col
(Pyramid of Doom)
a a
Apn Apn
This style of programming becomes difficult to understand & manage.
Promises Promises
Promise is for “eventual” completion of task. It is an object in JS.
ge
A JavaScript Promise object can be:
ge le
It is a solution to callback hell.
le l
Pending : the result is undefined
Col a Co
Resolved : the result is a value (fulfilled) resolve( result )
a Apn
Apn
let promise = new Promise( (resolve, reject) => { .... } )
Rejected : the result is an error object reject( error )
Promises Async-Await
ege
l ge
.then( ) & .catch( ) async function always returns a promise.
Col lle
o
async function myFunc( ) { .... }
a C
[Link]( ( res ) => { .... } )
Apn Apn
a
[Link]( ( err ) ) => { .... } ) await pauses the execution of its surrounding async function until the promise is settled.
llege
o
IIFE is a function that is called immediately as soon as it is defined.
a C
Apn