//ASYNC vs DEFER loading of javascript in HTML file

//HTML is parsed from top to down and if it sees an image tag it starts dowloading but it does not stop parsing HTMl and whenever the image is dowmloaded it is shown on the webPage.
//But when a javascript is to be executed or a <script> </script> tag comes while parsing the HTML then normallly HTML stops parsing any other thing and firstly starts downloading that script after that it executes the script and then the rest of html file is parsed.
//If we use "async" then <script> is downloaded simultaniously while parsing the html but once the script is downloaded html parser stops and the downloaded script is executed and after its execution the rest of the HTML file is parsed.
//If we use "defer" then <script> is downloaded simultaniously while parsing HTML file but even if it is downloaded it will not execute till the complete HTML file is parsed and after that our downloaded script will start executing. All the scripts  are executed in order in which they are declared in HTML file if we use defer for all the filles.
// EX - <script async src = "logging.js"></script
      // <script defer src = "logging.js"></script>
//It is always recommended to use "defer" while defining script in the <head> of the HTML. It is the fastest way to download the scripts and execute them once our whole HTML file is parsed.
//Never use "async" loading and if you want to use normal loading then add the script tag at the last of your <body> tag.



// Window Object
//The window object represents an open window in a browser.
// The window object is an global object for the entire browser.
// When we do console.log(), it is basically window.console.log() because console is part of window.
// When we say alert("hi") it is same as window.alert("Hi") because javascript understand via javascript engine when you are in browser it automatically adds window. in front of alert()
// The only time we need to say window.alert() or window.console.log() is when we already have a variable named alert so that javascript can differentiate between these two
//We have different event listeners and other porperties of our window object for any event occured in our window tab

// EX-> window.addEventListener('resize', ()=> {  by this whenever out browser window will be resized it will call this callback() function and console "resized", Even if we don't use window. and simply define addEventListener() function.
//   console.log('resized');
// })




//Document object
// When an HTML document is loaded into a web browser, it becomes a document object.
// The document object is the root node  of the HTML document. It can be accessed using window.document or just document as it is also a property of window object.
// This is the way we interact with our HTML. We can modify elements, delete elements and even add elements in our HTML using this document object.

// const element = document.createElement("div") Here we created an element using document object
// element.innerText = "Hello world" // here we entered a text in that element
// document.body.appendChild(element)  //here we added our element in the body of our html document.


//ID and Class Selector
//We can select or access any element of our HTML file using two functions-> document.getElementById("id-name"), document.getElementsByClassName("class-name"). With these functions we will get a complete element with that id and HTML collection  with that class name
//EX- const idElement = document.getElementByiD("ID-name")
//    const classElement = document.getElementByClassName("class-name")
//We can always edit these elements like
//EX- idElement.style.color = red
//    const classArray = Array.from(classElement) // here we are converting an HTML collection to an array so that we can iterate over each element in tat collection
//    classArray.forEach(ele => ele.style.color = "blue") // as we get an array of elements by using getElementsByClassName function so to style it we will have to iterate over all the elements in our array
//    If we only want to style one element of the HTML collection then we can access it in the same way as we do in case of array -> classElement[0].style.color = "green"
//Id in an HTML page is always unique


//Query Selector
//Other than the id or class selector we can access HTML elements using two more function i.e -> document.querySelector('slector-name') this returns first element with this query and other one is document.querySelectorAll('') , this returns an array of all the HTML elements with this query
//EX - const dataTestElement = document.querySelector('.class-name') // we use a '.' in front of class name while inserting it in the query
//     const dataTestElementArr = document.querySelectorAll('.class-name') // this will return a node-list of all the element which is like an array but some of the array functions are missing
//     const arr1 = document.querySelectorAll('input') // this will return all the input elements in our HTML file
//     const arr2 = document.querySelectorAll('input[type="text"]')// this will return all the input elements that have type as text
//     const arr3 = document.querySelectorAll('body > input[type="text"]') // this will select all the input elemens of type text that are directly inside the body
       

//Event Listeners
//We can add event-listeners to any of our HTML element using a function -> addEventListener(). This function will execute a callback() function when an event specified inside addEventListener() function is performed on that HTML element to which we applied addEventListener function.
//EX- const btn = document.querySelector("[data-btn]") //accessing the element from HTML file having custom attribute as -> "data-btn"
      // btn.addEventListener('click', ()=> {     //first argument is name of the event and second is the callback function that will execute every time this event occurs to this HTML element
      //   console.log("clicked")
      // })
//We can add multiple event-listeners of same name or different name to the same HTML element and JS will NOT over-write any of them it is going to execute all of them
      // btn.addEventListener('click', ()=> {
      //   console.log('clicked2')
      // })
      // btn.addEventListener('mouseover', ()=> {
      //   console.log('mouse is on the button')
      // })
//We can add event-listeners to our window object as well
// EX- window.addEventListener('resize', ()=> {
//   console.log('browser window is resized')
// })
//We can remove an event-listener from our HTML element as well
// EX- btn.removEventListener('click', here if we again write the exact same print function it will not work as they both are defined at different places so we need to create a named function and use it while adding an event-listener and removing an event-listener)
//     btn.removEventListener('click', ()=> { //this will not work as callback functions are anonymous as they are defined in different places so we need to first create a known function and then use it at both the places
//       console.log('clicked')
//     })
//     function printClicked(){
//       console.log('clicked')
//     }
//     btn.addEventListener('click', printClicked)
//     btn.removEventListener('click', printClicked) // this will work as we are using the same function "printClicked" in both the cases for same HRML element using same event-listener
//Every time we use addEventListener() function it provides us an event-obj which we can use in its callback function.
//This event-obj has complete information about that event.We can access the date/information in that obj 
// EX- const input = document.querySelector("[data-inp-text]")//this is giving us an input element of out HTML file 
//     input.addEventListener('input',(eventObj)=> {
//       console.log(eventObj.target.value) //this will print the value of input every time we enter an character
//     })
//We can also prevent our event from performing it's default function by using preventDefault function inside the callback function of addEventListener 
// EX- const form = document.querySelector("[data-form]") //this will give us our form element from our HTML file
//     form.addEventListener('submit', (eventObj)=> {
//       eventObj.preventDefault()
//       console.log('now this form will not submit the data where-ever it was supposed to submit as we prevented the default function of this form')
//     })


//Difference between Arrow function and normal function
//If we use "this" inside a normal callback function then it refers to the scope in which the normal function is called.
//But if we use "this" inside an arrow callback function then it refers to the scope where the outer function of arrow callback function is defined
// EX- const btn = document.querySelector("[data-btn]")//accessing the button element from our HTML file
//     btn.addEventListener('click', (e)=> {
//       console.log('arrow function', this) //this will print the window object as "this" is in arrow function is which is a callback function of addEventListener() which is defined globallly. So "this" will be equal to window object as if we use "this" globallly it is equal to window object
//     })
//     btn.addEventListener('click', function (e){ 
//       console.log('normal function', this) // this will print our button element/obj of our HTML file as we are using "this" inside of the normal function which is a callback of addEventListener so the scope of "this" will be limited to where the normal function is called.
//     })
//It is always recommended to use arrow function and if we want to access the eventObj then we can use "this" is normal function as eventObj and "this" in the case of normal function will be equal and in case of arrow function "this" will be equal to arrow function


//Data Attributes
// As we know that we can make our own custom Attributes for our HTML elements using "data-".Now we will see how to use them in javascript
// EX- in HTML-> <div data-test="1234" data-test-two="3">this is an example div</div>
//     in javascript-> 
//               const test = document.querySelector("[data-test]")
//               console.log(test.dataset); //this will give an object of all our custom attributes as key and their value as value of key and if our data-attribute's name is data-test-two then we will get it as testTwo in our test variable when we get it using querySelector as in javascript we can not have variable having '-' between them.
//               console.log(test.dataset.testTwo) //this will print 3 as our data-test-two has a value 3 in it
//               test.dataset.testTwo = "1111" // we can also set the value of these data-attributes using javascript
              
              
//DOM TRAVERSAL
// We can traverse through our whole DOM using javascript, by using js function and applying them on a HTML element to get it's children element, sibling elements and parent elements
// EX -1) -> in HTML:
//       <div id="grand-parent" class="g-p-class"> Grand Parent
//           <div> 
//               Parent1
//               <div id = "child-one"> child 1</div>
//               <div> child 2</div>
//           </div>
//           <div>Parent2 </div>
//       </div>
      
//       in Js:(Traversing through top to bottom)
//       const grandParent = document.querySelector("#grand-parent")
//       const parent1 = grandParent.children[0] //when we using grandParent.children this will give us and HTML collection so we are using 0th element of that collection
//       const parent2 = grandParent.children[1] //similarly we are getting parent 2 from grandParent
//       const parent2 = parent1.nextElementSibling // we can alsp get our parent2 via parent1 using nextElementSibling function this will give us the next sibling element of current element. We have a similar function as previousElementSibling to get previous sibling element.
//       const child1  = parent1.children[0]
//       const child2 = child1.nextElementSibling
//       child2.style.color = "red" //we can also use these element as modify them 
         
//       in Js:(Traversing through bottom to top)
//       const child1 = document.querySelector("#child-one")
//       const parent1 = child1.parentElement
//       const child2 = child1.nextElementSibling
//       cont parent2 = child2.parentElement
//       const grandParent = parent1.parentElement
//Suppose we want to jump over to an ancestor of an element without traversing through each and every parent. So we can do this using closest() function. The closest function will return the first parent that it finds according to the used querySelector.
//       const child1  = document.querySelector("#child-one")
//       const grandParent = child1.closest(".g-p-class")// this will return the first parent element that it gets with the given class
//       const parents = grandParent.querySelectorAll(".child") // we can use querySelectorAll or querySelector or any HTML element not just document 
         










 
by

Javascript Online Compiler

Write, Run & Share Javascript code online using OneCompiler's JS online compiler for free. It's one of the robust, feature-rich online compilers for Javascript language. Getting started with the OneCompiler's Javascript editor is easy and fast. The editor shows sample boilerplate code when you choose language as Javascript and start coding.

About Javascript

Javascript(JS) is a object-oriented programming language which adhere to ECMA Script Standards. Javascript is required to design the behaviour of the web pages.

Key Features

  • Open-source
  • Just-in-time compiled language
  • Embedded along with HTML and makes web pages alive
  • Originally named as LiveScript.
  • Executable in both browser and server which has Javascript engines like V8(chrome), SpiderMonkey(Firefox) etc.

Syntax help

STDIN Example

var readline = require('readline');
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

rl.on('line', function(line){
    console.log("Hello, " + line);
});

variable declaration

KeywordDescriptionScope
varVar is used to declare variables(old way of declaring variables)Function or global scope
letlet is also used to declare variables(new way)Global or block Scope
constconst is used to declare const values. Once the value is assigned, it can not be modifiedGlobal or block Scope

Backtick Strings

Interpolation

let greetings = `Hello ${name}`

Multi line Strings

const msg = `
hello
world!
`

Arrays

An array is a collection of items or values.

Syntax:

let arrayName = [value1, value2,..etc];
// or
let arrayName = new Array("value1","value2",..etc);

Example:

let mobiles = ["iPhone", "Samsung", "Pixel"];

// accessing an array
console.log(mobiles[0]);

// changing an array element
mobiles[3] = "Nokia";

Arrow functions

Arrow Functions helps developers to write code in concise way, it’s introduced in ES6.
Arrow functions can be written in multiple ways. Below are couple of ways to use arrow function but it can be written in many other ways as well.

Syntax:

() => expression

Example:

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const squaresOfEvenNumbers = numbers.filter(ele => ele % 2 == 0)
                                    .map(ele => ele ** 2);
console.log(squaresOfEvenNumbers);

De-structuring

Arrays

let [firstName, lastName] = ['Foo', 'Bar']

Objects

let {firstName, lastName} = {
  firstName: 'Foo',
  lastName: 'Bar'
}

rest(...) operator

 const {
    title,
    firstName,
    lastName,
    ...rest
  } = record;

Spread(...) operator

//Object spread
const post = {
  ...options,
  type: "new"
}
//array spread
const users = [
  ...adminUsers,
  ...normalUsers
]

Functions

function greetings({ name = 'Foo' } = {}) { //Defaulting name to Foo
  console.log(`Hello ${name}!`);
}
 
greet() // Hello Foo
greet({ name: 'Bar' }) // Hi Bar

Loops

1. If:

IF is used to execute a block of code based on a condition.

Syntax

if(condition){
    // code
}

2. If-Else:

Else part is used to execute the block of code when the condition fails.

Syntax

if(condition){
    // code
} else {
    // code
}

3. Switch:

Switch is used to replace nested If-Else statements.

Syntax

switch(condition){
    case 'value1' :
        //code
        [break;]
    case 'value2' :
        //code
        [break;]
    .......
    default :
        //code
        [break;]
}

4. For

For loop is used to iterate a set of statements based on a condition.

for(Initialization; Condition; Increment/decrement){  
//code  
} 

5. While

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while (condition) {  
  // code 
}  

6. Do-While

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {  
  // code 
} while (condition); 

Classes

ES6 introduced classes along with OOPS concepts in JS. Class is similar to a function which you can think like kind of template which will get called when ever you initialize class.

Syntax:

class className {
  constructor() { ... } //Mandatory Class method
  method1() { ... }
  method2() { ... }
  ...
}

Example:

class Mobile {
  constructor(model) {
    this.name = model;
  }
}

mbl = new Mobile("iPhone");