JS Tutorial (Harry)
- JavaScript which is often known as JS, is a high-level dynamic interpreted programming language.
- It allows client-side scripting to create completely dynamic web applications and websites
- initially designed for making pages “alives”
- can be executed on the browser(client) ans well as the server
try out
Section titled “try out”Try these codes on console of Google Chrome.
Google Chrome -> right Click -> Inspect -> console.
alert("Hello world")console.log("Hello world")34+897931
Right click and Inspect HTML documents, and find some class let - “button1” and some Id let - “navbar1”
try (use dot before name for class)
Let Do some DOM Manipulatoin
-
document.querySelector(".button1") -
document.querySelector(".button1").click() -
document.getElementById("navbar1") -
document.getElementById("navbar1").click() > button1-
`button1.innerHTML =“Hello Harry”;
-
document.getElementsByTagName('h1') -
document.getElementsByTagName('h1')[0] -
document.getElementsByTagName('h1')[0].style.fontSize = "99px" -
document.getElementsByTagName('h1')[0].style.background = "red" -
document.getElementsByTagName('h1')[0].style.visibility = "hidden" -
document.getElementsByTagName('h1')[0].style.display = "none"
this is client side javascript
Website
Section titled “Website”HTML (Structure) + CSS(Design) + JavaScript(Client side Scripting) = WebPageHow website work
Section titled “How website work”Browser(Client) ---request---> Server
- request like (Get
www.google.com)
Browser(Client) <---response--- Server
- response like (HTML with CSS and JS embedded in it)
Website:
- Client Side -> only java script
- Server Side -> JavaScript(NodeJS), Python(Django) etc.
Lets work on .html file
Section titled “Lets work on .html file”Inline JavaScript
...<body> Hello World! </body><script> console.log("Hello World"); </script>...“Hellow World” is shown on browser->inspect->console
similarly, add these in html, and check what is shown on browser’s document, console etc
<script> alert("me") </script>
```html<script> document.write("I am writing") </script><script> console.warn("this is a warning")</script><script> console.error("this is an error")</script><script> console.assert(4==(6-2))</script><script> console.log("Hello World", 4+6,"Another log")</script>.js file
Section titled “.js file”External Java Script : add this line in .html
<script src ="index.js" > </script>now use index.js file seperately , the Javascript engine in browser will automaticlly embed it in html
Java Script Variables
Section titled “Java Script Variables”variables -> container to store data values
var num1 = 34;var num2 = 56;console.log(num1 + num2);No, var will not give an error if used inside a block like if, for.
Because var is function scoped, not block scoped — it gets hoisted to the function level.
Example:
if (true) { var x = 10;}console.log(x); // 10 ✅But:
function test() { if (true) { var x = 10; }}console.log(x); // ❌ ReferenceError (x not defined globally)So:
varis accessible outside block, but not outside functionlet/constare not accessible outside block
Variable without var, let and const
- In non-strict mode, JavaScript allows a variable to be assigned without
var,let, orconst, and it becomes a global variable (even if inside a function).
function test() { if (true) { x = 10; // x becomes global } } console.log(x);- It’s considered bad practice
- In strict mode (
'use strict';), it throws an error
Comments
Section titled “Comments”Comments -> for developers readability ,but to ignore by the compiler // -> single line comment
/* */ -> multi line comment
// single line comment/* Multi line comment */Data Types
Section titled “Data Types”In java Script , there are two types of Data Type,i.e Primitive data types & Reference data types
Primitive Data Types
number,string,boolean,undefined,null,symbol
// Numbervar num1 = 455;
// Stringvar str1 = "This is a string";
// Booleansvar a=true // or var a = 1var b=false //or var b= 2
// Undefinedvar und = undefined; // or simply not assign the value like -> var und;
// Nullvar n = null;
// Symbolsymbol('')// not much imprtant, leave itNote:
- in javascript, you can use, comma
,between objects during functions likeconsole.log(a,b)to separate print value by White space ( ) - Semicolon is important in JavaScript but Java Script is very forgiving language 🥹, it provide flexibilities such as not using
;,letetc ''and" "are the same in JavaScript for defining strings, but template literals` `allow for multi-line strings and string interpolation.
Reference Datatype
Array, Objects
//Arrayvar arr = [1,2,"doe",4,5]console.log(arr) // 0:1 1:2 3:"doe" 4:5console.log(arr[0]) //print 1Note:- Arrays (or lists) in Python and JavaScript can store different datatypes. Unlike arrays in C++ which can store a single data type.
// Objectsvar marks = { ravi: 34, shubham: 78, harry: 99.977} //try console.log(marks);Operators in JS
Section titled “Operators in JS”x @ y = z -> Statement// x, y -> operands// @ ->OperatorAssignment Operators
var b = 5var c// Assignment Operatorsc=bc+=bc-=bc*=bc/=bArithmetic Operators
var a = 100var b = 10// Arithmetic Operatorsa+b // 110a-b // 90a*b // 1000a/b // 10Comparison Operators
var x = 34var y = 56// Comparison Operatorsx == y // falsex < y // truex > y // falsex <= y // truex >=y // falseLogical Operators
&&-> for AND||-> for OR
true && true // truetrue && false // falsefalse && true // falsefalse && false // false
true || true // truetrue || false // truefalse || true // truefalse || false // false
!false // true!true // falseNote:- Unlike other languages like Python & C++, JavaScript does not support using words and or or directly. Instead, it uses && for logical AND and || for logical
Bitwise Operator
& and |
// 1:23:05 Functions
Functions
Section titled “Functions”- Works on DRY Principle
- DRY = Do not repeat yourself
- Reuse peace of code/logic
function avg(a,b){ return(a+b)/2 ;}avg(4,6) //call avg()Types of Functions in JavaScript:
- Anonymous Function
// Anonymous Function Expressionconst funcVar = function() { };
// Immediately Invoked Function Expression (IIFE)(function() {})();
// Callback ExamplesetTimeout(function() {}, time);
// Event Handler Exampledocument.getElementById("elementId").addEventListener("event", function() {});- Note: Anonymous functions do not have a name. They need to be assigned to a variable if you need to use them later, except when used as an IIFE or in contexts like callbacks and event handlers.
- Named Function (Assigning to variable is optional)
// Named Function Declarationfunction funcName() { }
// Named Function Expressionconst funcVar = function funcName() { };
// Named Function Expression with Immediate Invocation(function funcName() {})();- Note: Named function expressions can be used for recursion and debugging but are not hoisted.
- Arrow Function
// Arrow Functionconst funcName = () => { };
// Immediately Invoked Arrow Function(() => {})();- Note: Arrow functions have a concise syntax and capture the
thisvalue from their surrounding context. They also need to be wrapped in parentheses for immediate invocation.
Note : Call Back Function callback function is a function passed as an argument to another function, which is then executed after some operation has completed. It’s a general programming concept used to ensure that certain code is executed after a task finishes
Conditionals in JavaScript
Section titled “Conditionals in JavaScript”- single if statement : only if condition.
- if - else statement : both if and else condition
- if-else Ladder statement : if, series of else if ,and else conditons
var age = 21;// if-else Ladderif(age<18){ console.log('You are kid');else if(age>30){ console.log('you are youth')}else{ coonsole.log('you are man')}}for
var arr[1,2,3,4,5,6,7]
//for loopfor(var i =0;arr.length; i++){ console.log(arr[i])//1234567}for loop: best to iterate from a lower bound value to upper bound value
forEach
// for-Each loop ⭐arr.forEach(functions(element){ console.log(element)}) //1234567forEach loop : best to iterate over elements of sequence - array, string etc.
while
//while loopwhile(j<arr.length){ console.log(arr[j]); j++;} //1234567while loop : Iterate until a given condition is true
do-while
//do-while loop ⭐do{ console.log(arr[j]); j++;}while (j < arr.length);do while : best when we have to run a loop,at least one time.
Break and Continue;
Section titled “Break and Continue;”//breaks;for( var i = 0; i<10; i++){ if(i==4){ break; } console.log(i)} //123break: terminate loop based on condition
for( var i = 0; i<10; i++){ if(i==4){ continue; }} //1235678continue: skip loop’s execution for a condition
let var const ⭐
Section titled “let var const ⭐”var :
- Function-scoped
- hoisted & initialized with
undefined - Can be re-declared
let :
- Block-scoped (
{}) - hoisted but not initialized.
- Cannot be re-declared (only re-assign possible)
const : can’t updated once after initialisation
- neither be re-declared nor re-assigned
var alet bconst cNote: - Hoisted mean moving declarations to the top of their scope (either global or function scope) before the code execution begins.
This means that you can use variables and functions before they are formally declared in the code.
‘var’ is a old js standard, we should use ‘let’ and ‘const’ whenever possible possible, that make temporary variables in blocks, without appending the global one.
Methods in JavaScript
Section titled “Methods in JavaScript”Methods on array
let myArray = ["Fan", "Camera", 34, null, true ]
// Length of ArraymyArr.length
// Remove last elment from arraymyArr.pop() // ["Fan", "Camera", 34, null]
// Push an element to an IndexmyArr.push("harry")
// Remove first element from array ⭐myArr.shift()
// Add element to Starting ⭐myArr.unshift("Harry")
// Print arrayconsole.log(myArr) // ["Harry", "Camera", 34, null, "harry"]
// Print length of new array ⭐console.log(myArr.unshift("Gurav")) // 6
// Convert array to string ⭐myArr.toString() // "Harry,Fan,Camer,34,,true"
// Sort Array (in Dictionary Order) ⭐let d = [1,4,6,43,23,32324]d.sort() // [1, 23, 32324, 4, 43, 6]Note: javascript allow storing different datatypes in single array
String Methods in JS
let myLovelyString = "Gaurav is a good boy, Gaurav";
// Length of stringmyLovelyString.length // 20
// Starting index of substringmyLovelyString.indexOf("Gaurav") //0 (first matched index)
// Starting index of substringmyLovelyString.lastIndexOf("Gaurav") //23 (last matched index)
// Slicing in string (startIndex, size)myLovelyString.slice(0,3) // "Gau
// Replace first substring occurence in stringmyLovelyString.replace("Gaurav","Meena") //"Meena is a good boy, Gaurav"Date-Time Method in JS
// Datelet myDate = new Date(); // Mon July 01 2024 22:47:00 GMT+0530 (Indian Standard Time)
//moremyDate.getTime()myDate.getFullYear()myDate.getDay() //1 (sun = 0 to sat =6)myDate.getMinutes()myDate.getHours()Note: In JavaScript, the new keyword is used to create instances of objects that have a constructor function.
Note: JS Methods are generally in camelCase in format
Document Object Model (DOM)
Section titled “Document Object Model (DOM)”DOM - Everything inside body of browser is DOM document is used to access HTML page’s element and apply DOM manipulation
Get Element
Section titled “Get Element”document.getElementById('click').click() document.getElementById('click').style.border = '2px solid blue'
// Get HTML elment by Idlet elem = document.getElementById('click');console.log(elem)
// Get Collection of HTML elments by Class Namelet elemClass = document.getElementByClassName('container');
// Access elements elemClass and Style themelemClass[0].style.background = "yellow"
// Add a class in a element (class can be more than one, unlike Id )elemClass[0].classList.add("bg-primary")
// Remove a class of a elementelemClass[0].classList.remove("bg-primary")
// Get the Inner HTML of elementelemClass[0].innerHTMLelemClass.innerHTML
// Get only the Text Inside HTMLelemClass[0].innerTextelemClass.innerText
// Get collection of element by Tag Nametn = document.getElementsByTagName('button')console.log(tn)
document.getElementsByTagName('div`)Tired of typing getElementById , getElementByClassName type ‘gebi’, ‘gebcn’ as shortcut respectively in Vscode , explore more
Tag Name : tag names refer to the names of HTML elements used to structure and display content on a web page. Here’s an overview: <body>, <div>, <img>
getElementsByClassName,getElementsByTagName,getElementsByName= Elements (plural)getElementById= Element (Singular)
// Create a Element <p></p>createdElement = document.createElement('p');
// Add content/Text into elementcreatedElement.innerText = "This is a created para"
// place the element inside a elementtn[0].appendChild(createdElement);
createdElement2 = document.createElement('b')createdElement2.innerText = "This is a created bold"
// Replace Child - createdElement2 with CreateEllementtn[0].replaceChild(createdElment2,createdElement )
tn[0].removeChild(createdElment2)document.location- many information like href, hostname, origin, port etc document.title document.URL document.scripts // collection of JS scripts document.links document.images document.forms document.domain
Note: focus on singular plural words, in js it worked as they are written
Selecting using Query /CSS
Section titled “Selecting using Query /CSS”the querySelector and querySelectorAll methods provide a concise and powerful way to select elements using CSS selectors, demonstrating their flexibility and ease of use compared to traditional getElement methods.
check all by console.log(sel)// Select first element using Idsel = document.querySelector('.container')
// Select all element using Idsel = document.querySelectorAll('.container')Events in JS
Section titled “Events in JS”onclick
<!--Add function call in HTML Element Manually--><button id="click"> onclick="clicked()"> Click Me </button>//call function clicked() when onclick event occured
//function definitionfunction clicked(){ console.log('The button was clicked')}More events
mouseoveronmouseoutonload //when page is load
//exdocument.onload = function(){ console.log('The document was loaded') ❌ // should attach it on window object
window.onload = function(){ console.log('The document was loaded') }}// Add event on firstContainer class using js EventListenerfirstContainer.addEventListener('click',fucntion()){ //you can direct access html element like firstContainer here console.log("clicked on container")}you can add more events in place of ‘click’ like: mouseup : when mouse is released after click mousedown : when mouse is released after hold mouseover: when mouse go on an element mouseout : when mouse go out of an element
To change html element on click
let prevHTML = document.querySelectorAll(.container)[1].innerHTML;
//when clicked, change innerHTMLfirstContainer.addEventListener('click', function(){ document.querySelectorAll('.container'.)[1].innerHTML = "<b> we clicked </b>" console.log("Clicked on Container")})
//When released click, undo changesfirstContainer.addEventListener('mousedown', function(){ document.querySelectorAll('.container')[1].innerHTML = "<b> we had clicked </b>" console.log("Clicked on Container Released"))Arrow Functions
//normal functionfunction sum(a,b){ return a+b;}//arrow function (no 'function' keyword required)sum =(a,b)=>{return a+b;}
//arrow function is used when we have to insert function in betweensetTimeout and setInterval
Section titled “setTimeout and setInterval”logKaro = () => { document.querySelectorAll('.container')[1].innerHTML = "<b> Set Interval fired </b>" console.log("I am your log")}setTimeout: -> Schedule a function to execute after some millisecond of time
setTimeout(function, Time_in_ms)
// Execute logKaro() after 2 secondsetTimeout(logKaro, 2000); //2000 ms => 2 secondSet Interval -> repeatedly execute function after in fixed time interval
setInterval(function,time)
// Execute logKaro() after every 2 secondsetInterval(logkaro, 2000);// setTimeout return Id to 'timeoutId'timeoutId = setTimeout(logkaro, 2000);
// setInterval return Id to 'intervalId'intervalId = setInterval(logkaro, 2000);// pass the Id to cancel the setTimeoutclearTimeout(timeoutId)
// pass the Id to cancel the setIntervalclearInterval(intervalId)JavaScript local storage
Section titled “JavaScript local storage”// set local storagelocalStorage.setItem('name', 'gaurav')
// check local storagelocalStorage
// Clear local storagelocalStorage.clear()
// get value of Item on local storagelocalStorage.getItem('name') // 'gaurav'JavaScript Object Notation is a lightweight data-interchange format.
- Easy for humans to read/write
- Easy for machines to parse/generate
- Based on a subset of JavaScript (ECMA-262 3rd Edition - Dec 1999)
obj = {name: "harry", length: 1}jso = JSON.stringify(obj);console.log(jso) // {"name":"harry,"length":1}
// Type of datatypeof jso // "string"typeof obj // "object"obj2 = {name: "harry", length: 1, a:{this:"that"}}
jso = JSON.stringify(obj2);console.log(jso) // obj2 = {"name": "harry", "length": "1", a:{"this":"that"}}obj2 = {name: "harry", length: 1, a:{this:'tha"t'}} // valid JS object even after adding single quotes
jso = JSON.stringify(obj2);console.log(jso) // obj2 = {"name": "harry", "length": "1", a:{"this":"tha\"t"}}similarly it behaves
"tha\ "t" -> "tha \"t""tha\"t" -> "tha\"t""tha\\"t" -> "tha\\\"t"// Object to Json stringjso = JSON.stringify(obj)
// Json string to Objectparsed = JSON.parse(jso)
// Print the object in consoleconsole.log(parsed);
// direct json string to ObjectJSON.parse(`{"name": "harry", "length": "1", a:{"this":"that"}}`) // we can write string in backticks "`"- JSON as standard requires double quotes and will not accept single quotes. it convert
'tha"t'to"tha\"t". - it changes single quotes to double , and uses backslash so that to ignore 2nd ” as end of string.
ECMAScript
Section titled “ECMAScript”ECMAScript is a scripting language specification standardized by Ecma International.
It was created to standardize JavaScript and support multiple implementations.
- 1st – 5th Edition → JavaScript
- 6th – 10th Edition → ECMAScript (2015–2019)
ES6 = ECMAScript 2015 (6th Edition)
Introduced features like:
let,const- Arrow functions
- Template literals (
backticks) - Destructuring
- Classes, Modules
- Promises, etc.