Introduction to JavaScript Basics
Introduction to JavaScript Basics
Javascript - Day 1
Agenda
▪ Javascript
HTML -> Markup Language which is the building block of any website
CSS -> Style sheets which is used to style any website.
Javascript
Drawback-
1994 started Netscape Corp and stated new project called Netscape Navigator.
Brendan Eich -> He was given the task to create a PL which would add dynamic
Capabilies to the browser.
Livescript is integrated with the browser. It would add the dynamic capabilities to
the browser.
1995 they released Browser Navigator beta version which included a PL called
Livescript
Previously Javascript was used only at the client side. Now we can use Javascript
on both Client side and Server side.
Agenda
▪ Javascript
[Link]("Hello World"); // Prints the data normally on to the console
[Link]("Debugging in progress"); //Prints the text in blue color
[Link]("This is a warning..."); // Prints the message in Yellow color
[Link]("This is an error"); //Prints the message in red color
[Link]("This is just an Information") ; //Exactly same as that of log
Javascript Comments
Syntax: //
Example:
Syntax
/* Your Content */
Example
Keyboard shortcut
Shift + Alt + A
'use strict';
When we declare a variable using const then it would act like a constant. Once the
value is assigned , then we cant modify that value.
Data types:
10 , 10.5432131, "Sachin"
yes/no (true/false) "C"
number -> In order to handle all the numeric values we can use number datatype.
By default All the numbers are floating points in Javascript.
boolean -> Yes/No of type of data falls under boolean category. In order to handle
yes/no (true/false) type of data we can use boolean
Example:
isCompleted = true;
undefined -> When the variable is declared but it is not defined then the datatype
will be undefined.
Example:
var firstName;
[Link](firstName);
In the above example firstName variable is declared but it is not assigned any
value. So its undefined.
Primitive datatypes are such datatypes which doesnt have any methods associated
with it.
To know what type of data is present in any variable we can use typeof operator.
syntax:
typeof <variable_name>;
Example:
Agenda
▪ Data Types
// Primitive Datatypes
number
string
boolean
null
undefined
Object type.
Ex:
name
age
gender
qualification
height
walk
run
cry
dance
swim
play
Syntax:
var object_name = {
key1: <value>,
key2: <value>,
.
.
.
.
.
keyN: <value>,
var person = {
name: "Sucheendra", age: 27, height: 5.11, gender: "Male", qualification: "BE",
}
For all the objects the memory will be allocated in the Heap Memory
1)
var person = {
name: "Sucheendra", age: 27, height: 5.11, gender: "Male", qualification: "BE",
}
2)
Example:
1)
[Link] = "Sucheendra"
2)
person['name'] = "Sucheendra"
Accessing JS Objects
==================
In order to access the JS Objects we can use dot(.) operator or we can use it as
shown below
[Link]([Link]) //Sucheendra
[Link](person['age']) //27
->
var person = {
name: "Sucheendra",
age: 27,
height: 5.11,
gender: "Male",
qualification: "BE",
dance: function() {
[Link]("Sucheendra is Dancing....!!!")
}
}
!!!!!Important !!!!!!
Syntax:
[Link](object_name)
Example:
var person = {
name: "Sucheendra",
age: 27,
height: 5.11,
gender: "Male",
qualification: "BE",
dance: function() {
[Link]("Sucheendra is Dancing....!!!")
}
}
Output:
!!!!!Important !!!!!!
From the JSON/JS Object just retrieve only the values...
output:
!!!
When ever we are trying to copy an object always the references gets copied. Not
entire object. In otherwords, Objects are Mutable in JS.
Front End Technologies
Javascript - Day 4
Agenda
▪ Data Types
NaN -> Not a Number
[Link]('ba'+(100/"s")+'a'); //banana
strings.
Example
String concatenation.
Whenever we are enclosing the string within single quote and the string also
contains the single quote then there will be an issue. To resolve that issue we use
escape characters.
Example:
var str = 'it's my computer';
[Link](str); //error
To fix the above error we must include the escape characters as shown below
Whenever we need to compare any strings we use the syntax as shown below..
We will be using (==) operator as shown below
Example:
var str1 = "Hello";
var str2 = "Hellow";
[Link](str1 == str2);
The above code will return false. Because we are using strict comparision. When
we use strict comparision it will not only check the data. rather it will also check
the type of data. So in our case the type of str1 is string and type of str2 is object.
since both of them are not same it return false.
1) charAt()
Whenever from a string if we need to extract a specific character we use charAt().
charAt() accpts a index as a parameter.
Example
var str = "HELLO WORLD";
[Link]([Link](4));
2) toLowerCase()
All the characters of the string will be converted to lowercases
Example:
var str = "HELLO WORLD";
[Link]([Link]()); //hello world
3) toUpperCase()
All the characters of the string will be converted to uppercases.
var str = "hello world";
[Link]([Link]()); // HELLO WORLD
!!!important
4) slice()
Whenever we want to extract a substring from a string we can use slice()
slice(begin_index);
slice(2) It always starts from index 2
Example:
Example-2:
Example-3:
slice(beginIndex, endIndex);
slice(2, 8);
If we use the above syntax then the extraction starts from the beginIndex and goes
till the endIndex and ignores the character present at the endIndex.
Output: llo Wo
5)substring()
Its almost similar to slice(). The difference between substring and slice() is
substring doesnt support -ve indexes.
Exmple:
var str = "Hello World";
[Link]([Link](-4)); //Hello World
6) replace()
When we want to replace a particular string with new string then we use replace
method().
Example:
var str = "Hello World";
[Link]([Link]("Hello", "Hi")); //Hi World
In case we have Multiple occurances of the same string, the replace method would
replace only the first occurance of the string with the new string..
Example:
To replace all the occurances with the new string we can't use replace() rather we
should use replaceAll().
Example:
7) trim()
Inorder to remove the whitespaces from the string we use the trim()
Example:
var str = " Hello World ";
[Link]([Link]()+" Hello"); //Hello World Hello
trim() will remove only the whitespaces before and after the string and it wont
remove the whitespaces present between the strings.
8)concat()
It is used to concat two strings.
Example
[Link]([Link](str2)); //HELLOWorld
Front End Technologies
Javascript - Day 5
Agenda
▪ Arrays
substring() vs substr()
substr(3)
Syntax2:
[Link](index, length);
Example2:
[Link]([Link](3, 4));
The above code will start at the index3 and extract the length number of characters.
In our case it will extract 4 characters.
So Output will be lo W
Arrays.
=========
Arrays are a kind of data structure where we can store multiple data. There is no
restriction about the data we are storing.
Example
var arr = [1,2,3,4,5];
[Link](arr) // [1,2,3,4,5]
In JS all the arrays declared are dynamic in nature. Ie as we keep on adding data ,
the size of the array keeps on growing.
Example:
var arr = [1, "Sachin", true, {}, 'c', [10, "Ramu", false],7777,"dakdah",true];
[Link]('First Way ',arr); // [1, 'Sachin', true, {…}, 'c', Array(3), 7777,
'dakdah', true]
var arr = [1, "Sachin", true, {}, 'c', [10, "Ramu", false],7777,"dakdah",true];
[Link](arr[5]) //[10, "Ramu", false]
1) push()
When we need to push any data to an array we use push method.. push() always
appends the data to the end of the array.
Example:
2) pop()
Whenever we need to remove an element from the array we use pop(). pop()
removes the element which is present at the last index of an array.
Example:
3) unshift()
When we need to push the data to the beginning of the array we use the unshift().
Example:
var arr = [10,"Sachin",true,null, 15.7655343421];
[Link]("Virat");
[Link](arr); // ["Virat",10,"Sachin",true,null, 15.7655343421];
4) shift();
Example:
var arr = ["Virat",10,"Sachin",true,null, 15.7655343421];
[Link]();
[Link](arr);
5) indexOf()
This method is used to get the index of a specific element present in an array. If the
element is present inside the array then its index will be returned. If the element is
not available inside the array then the indexOf() will return -1/
Example:
var arr = ["Virat",10,"Sachin", true, null, 15.7655343421];
[Link]([Link]("dahdlhakdlhkahldahldhladhla")) //-1
6) join()
Whenever we need to join all the elements inside the array join() should be used.
join() will join all the elements of an array and return it in the string format.
Example;
var arr = ["Virat",10,"Sachin", true, null, 15.7655343421];
[Link]([Link]());
join() by default will seperate the strings using comma. But if we want to change it
then we need to pass the character to join() as shown below.
[Link]([Link]('-')); //Virat-10-Sachin-true--15.7655343421
7) includes()
includes() checks whether the data passed to it is present inside the array or not. If
its present then it returns true else it returns false.
var arr = ["Virat",10,"Sachin", true, null, 15.7655343421];
[Link]([Link]('Sachin Ramesh... ')); //false
8) reverse()
In order to reverse an array we use reverse()
Example:
var arr = ["Virat",10,"Sachin", true, null, 15.7655343421];
[Link](arr);
[Link]([Link]());
9) slice()
var arr = ["Virat",10,"Sachin", true, null, 15.7655343421];
If we use the slice() it will not alter the original array. Rather it extracts the data
based on the indexes we pass.
slice(start,end);
extraction starts at the start index and ends at the end-1 index;
10) splice()
splice(start,length);
extraction starts at the start index extracts the length number of elements from the
array. In case of splice() it also alters the original array.
Example:
Agenda
▪ Arrays
Array Destructuring and Object Destructuring.
Example:
// OLD APPROACH
// var num1 = arr[0];
// var num2 = arr[1];
// var num3 = arr[2];
// var num4 = arr[3];
Destructuring Syntax
While destructuring an array we can unpack and assign the remaining part of the
elements to another variable using the rest parameter.
Example:
var arr = [10, 20, 30, 40, 50, 60, 70, 80, 90];
var [num1, num2, ...rest] = arr;
Example:
var student = {
firstName: "Sucheendra",
lastName: "Sachin"
}
Conditionals
1) if-else
2) switch
3) ternary
if-else
syntax:
if(some_condition) {
// conditions belonging to true
} else {
//conditions belonging to true
}
Example:
var firstName = "Sachin";
if([Link]("Virat")){
[Link]("First Name is ",firstName);
} else {
[Link]("First Name is Something else");
}
2) Switch
syntax
switch(condn) {
case:
//some statements
break;
}
Example:
switch(firstName) {
case "Sachin":
[Link]("My name is Sachin");
break;
case "Virat":
[Link]("My name is Virat");
break;
default:
[Link]("My name is something else");
break;
}
Ternary operator
Syntax:
Example:
Agenda
▪ Loops
loops
for loop
while loop
do while loop
for in loop
for of loop
loops are used to complete repeatative tasks easily. Instead of manually repeating
the tasks we must take advantage of loops.
for loop
Syntax:
Example:
Output:
Number 0
Number 1
Number 2
Number 3
Number 4
Number 5
Number 6
Number 7
Number 8
Number 9
While
Syntax:
while(condition) {
//Execute statements if true
}
while should be read as "AS LONG AS"
Example:
var counter = 0;
Output:
Counter value is 0
.
.
.
.
.
.
.
Counter value is 9
do while loop
syntax:
do {
//Execute the statements
} while(condition)
Example:
var counter = 0;
do {
[Link]("COUNTER VALUE IS "+counter);
counter++;
} while(counter < 10);
for in loop
Whenever we need to loop through the properties of an object we can use the for in
loop.
Syntax:
Example:
var student = {
name: "Sachin",
age: 27,
qualification: "Engineering",
location: "Bengaluru"
}
Output
Sachin
27
Engineering
Bengaluru
for of
Its used to iterate an array. Its very helpful while reading the arrays.
syntax:
Example:
//Output
10
20
30
40
50
60
[Link]
Front End Technologies
Javascript - Day 8
Agenda
▪ Functions
Functions.
Functions are block of code which are destined to perform a specific task.
Functions wont get automatically invoked unless and until we invoke it.
function function_name() {
Example:
function sayHello(){
[Link]("Hello");
}
Function Parameters/Inputs
addTwoNumbers(10, 20)
In the above example number1 and number2 are inputs/parameters
Anonomous Functions
Syntax:
Example:
sayHello() //HELLO
Arrow Functions
() => {
//Function Body
}
Arrow functions are added to ES6 (Ecma Script 6) //Latest version of JS.
sayHello()
forEach()
Syntax:
array_name.forEach(function(){
...
...
})
Example:
or
[Link](function(element){
[Link](element);
})
or
[Link]((element) => {
[Link](element);
})
Example
map()
map() creates a new array with the results of calling a function for every array
element.
Example:
1) Whenever we dont use the array it returns we shouldn't use the map(). Rather we
can use the forEach()
2) Whenever we are not returning anything from the callback function then no
need of using map().
callback() are such functions which gets called by the functions to which its
passed.
or
Agenda
▪ Functions
reduce()
Its used to reduce the array to one single value.
-> Reduce method is such a method which accepts a callback function as the
parameter(first Param)
-> (second param) Initial Value.
Syntax:
reduce(callbackFn, initial_value)
Example;
'use strict';
// Output
220
sort method
Example:
filter()
Example:
[Link](res); //[30,40,50]
try/catch/finally
Whenever we feel some part of code may cause problems, we must enclose the
part of code with in try. So if any problems occur try is designed in such a way that
it throws the exception object outside, which later will be caught by the catch().
By using try-catch syntax we can avoid our programs getting terminated abruptly.
Syntax:
try {
//Code
} catch(err){
//To catch the exceptions
}
finally
try {
//fetching
var num = 20;
firstName = "sachin"; //Exception
[Link]("NUM",num);
[Link](firstName);
} catch(err) {
[Link](err);
} finally {
//eliminate db connection here
[Link]("Finally Executed");
}
Output:
Agenda
▪ DOM
DOM -> Document object model.
[Link]()
It helps us write some text directly to the HTML Document.
Example:
O/P
1) alert popup
2) confirm popup
3) prompt popup
1) alert popup
Its used to alert the users regarding some change on the webpage.
Example:
2) confirm popup
confirm() will return true is OK button is clicked Ie the positive response. Else it
returns false I.e Negative Response
Example::
In our above example if ok is clicked, the confirm() will return true and "Thank
you. Your image is deleted from the database." will be displayed on the webpage
If cancel is clicked then "Thank you. Your image is not deleted from the database."
will be displayed on the webpage.
3) prompt popup
It allows users to enter the data and we can use the data entered by the users to
perform some operations.
Example:
innerHTML
Ex:
Agenda
▪ DOM
difference between textContent and innerHTML?
innerHTML -> If we have any HTML tags present while using innerHTML then
innerHTML property recognises the HTML Tags
Example:
//The output for the above syntax is "This is the division" and will be displayed in
italics
textContent -> textContent will not recognise any HTML tags. So textContent will
render the HTML Tags also as normal text.
Example:
//Output
getElementsByName()
Its used to find the elements on the webpage based on the name attribute.. It returns
NodeList . NodeList is nothing but an array of nodes or HTML Elements
Example:
Example:
In our above example it will search the webpage using the tag name input. If the
elements are found it will be returned in an array of type HTMLCollection.
getElementsByClassName()
Its used to find the elements using class attribute.
Example:
<p class="para"></p>
Styles
======
We can dynamically apply the css styling by using the style property as shown in
the below example:
<p id="para">
</p>
In order to append the dynamically created division to the webpage we can take the
help of appendChild() as shown in the below example:
[Link](paragraph)
Front End Technologies
Javascript - Day 13
Agenda
▪ Timers
Timers
setTimeout()
1)setInterval()
Example:
let sayHello = () => {
alert("Hello!!");
};
setTimeout(sayHello, 5000);
2) setInterval()
The main difference between the setTimeout() and setInterval() is that the
setTimeout() will execute the callback() only once. Whereas setInterval() keeps on
triggering the callback() regularly after the given interval of time (Unless you stop
it. )
Example:
let sayHello = () => {
[Link]("Hello");
}
setInterval(sayHello, 3000);
Every setInterval() will return one id. We need that id inorder to clear the interval.
Example:
setTimeout(() => {
clearInterval(timerId);
alert("Timer Stopped!!")
},9000)
Events
=======
click event
type event
onclick
<body id="body">
<button onclick="onButtonClick()">Click Here</button>
<script src="./[Link]"></script>
</body>
function onButtonClick(){
var body = [Link]("body");
var para = [Link]('p');
[Link] = "Hello Everyone. I am generated because you clicked on a
button!!"
[Link](para);
}
In our above example upon clicking on the button we will be dynamicaaly adding
the paragraphs
2) onchange
function onDropdownChange(e){
[Link]("Dropdown value changed",e);
}
event is the predefined object in jS where it contains all the information regarding
the current happening events. Example:
When we click on a button the event object will contain all the information related
to click event.
When we change the dropdown option the event object contains all the information
related to option change, .
Event Object looks like this.
{
bubbles: true,
cancelBubble: false,
cancelable: false,
composed: false,
currentTarget: null,
defaultPrevented: false,
eventPhase: 0,
isTrusted: true,
path: (5) [select, body#body, html, document, Window],
returnValue: true,
srcElement: select,
target: select,
timeStamp: 3245,
type: "change"
}
onkeydown
This event gets triggered when we type any key on the keyboard.
Example:
function keyPress(event){
[Link]("KEY PREssed",[Link]);
//API CALL [Link]
}
function mouseOver(event) {
[Link](event);
[Link]("box").[Link] = "red";
}
function mouseOut(event) {
[Link]("box").[Link] = "white";
}
Front End Technologies
Javascript - Day 14
Agenda
▪ Built-In Objects
Adding Events through Javascript
Example:
<button id="btn">Submit</button>
[Link]("btn").addEventListener('click',(event)=>{
alert("Button Clicked!!");
})
Example2:
[Link]("dropdown").addEventListener('change', (event)=>{
alert("The Value is "+[Link]);
})
1) Math
4) [Link]() Will help us to round the number passed to it to its nearest integer
value.
Example:
5) [Link]()
[Link](num) return the value of num rounded up to its nearest integer.
Ex:
var num = 4.4;
[Link]([Link](num));
6) [Link](num)
[Link](num) returns the value of num rounded down to its nearest integer.
Example:
var num = 4.9;
[Link]([Link](num));
7) [Link]()
[Link](num) will truncate the decimal and returns only the integer part of a
num
Example:
var num = 4.334802842084802;
[Link]([Link](num));
8) [Link]()
[Link](num) returns -1 if the num is negative and +1 if the num is positive. If
the num is 0 then it returns 0
Example:
var num = 0;
[Link]([Link](num)); //0
9) [Link]()
[Link]() is used to generate the Random Numbers.
10) [Link]()
Returns the Max number passed as an arguement
Exmple:
[Link]([Link](10, 12, 150, 9, 65, 43)); //150
11) [Link]()
Returns the Min Number passed as an arguement
Example
Agenda
▪ Date()
Date()
When ever we need to know about the date we should use Date Object.
Date Object gives information regarding Day, Month, Year, Minutes, Hours,
Seconds and Time Zone .
Example:
If the months that we are passing exceeds the limit, it actually moves to next year.
The same rule holds good for days as well
Example:
[Link](new Date(2020,13,30));
In our above example 2020 is the year. 13 is not a valid month. (0-11) are only
valid. so 13-11= 2 so add 2 months to the exisiting month. So it will become Feb.
30 is not a valid day in feb. so 30-maxDays = 30-28 =2. Add 2 days to existing
days.
Hence the below output
epoch time or unix time is the time in milliseconds since jan 1st 1970. Or number
of seconds elapsed since Jan1st 1970.
debugger keyword.
Agenda
▪ LocalStorage
LocalStorage
Its a feature available in the browser where we can store key value pairs to make
data persistant.
Max Storage supported is up to 10MB .
We can make the data persistant on the client side using localStorage.
Example:
<body id="body">
<label for="">First Name</label> <input type="text" id="firstName">
<button id="btn">Submit</button>
<br/>
<br/>
[Link]('firstName').addEventListener('keydown',(event) => {
firstName = [Link];
})
[Link]('btn').addEventListener('click',()=> {
[Link]('name',firstName);
[Link]('setFname').textContent =
[Link]('name');
})
[Link]
'use strict';
[Link]('click', () => {
var index = generateRandomNumber();
[Link] = colors[index];
[Link] = colors[index];
})
function generateRandomNumber(){
return [Link]([Link]() * len);
}
[Link]
main {
min-height: 100vh;
display: grid;
place-items: center;
}
.container {
text-align: center;
}
.container h2 {
background-color: #222;
color: #fff;
padding: 10px;
border-radius: 10px;
margin-bottom: 25px;
}
.btn-hero {
text-transform: uppercase;
background: transparent;
color: #222;
font-weight: 700;
border: 2px solid #222;
cursor: pointer;
border-radius: 10px;
padding: 8px;
}
.btn-hero:hover {
color: #fff;
background: #222;
}