JavaScript Tutorial
JavaScript Tutorial
console.log
console.error
console.warn
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));
console.log(str);
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
.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
Column2 Column3
<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]);
console.log(sel);
or
let sel = document.querySelector('#cont');
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
HTML COLLECTION
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
Gives character code of character at 5th position this will return UTF code
Concatenation
Make first letter to upper case Rakesh
tut47.html
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);
console.log(emp[0]);
console.log(emp[1]);
console.log(emp[2]);
console.log(emp[3]);
or
console.log(staff.length);
staff = staff.sort();
let employee = {
name: "rakesh",
empid: 94463,
job: "developer",
location: "hyderabad"
}
console.log(employee);
console.log(employee.job);
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"}
alert("this is a message");
prompt
confirm
will ask using prompt
another syntax:
emp.foreach(element=>console.log(element));
for loop
while
do while
for-in loop to access elements of object
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() {
function greet(name) {
function displayTime() {
document.getElementById('time').innerHTML =
time1;
let time2 = document.getElementById('time');
console.log(time2);
}
setInterval(displayTime, 1000);
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
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);
const materials = [
'Hydrogen',
'Helium',
'Lithium',
'Beryllium'
];
replacement of
function greet() {
console.log("Greeting from my
tutorial");
}
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'
];
const materials = [
'Hydrogen',
'Helium',
'Lithium',
'Beryllium'
];
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();
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
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=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
Array.from(a).foreach(element=>{con
sole.log(element)
access forms with index (if 4 forms are available in pa element.style.color='blue'}
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 arr2 = []
arr2 = (arr.filter((el, indx, array) => (el.className == 'container_')))
console.log(arr2)
Column2 Column3 Column4
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
}
sum += i
}
postMessage(sum)
}
})
https://www.javascripttutorial.net/javascript-regular-expression/
Quantifier Description
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
let ee =
('123123A313abcdsad'.match(regex))
console.log(ee == '123123A313abcdsad')