0% found this document useful (0 votes)
13 views15 pages

JavaScript Basics: Variables, Functions, and Loops

The document provides an overview of JavaScript (JS), a programming language used for web development, and includes instructions for setting up Visual Studio Code. It covers fundamental concepts such as variables, data types, operators, conditional statements, loops, functions, and DOM manipulation. Additionally, it includes practice exercises to reinforce learning and understanding of JS syntax and functionality.

Uploaded by

sharma79822
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)
13 views15 pages

JavaScript Basics: Variables, Functions, and Loops

The document provides an overview of JavaScript (JS), a programming language used for web development, and includes instructions for setting up Visual Studio Code. It covers fundamental concepts such as variables, data types, operators, conditional statements, loops, functions, and DOM manipulation. Additionally, it includes practice exercises to reinforce learning and understanding of JS syntax and functionality.

Uploaded by

sharma79822
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?

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

Our 1st JS Code Variables in JS


[Link] is used to log (print) a message to the console Variables are containers for data

lege lege
Col Col
a a
Apn
[Link](“Apna College”);

Apn
radius

14

memory

Variable Rules let, const & var

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

Let‘s Practice Let‘s Practice


Qs1. Create a const object called “product” to store information shown in the picture. Qs2. Create a const object called “profile” to store information shown in the picture.

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

Apn >, >=, <, <= Apn

Operators in JS Conditional Statements


To implement some condition in the code
Logical Operators

ge ge
if Statement

e e
&&

ll ll
Logical AND

a Co a Co
Apn Apn
Logical OR ||

Logical NOT !

Conditional Statements Conditional Statements


if-else Statement else-if Statement

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

Let‘s Practice Let‘s Practice


Qs1. Get user to input a number using prompt(“Enter a number:”). Check if the number is Qs2. Write a code which can give grades to students according to their scores:
a multiple of 5 or not. 80-100, A

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

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

[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) {

//do some work //do some work

} }

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

[Link] To create strings by doing substitution of placeholders

`string text ${expression} string text`


String Indices

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

String Methods in JS String Methods in JS


These are built-in functions to manipulate a string

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 )

Let‘s Practice Arrays in JS


Collections of items
Qs1. Prompt the user to enter their full name. Generate a username for them based on the input.

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 ];

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


Arrays in JS Looping over an Array
Print all elements of an array

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

Let‘s Practice Let‘s Practice


Qs. For a given array with marks of students -> [85, 97, 44, 37, 76, 60] Qs. For a given array with prices of 5 items -> [250, 645, 300, 900, 50]

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

toString( ) : converts array to string


shift( ) : delete from start & return
Arrays in JS Let‘s Practice
Qs. Create an array to store companies -> “Bloomberg”, “Microsoft”, “Uber”, “Google”, “IBM”, “Netflix”

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

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


c. Add Amazon at the end
splice( startIdx, delCount, newEl1... )

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
}

Ap function functionName( param1, param2 ...) {

//do some work

Arrow Functions Let‘s Practice

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.

const sum = ( a, b ) => {

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);

})

Some More Array Methods Some More Array Methods


Map Filter

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 ) => {

return val % 2 === 0;


let newArr = [Link]( ( val ) => {
})
return val * 2;

})

Some More Array Methods Let‘s Practice

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>

What is DOM? DOM Manipulation

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”)

Selecting with tag

[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

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


[Link](“#myId / .myClass / tag”)
//returns a NodeList textContent : returns textual content even for hidden elements

Homework Let‘s Practice


Qs. Create a H2 heading element with text - “Hello JavaScript”. Append “from Apna College

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.

DOM Manipulation DOM Manipulation


Attributes Insert Elements let el = [Link](“div“)

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)

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

[Link] Delete Element

[Link]( ) //removes the node


Let‘s Practice Events in JS
Qs. Create a new button element. Give it a text “click me”, background color of red & text color The change in the state of an object is known as an Event

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

Event Handling in JS Event Object


It is a special object that has details about the event.

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]

Event Listeners Let‘s Practice


Qs. Create a toggle button that changes the screen to dark-mode when clicked & light-mode

ge ge
when clicked again.

e e
[Link]( event, callback )

Coll Coll
a a
Apn Apn
[Link]( event, callback )

*Note : the callback reference should be same to remove


Classes & Objects Prototypes in JS

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( ) { ... }

let myObj = new MyClass( ) ;

Inheritance in JS super Keyword

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 )
}

*If Child & Parent have same method, child’s


method will be used. [Method Overriding]
Let‘s Practice Error Handling

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

} catch ( err ) { //err is error object


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. ... handling error

What this chapter is about? Sync in JS

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.

Callbacks Callback Hell

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 )

Function with 2 handlers

*Promise has state (pending, fulfilled) & some


*resolve & reject are callbacks provided by JS
result (result for resolve & error for reject).

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.

IIFE : Immediately Invoked Function Expression

llege
o
IIFE is a function that is called immediately as soon as it is defined.

a C
Apn

You might also like