0% found this document useful (0 votes)
40 views

JavaScript Tutorial

The document shows different ways to define and access objects and arrays in JavaScript including defining an object with properties, accessing properties of an array by index, creating an array with new Array(), accessing the length of an array, and using the push method to add an element to an array.

Uploaded by

rakesh ahuja
Copyright
© © All Rights Reserved
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

JavaScript Tutorial

The document shows different ways to define and access objects and arrays in JavaScript including defining an object with properties, accessing properties of an array by index, creating an array with new Array(), accessing the length of an array, and using the push method to add an element to an array.

Uploaded by

rakesh ahuja
Copyright
© © All Rights Reserved
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
You are on page 1/ 60

Column1 Column2 Column3

console.log
console.error
console.warn

console.time and console.timeEnd


console.assert(age>180,'Age can not be >180')
Column4 Column5

console.time('mytag')
……………………………
……………………………
…………………………...
console.timeEnd('mytag') Will show time taken in miliseconds
can not be >180')
Column1 Column2 Column3 Column4
String(45) number to String
let Bvar = String(true)
boolean to String
toString() function
const i=43;
console.log(i.toString()) toString() function
let Bvar = String(true)

let STR='345'
console.log(typeof STR)
let num = Number(STR)
console.log(typeof num)
Command
script
console.log()
var num1=2;
console.log(num1);
var num2=5;
console.log(num2);

var num1=2;
var num2=5;
console.log('sum of num1 and num2 is ' + (num1+num2));

var temp = `${num1} and ${num2} 'both' are "numbers"`


var string=" 'this is tutorial' "
var string=' "this is tutorial" '
var len= name.length;
console.log(`length of name is ${len}` );
\n
\t
\b
\v

var str = "this is outer block";


{

let str = "this is inner block";


console.log(str);
}

console.log(str);

const a = "this can not be changed";


console.log(a);

a = "let me try to change it";


console.log(a);

Data types
Primitive Data types
String
Number
Boolean
null
undefined
Symbol in ES6
Reference Data type
Object
Function
Array
Date
description short description
to start a script tag in html body or in html head
to see console in web browser

will print 2 in console

will print 5 in console

+' is used to concatenate strings

` is used to write a string with variables in a better


way
that can also include single quote and doube quote
altogether
use double quote when single quote to be printed
use single quote when double quote to be printed

.length
escape sequence character new line
escape sequence character horizontal tab
escape sequence character backspace
vertical tab

Output:
let is used instead of var for a variable of scope this is inner block
BLOCK this is outer block

TypeError: Assignment to constant variable


Also const should be ininitialised

But elements can be pushed in const type array,


constant but array can not be initialised again

Column2 Column3

data type of null is object Bogus data type


Column1 Column2
tut52

<div id="myid">

</div>
<script>
document.getElementById('myid').innerHTML = '<h3>
this is h3 heading</h3'
</script>
let mm = document.getElementById("contid");
console.log(mm);

let navb =
document.getElementById('navb').innerHTML;
console.log(navb);

let variable =
document.getElementsByClassName('container');
console.log(variable);
console.log(variable);
console.log(variable[0]);
console.log(variable[1]);

let sel = document.querySelector('.container');

console.log(sel);
or
let sel = document.querySelector('#cont');

console.log("selector return: ", sel);


let sel = document.querySelector('#navb>li');
console.log("selectror return ", sel);
let sel = document.querySelectorAll('#navb>li');
console.log("selectror return ", sel);

let sel = document.querySelectorAll('#navb>li');


console.log("selectror return ", sel[0]);
sel[0].innerHTML = "house"
Insert into element dynamically using JS
access an element by id

access element as HTML

access a class as array

access a selector
-> if class is accessed, it will return first occurance of
class in the document
-> if id is accessed , it will return exact id

First element of list of navb(id)

all element of satifying

replace sel[0] with "house "


used to update cart of page dynamically

used to send static information to cart

HTML COLLECTION

Home replaced with House


tut46.html
var string=" 'this is tutorial' "
var string=' "this is tutorial" '

var str= "this is a string"


position= str.indexOf('is');
console.log("position of is is" +position);
var n = str.lastIndexOf("is");
var sub_str = str.slice(3, 12);
console.log(sub_str);
console.log(str[3]);
var sub_str = str.substring(3, 12);
console.log(sub_str);
var sub_str = str.substr(3, 12);
console.log(sub_str);
str = str.replace('string', 'world');
console.log(str);
console.log(str.toUpperCase());
str1.concat(str2);

var str1 = " this text might contain white spaces at the start and end ";
console.log(str1);
var trimmed = str1.trim();
console.log(trimmed);
var poschar = str.charAt(5);
console.log(poschar);
var poscharcode = str.charCodeAt(5);
console.log(poscharcode);

let a = 'rakesh'
let b = 'ahuja'
console.log(a + " " + b)

*******************OR***************
console.log(a.concat(" ").concat(b))
*******************OR***************
let c = [a, b].join(" ");
Concatenat console.log(c)
console.log('rakesh'.charAt(0).toUpperCase() + 'rakesh'.slice(1))
use double quote when single quote to be printed
use single quote when double quote to be printed

this will return first subscript of occurance index starts from zero
this will return last subscript of occurance

Substring from a string from 3 to 12


charater at third position
from 3 to 12
Substring from a string slice and sbstring both work same

Substring from a string from 3 with length of 12

replace a substring from a string


to upper case
function to concatenate + can also be used'

removes white spaces from start and end

charater at fifth position

Gives character code of character at 5th position this will return UTF code

Concatenation
Make first letter to upper case Rakesh
tut47.html

let age = 34;


if (age > 50) console.log("you
can drink coffee")
else console.log("you can drink
milk ");

let age = 34;


if (age > 50) console.log("you
can drink coffee")
else if (age > 45)
console.log("you can drink tea ")
else if (age > 35)
console.log("you can drink cold drink
")
else console.log("you can drink
hot milk ");

const cups = 45;


switch (cups) {
case 40:
console.log("the vale of
cups is " + cups);

break;
case 45:
console.log("the vale of
cups is " + cups);

break;

default:
console.log("the vale of
cups is not aplicable");
break;
}
Conditional if-else

if else ladder

if break is not applied, then wahan ke baad ke sare cases execute ho jate hn
output:
you can drink milk

output:
you can drink milk
tut48.html

let employee = {

name: "rakesh",
empid: 94463,
job: "developer",
location: "hyderabad"
}
console.log(employee);

let emp = ["rakesh", 96643, "developer", "hyderbad"];


console.log(emp);

console.log(emp[0]);
console.log(emp[1]);
console.log(emp[2]);
console.log(emp[3]);

or

let staff = new Array("nisha", 96649, "HR", "hyderbad");


console.log(staff[0]);
console.log(staff[1]);
console.log(staff[2]);
console.log(staff[3]);
console.log(staff);

console.log(staff.length);
staff = staff.sort();

let staff1 = new Array("nisha", 96649, "zz", "hyderbad");


staff1.push("4rating");
console.log(staff1);

let employee = {

name: "rakesh",
empid: 94463,
job: "developer",
location: "hyderabad"
}
console.log(employee);
console.log(employee.job);

let emp = new Array(12);


{ let emp = new Array(11);
console.log(emp);

emp[0] = "rakesh"; emp[1] = "rakesh1"; emp[2] =


"rakesh2"; emp[3] = "rakesh3"; emp[4] = "rakesh4";
emp[5] = "rakesh5"; emp[6] = "rakesh6"; emp[7] =
"rakesh7"; emp[8] = "rakesh8"; emp[9] = "rakesh9";
emp[10] = "rakesh10";

let greettext = "good morning"


console.log(emp);
for (let index = 0; index < emp.length; index++)
{
let element = emp[index];
let string_return = names(element, greettext);
console.log(string_return);
}
function names(ele,greettext="default value if no value is
paased")
{
let string_return = greettext + " " + ele + ", " + ele + "is a
good boy"
return string_return;
}
}

a=document.all
Array.from(a).forEach(function(element){
console.log(element)
})
object

ARRAY
gives length of array
sorts the array in inself

output:
push a value to the end of array {"nisha", 96649, "zz", "hyderbad", "4rating"}

{name: "rakesh", empid: 94463, job: "developer",


location: "hyderabad"}
access value of key from object developer
make an empty array of 12 elements [empty × 12]
create an array with the help of 'a'
tut50

alert("this is a message");

let name = prompt("wt is ur name",


"GUEST");
console.log(name);
confirm
let a = prompt("what is your name")
a = confirm("Are you sure you want to
delete")
alert

prompt
confirm
will ask using prompt

this will assign a boolean to 'a'


tut51
//forin loop for object
for (yyy in emp) {
console.log("hello " + emp[yyy]);
}

// forof loop for array


for (xxx of emp) {
console.log("bye " + xxx);
}

//forrach loop to access elements of array


emp.forEach(function funname(element) {

console.log("hello friend " + element);


})

another syntax:

emp.foreach(element=>console.log(element));
for loop
while
do while
for-in loop to access elements of object

for-of loop to access elements of array

forrach loop to access elements of array


for loop
while
do while
tut53

<!-- List of events -->


<!-- click

contextmenu for righ click of mouse


contextmenu

mousehover/mouseout
mousedown/mouseup
mousemove

submit
focus

DOMContentLoaded

transistionend

-->
para.addEventListener('mouseout', function error() {

console.log("mouse outside");

}
OR
para.addEventListener('mouseout', (e) => {
console.log("out")
console.log(e)
})
tut54

Column1

setTimeout(greet, 5000);

function greet() {

console.log("helllo my dear !!!");

setTimeout(greet, 5000, "RAKESH");

function greet(name) {

console.log("helllo my dear ", name);

setTimeout(greet, 5000, "RAKESH", "good Bye");

function greet(name, msg) {

console.log("helllo my dear ", name, msg);

timeout = setTimeout(greet, 5000, "RAKESH",


"good Bye");
console.log(timeout);

setInterval(greet, 4000, "RAKESH", "good night");

let newdate1 = Date.now();


Column2 Column3

greet function will be called with delay


of 5000 ms

In settimeout write name of function without


paranthesis

greet function will be called with delay


of 5000 ms
and argument passing

Same as above and with multiple


arguments

clearTimeout(timeout_id) Here timeout_id is the id given by timeout

example:If a user is to be asked for signup


after 20 seconds using setTimeout
and he signs-up before that then
clearTimeout to be executed
Repeats the function in every 4seconds

shows a time stamp (in milisecond)


starting from 1970
tut55
Column1

console.log("This id date & Time");


let now = new Date();
console.log(now);

console.log("This id date & Time");


let dt = new Date(0);
console.log(dt);

let dt2 = new Date(5000);


console.log(dt2);

function displayTime() {

time1 = new Date();

document.getElementById('time').innerHTML =
time1;
let time2 = document.getElementById('time');
console.log(time2);
}

setInterval(displayTime, 1000);

let dt3 = new Date("2029-09-25");


console.log(dt3);

let dt4 = newdate.getDate();


let dt5 = newdate.getFullYear();
let dt6 = newdate.getMonth();
let dt7 = newdate.getDay();
let dt8 = newdate.getMinutes();
let dt9 = newdate.getHours();

console.log(dt4);
console.log(dt5);
console.log(dt6);
console.log(dt7);
console.log(dt8);
console.log(dt9);
newdate.setDate(12);
console.log(newdate);
Column2 Column3

Shows current Date and Time

Thu Jan 01 1970 05:30:00


GMT+0530 (India Standard
Time) Refrence Date

Thu Jan 01 1970 05:30:05


GMT+0530 (India Standard
Time) 5 second aage ka time from 1970 wala time

display Time using will also update time on screen as well as


setintervalTime
at console
every second

Tue Sep 25 2029 05:30:00


GMT+0530 (India Standard Get Future Date
Time)

In details
used to update the date
tut56
Column1

greet = () => {
console.log("Greeting from my tutorial");

}
greet();

setTimeout(() => {
console.log("we are in settime out");
}, 5000);

let sum= (a,b)=>{


return a+b;
}
let x = sum(4, 5);
console.log(x);

sum = (c, d) => (c + d);


let x = sum(4, 5);
console.log(x);

let half = a => a / 2;


let y = half(46);
console.log(y);
let greet = () => console.log("greetings");
greet();

const materials = [
'Hydrogen',
'Helium',
'Lithium',
'Beryllium'
];

console.log(materials.map(material => material.length));


Column2 Column3

replacement of

function greet() {

console.log("Greeting from my
tutorial");
}

Arrow Function shortcut

Another Shortcut using arrow function

// expected output: Array [8, 6, 7, 9]


var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " +
this.lastName;
}
};

var person = {
firstName : "John",
lastName : "Doe",
id : 5566,
myFunction : function() {
return this;
}
};

let x = this
Here this returns global window
tut57
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

The map() method creates a new array with the results of calling a function for every array element.
Column1

const materials = [
'Hydrogen',
'Helium',
'Lithium',
'Beryllium'
];

console.log(materials.map(material => material.length));

const materials = [
'Hydrogen',
'Helium',
'Lithium',
'Beryllium'
];

console.log(materials.map(material => material[2]));

var numbers = [4, 9, 16, 25];


var x = numbers.map(Math.sqrt)
document.getElementById("demo").innerHTML = x;

var numbers = [65, 44, 12, 4];


var newarray = numbers.map(myFunction)

function myFunction(num) {
return num * 10;
}

console.log(newarray);
var persons = [
{firstname : "Malcom", lastname: "Reynolds"},
{firstname : "Kaylee", lastname: "Frye"},
{firstname : "Jayne", lastname: "Cobb"}
];

function getFullName(item) {
var fullname = [item.firstname,item.lastname].join(" ");
return fullname;
}

function myFunction() {
document.getElementById("demo").innerHTML = persons.map(getFullName);
}
myFunction();

let contacts = new Map()


contacts.set('Jessie', {phone: "213-555-1234", address: "123 N 1st Ave"})
contacts.has('Jessie') // true
contacts.get('Hilary') // undefined
contacts.set('Hilary', {phone: "617-555-4321", address: "321 S 2nd St"})
contacts.get('Jessie') // {phone: "213-555-1234", address: "123 N 1st Ave"}
contacts.delete('Raymond') // false
contacts.delete('Jessie') // true
console.log(contacts.size) // 1
_Objects/Map

of calling a function for every array element.


Column2

returns length of each array element


[
8,
6,
7,
9
]

return second character of each array element

"y", "e", "i", "e"

2,3,4,5

Output:
(4) [650, 440, 120, 40]
Malcom Reynolds,Kaylee Frye,Jayne Cobb
let mvar = Math;
console.log(mvar);
Math.round(3.6)
Math.pow(8,2)
Math.sqrt(36)
Math.ceil(5.7)
Math.floor(5.7)
Math.abs(5.666)
Math.abs(-5.666)
Math.sin(Math.pi/2)
Math.min(4,5,6)
Math.max(4,5,6)
Math.random()

let a = 5;
let b = 100;
let r = a + (b - a) *
Math.random();
console.log(r);
4
64
6
6
5
5.666
5.666
1 radian input
4
6
Generating a random number between 0 and 1

randomw number between 5 and 100


tut59

let jsnobj = {

name: "RAKESH",
favfood: "PANEER",
Wife: "Nisha"

}
console.log(jsnobj);
let myjsnstr = JSON.stringify(jsnobj)
console.log(myjsnstr);
myjsnstr = myjsnstr.replace("RAKESH",
"rakesh");
console.log(myjsnstr);

newJSONObj = JSON.parse(myjsnstr);
console.log(newJSONObj);
Purpose of JSON is to convert in to a STRING,
and STRING handeling is easy, then parse it back
Window Column2
let a = window.document This wil show attributes of document
console.log(a)
a = window.innerHeight
Shows height of window
console.log(a)
a = window.innerWidth
Shows width of window
console.log(a)
a=window.scrollX shows x cordinate of horizontal scroll bar
console.log(a)

a=window.scrollY
shows Y cordinate of horizontal scroll bar
console.log(a)

a=window.location
Shows location
console.log(a)

a=window.location.reload
console.log(a) Reloads the page

a=window.location.href
shows URL
console.log(a)

location.href
="https://codewithharry.com" redirects to codewithharry.com

a = window.location.toString() shows location in string form


history.go(-1) Goes back (as back button)

history.go(-2) Goes back to back (2 pages back)


scrollBy()
It will scroll the document by the specified
number of pixels
It will scroll the document to the specified
scrollTo()
coordinates
https://developer.mozilla.org/en-US/docs/Web/API/Document
DOM
a=document
console.log(a)
a=document.all
console.log(a)

a=document.body

a=document.forms

<form name="login">
<input name="email" type="email">
<input name="password" type="password">
<button type="submit">Log in</button>
</form>

<script>
var loginForm = document.forms.login; // Or document.forms['login']
loginForm.elements.email.placeholder = '[email protected]';
loginForm.elements.password.placeholder = 'password';
</script>

a=document.forms[0]
a=document.forms[1]
a=document.forms[2]
a=document.forms[3]
a=document.link
console.log(a)

a=document.link[0]
a=document.link[1]
a=document.link[2]
console.log(a)

document.images
document.script
var a = document.images.length;
var a = document.images[0].src;

var x = document.images.namedItem("myImg").src;
var x = document.images;
var txt = "";
var i;
for (i = 0; i < x.length; i++) {
txt = txt + x[i].src + "<br>";
}
Description Column1

DOM

HTML collection

Shows body

will show all the forms if available (HTML collecton)

Array.from(a).foreach(element=>{con
sole.log(element)
access forms with index (if 4 forms are available in pa element.style.color='blue'}

access links using index

Access all the images

Shows number of images


Get the URL of the first <img> element (index 0) in
the document:
Get the URL of the <img> element with id="myImg"
in the document:
Loop through all <img> elements in the
document, and output the URL (src) of
each image:
Column2

For loop can be used to access HTML


collection
but foreach can not be used.
container is parent
Column1

let cont= document.queryselector(.child)


console.log(cont)
cont= document.queryselector(.container)
console.log(cont.childNodes)
console.log(cont.children)

container=document.queryselector('div.container')
console.log(container.children[1].children[0].children)
console.log(container.firstchild)
console.log(container.firstelementchild)
console.log(container.lastchild)
console.log(container.lastelementchild)
console.log(container.childelementcount)
console.log(container.firstelementchild.nextElementsibling)

var mydiv = document.querySelector('.divcontainer')

var arr = Array.from(mydiv.children)

var arr2 = []
arr2 = (arr.filter((el, indx, array) => (el.className == 'container_')))

console.log(arr2)
Column2 Column3 Column4

cont.childNodes gives next-line and comments as well.


gives only tags

gives children in heirarchy


TEXT
H1

counts number of elelemtns of parent


Gives next sibling

convert node to array to iterate it.


Column1

function set(uname, val, expires) {


const d = new Date();
d.setTime(d.getTime() + expires * 24 * 60 * 60 * 1000)
let expirey = "expires=" + d.toUTCString();
document.cookie = `${uname}="${val}";${expirey}` }
function get(uname) {
let ename = uname + '='
const arr = document.cookie.split(";")
for (let i = 0; i < arr.length; i++) {
let element = arr[i];
if (element.charAt(0) == ' ') element = element.substr(1)
if (element.indexOf(ename) == element.lastIndexOf(ename)) return
element;
}
}
set('name', 'rakesh', 5)
set('name1', 'nisha', 7)
console.log(get('name'))
Service Worker
INDEX.js

if ('serviceWorker' in navigator) {
const webworker = new Worker('./worker.js')
webworker.postMessage('Hello Lets start worker')
webworker.onmessage = (e) =>
document.getElementById('secondDiv').innerText = e.data
}

onmessage = (event => {


if (event.data == 'Hello Lets start worker') {
let sum = 0
for (let i = 0; i <= 10000000000; i++) {

sum += i
}

postMessage(sum)
}
})
https://www.javascripttutorial.net/javascript-regular-expression/

Quantifier Description

n+ Matches any string that contains at least


one n
n* Matches any string that contains zero or
more occurrences of n
n? Matches any string that contains zero or
one occurrences of n
n{X} Matches any string that contains a
sequence of X n's
n{X,Y} Matches any string that contains a
sequence of X to Y n's
n{X,} Matches any string that contains a
sequence of at least X n's
n$ Matches any string with n at the end of it

^n Matches any string with n at the beginning


of it
m(?=n) Matches any string that is followed by a
specific string n
m(?!n) Matches any string that is not followed by
a specific string n

/(?=.{8,})/g atleast 8 character

/(?=.[A-Z]/g var regex = /(?=.[A-Z])/g;

check atleasst one Capital letter console.log('mynamei@srakeAshrake@shahBujaakesh'.match(regex).length)

let yy = /[^a-zA-Z0-9\s]/g
zz = ('rajrja%^*(*(**()))'.replace(yy, ''))
console.log(zz) remove non -alpha numeric values

let kk = /\/\/.*/gmi
let mystr = `<h1>hello</h1>
//commentLine1
<p>this is paragraph</p>
// commentLine2
console.log(mystr.replace(kk, '')) remove // comment lines from the code

var regex = /^(?=.{8,32}$)([A-Za-z0-9]*[A-Z]


([A-Za-z0-9])*)/gim

let ee =
('123123A313abcdsad'.match(regex))
console.log(ee == '123123A313abcdsad')

var regex = new RegExp('\n')

mystr = `mynameis rakesh


how are you
what is your name`

console.log(mystr.match(regex, 'g')) search for \n

You might also like