Skip to content

Instantly share code, notes, and snippets.

@tarunxsh
Last active August 12, 2024 12:15
Show Gist options
  • Select an option

  • Save tarunxsh/882b544a8db9dabfc5e1f40ba152f0d6 to your computer and use it in GitHub Desktop.

Select an option

Save tarunxsh/882b544a8db9dabfc5e1f40ba152f0d6 to your computer and use it in GitHub Desktop.
javascript basics
//======================================================================================================================
//Javascript
// Variables, Arrays, Functions,Loops, Classes, Objects
//======================================================================================================================
// single line comment using //
/*
multi line
comments in javascript
using this block
*/
//semicolons are optional(not always) in javascript. JavaScript parser will automatically add a semicolon .
//=====================================================================================================================
//VARIABLES
//Global variables are those declared outside of a block
//Local variables are those declared inside of a block
//Using local scope, we can actually create new variables
//with the same name as a variable in an outer scope without changing or reassigning the original value.
c = 20 //Global variable
var d = 30 //Function Scope|hoisting|Can Be Reassigned|Can Be Redeclared|
let e = 50 // Block Scope|Can Be Reassigned.|
const NAME = "value" //Block Scope only|
let [a, b] = [3, 7]; //Destructuring array
console.log(a); //print 3 and returns undefined
console.log(b); // 7
console.log("%d, %d %s", d, e,NAME);
// Hoisting : Attempt to use a variable before declaring it
//======================================================================================================================
//Arrays In Javascript
let myArray = new Array('1', '2') //array declaration method 1
let arr = ["Apple","Mango","Guava" , "orange"] //array declaration method 2
console.log("array")
console.log(arr)
comb = [3,4,5,6,...myArray] //spread operator : spread out elements of an iterable such as an array,a map, or a set
console.log(comb)
var len = arr.length
// Loop over Array
//method 1
console.log("looping over array")
console.log("method 1")
for(let i=0;i<len;i++){
console.log(arr[i])
}
//method 2
console.log("method 2")
arr.forEach(function(item, index, array) {
console.log(item, index) //print item , index
})
//method 3
console.log("method 3")
for (let value of arr) { //for...of use to loop over an iterable object such as an Array, a Map, a Set,
console.log(value); //for...in use to loop over the properties of an object (the object keys)
}
console.log(arr[1]) //access elements using array "Mango"
arr.concat("cherry" ,"grape") //joins two or more arrays and returns a new array.
arr.push("Banana") //Insert at back ["Apple","Mango","Guava" , "orange","cherry" ,"grape","Banana"]
arr.pop() //remove from back
arr.shift() //remove from front
arr.unshift("Kiwi") //insert at front
arr.indexOf("Kiwi") //finds you the index
arr.reverse()
arr.sort()
list = arr.join(' - ') //join(delimiter = ',') joins all elements of an array into a string.
console.log(list) //Kiwi - Mango - Guava - orange
//slice(start_index, upto_index) extracts a section of an array and returns a new ,does not affetc original array
arr.slice(3 , 5) //slicing the array
//arr.splice(index, count_to_remove, addElement1, addElement2, ...)
//removes elements from an array and (optionally) replaces them. It returns the items which were removed from the array.
//array.map(callback) returns a new array of the return value from executing callback on every array item.
let a2 = arr.map(function(item, index, arr) { return item.toUpperCase() })
console.log(a2)
//arr.filter(callback) returns a new array containing the items for which callback returned true.
//every(callback) returns true if callback returns true for every item in the array.
//some(callback) returns true if callback returns true for at least one item in the array.
//======================================================================================================================
// Map object
//A Map object is a simple key/value map and can iterate its elements in insertion order.
let capitals = new Map();
capitals.set("Gujarat" , "Gandhinagar") //set(key,value)
capitals.set("Bihar","Patna")
capitals.set("Maharashtra","Mumbai")
for (let [key, value] of capitals) {
console.log("capital of ", key + "is" + value);
}
capitals.get("Bihar") //Patna
capitals.has("Goa") //check if key exists
capitals.delete("Bihar") //delete a single entry
capitals.size //retrun size
capitals.clear() //clear map or dictionary
//======================================================================================================================
//Set Object
//A value in a Set may only occur once.
//can have different data types
let mySet = new Set()
mySet.add(1)
mySet.add('some text')
mySet.add('foo')
mySet.has(1); // true
mySet.delete('foo')
mySet.size // 2
for (let item of mySet) console.log(item);
// 1
// "some text"
//======================================================================================================================
//if-else in js
if(arr[0]=="Apple"){
console.log("Apple")
}
else{
console.log("No it is",arr[0])
}
//======================================================================================================================
//Strings
let string = "Javascript";
for (let char of string) {
console.log(char);
}
//======================================================================================================================
//Funstions in javascript
//Function Hoisting Calling before declaration
square_root(10) //fuction calling
//global fuction
//nested fuctions are local and they can access only fuction level variables
function square_root(n){
console.log("In first sqrt fn")
console.log("sqr root of " ,n, "is: " ,Math.sqrt(n))
return
}
//Function Expression
var sqr = function(n){return n*n }
console.log("square of" , e , "is:", sqr(e))
//variable scope visualisation
var f = 100
console.log("Global var outside function " , f)
//Function Declaration
function fun(){
var f = 40
console.log("inside fuction outside if " , f)
if(f===40){
let f = 100 //let has a block scope, var has a function scope
console.log("Inside if block",f)
}
console.log("Outside if block",f)
}
fun()
console.log("Global outside function",f)
//----------------------------------------->
//Arrow Funtions
//New Syntax There are two parts of the syntax.
//The first part is just declaring a variable and assigning the function (i.e) () to it.
//Now variable name is actually the function name.
//Then the second part is declaring the body part of the function
//The arrow part with the curly braces defines the body part.
var newOne = () => { //(parameters)
console.log("Hello World..!"); //(a = 10) default parameters
}
var add = (x, y) => { return x + y; };
console.log(add(5,4))
//typeof use to check data type
console.log(typeof add); // function
//======================================================================================================================
//rest parameters
//converts lots of parameters into an array. must be at the end of the argument list.
function sum(a,b,...args) {
let total = 0;
for (const a of args) {
total += a;
}
return total;
}
sum(1,2,3,4,5,6,); //a=1 b=2 args=[3,4,5,6]
//======================================================================================================================
//Objects in javascript...........In JavaScript, almost "everything" is an object.
//All objects in JavaScript inherit from at least one other object known as the prototype
//Booleans can be objects (if defined with the new keyword)
//Numbers can be objects (if defined with the new keyword)
//Strings can be objects (if defined with the new keyword)
//Dates are always objects
//Maths are always objects
//Regular expressions are always objects
//Arrays are always objects
//Functions are always objects
//Objects are always objects
//method 1
var person1 = {firstName:"Nick", lastName:"Jonas", age:30, eyeColor:"blue"};
person1.age //accessing properties of objects
person1["age"] //method2
person1.firstName = "Max" //setting properties of objects
//method 2
//creation of new object and the setting values to it
var person2 = new Object();
person2.firstName = "John";
person2.lastName = "Doe";
person2.age = 50;
person2.eyeColor = "blue";
//method 3
var person3 = Object.create(person1); //takes object prototype as a parameter
person3.firstName="Tarunesh"
//method 4
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
var mycar = new Car('Eagle', 'Talon TSi', 1993);
//Adding a functtion to js object
function sayHi() {
console.log('Hello, my name is', this.firstName) //this refer object that it is calling/accessing the property
}
person3.greet = sayHi
person3.greet() //Hello, my name is Max
//Use for…in to iterate over the properties of an object (keys) also arrays and strings but not on set and map
for (let key in mycar) {
console.log(`${key} --> ${mycar[key]}`); //string templates uses backticks
}
//string templates
let str = `Template literal in ES6`;
let msg = 'Multiline \n\
string';
//======================================================================================================================
//Classes in Javascript (not hoisted ...ReferenceError)
//Class Keyword (ECMAScript 2015) ES6
//class can be pass to a function, return from a function, and assign to a variable.
class Animal {
constructor(type,legs) { //constructor() is where you can add the properties of an instance
this.type = type
this.legs = legs
}
identify() { //function keyword is not needed to declare a method of the class.
console.log(this.type)
}
walk() {
console.log('walking on ' + this.legs + ' legs')
}
static AnimalWorld() {
console.log('Hello from AnimalWorld');
}
}
let cat = new Animal('Cat',4)
cat.identify()
cat.walk()
// class expressions.............Similar to functions
let Animal2 = class {
constructor(type) {
this.type = type
}
identify() {
console.log(this.type)
}
}
let duck = new Animal2('Duck')
//static methods
//Static methods aren't called on instances of the class. Instead, they're called on the class itself.
class Example {
static Callme() {
console.log("Static method")
}
}
Example.Callme()
//Getters and Setters
class People {
constructor(name) {
this.name = name
}
get Name() { // ‘get’ property is used to get the value of the variable
return this.name
}
set Name(name) { //‘set’ property is used to set the value to the variable.
this.name = name
}
}
let person = new People("Jon Snow")
console.log(person.Name) //get Name function is called without parenthesis
person.Name = "Dany" //called without parenthesis....just like assigning a value to the variable.
console.log(person.Name)
//JavaScript inheritance https://www.javascripttutorial.net/es6/javascript-inheritance/
//old prototypal inheritance
//https://www.javascripttutorial.net/javascript-prototype/
//https://www.javascripttutorial.net/javascript-prototypal-inheritance/
class Bird extends Animal { //inherits from Animal class using extend
constructor(type,legs) { //nimal class is called base class and the Bird class is known as derived class.
super(type,legs) //super() to call the Animal‘s constructor with the specified arguments.
}
fly() {
console.log('flying')
}
birdWalk(){
console.log("calling BASE CLASS from CHILD CLASS")
super.walk() //To call the method of the base class in the derived class, you use super.method()
}
}
Bird.AnimalWorld() //The derived class inherits all static members of the base class
let bird = new Bird('new',2)
console.log("Bird type : ",bird.type)
bird.birdWalk()
bird.fly()
//if using contructor then you must call super()
//super() initializes the .this object
//new properties should be inside constructor
//NOT using constructor is equivalent to
/*
constructor(...args) {
super(...args);
}
*/
/*new.target is used to check whether a function is being executed as a function or as a constructor
if (!new.target) {
throw "must use new operator with Person";
*/
//----------------------------------------------->
//Queue using inheritence in javascript
class Queue extends Array {
enqueue(e) {
super.push(e);
}
dequeue() {
return super.shift();
}
peek() {
return !this.empty() ? this[0] : undefined;
}
empty() {
return this.length === 0;
}
}
var customers = new Queue();
customers.enqueue('A');
customers.enqueue('B');
customers.enqueue('C');
while (!customers.empty()) {
console.log(customers.dequeue());
}
//======================================================================================================================
//JavaScript Promises
//for handling asynchronous operations such as API request, file handling, downloading images, etc.
//a promise is an object that returns a value which you hope to receive in the future, but not now.
//three states in promises : Pending => Fulfilled or Rejected
//Pending: In this state the promise is just executing the async operation.
//Fulfilled: async operation is complete and we have the output
//Rejected: the async operation is not successful and we have the error which caused the operation to fail.
//Promise constructor accepts a function as an argument. This function is called the executor.
//The executor accepts two functions with the names, by convention, resolve() and reject()
//when you call the new Promise(executor), the executor is called automatically.
//The async operation is defined inside the executor function => in pending state
//if async operation is successful resolve is called => fulfilled state reached
//else invoke the reject() function in case of an error occurs. => rejecte state reached
let completed = false;
let learnJS = new Promise(function (resolve, reject) {
setTimeout(() => { //setTimeout() is not required ,used here to see the pending state of the promise
if (completed) {
resolve("I have completed learning JS.");
} else {
reject("I haven't completed learning JS yet.");
}
}, 3 * 1000); // in pending state for 3 seconds
});
learnJS
.then(function(success){
console.log(success); })
.catch(function(error){
console.log(error); })
.finally(function(){
console.log("Thank You")});
console.log("asynchronous operation RUNNING")
//use then and catch handlers to handle the output returned from the promise
//Handlers are just functions which executes when some event occurs such as clicking a button, moving the cursor, etc.
//then() handler method is used to schedule a callback to be executed when the promise is successfully resolved.
//======================================================================================================================
//Async / Await in javascript
//Async keyword makes any function to return only promises.
//Await can be used only inside async function. It doesn’t work outside async function
async function corona() {
let response = await fetch('https://api.rootnet.in/covid19-in/unofficial/covid19india.org/statewise');
// above line fetches the response from the given API endpoint.
let data = await response.json();
return data;
}
corona()
.then(function(success) {
console.log(success)
})
.catch(function(error){
console.log(error); })
.finally(function(){
console.log("Thank You")});
//======================================================================================================================
//DOM api
//all window properties are automatically global variables,
console.log(document.body);
document.getElementById("ref1").textContent = "Hello, World";
//Adding new element to DOM
var new_element = document.createElement('p');
new_element.textContent="new element created"
document.body.appendChild(new_element); //add the newly created element to the DOM
//Dialog boxes are modal windows they prevent the user from accessing the rest of the program's interface until closed
window.alert("This is a alert Enter you age");
var age = prompt("How old are you?") //prompt(text, [default])
console.log(age); // Prints the value inserted by the user
document.getElementById("ref1").textContent = `Age is ${age}`;
result = window.confirm("Are you human"); //return boolean value
var img = new Image();
img.src = 'https://i.ytimg.com/vi/zecueq-mo4M/maxresdefault.jpg';
document.body.appendChild(img);
//======================================================================================================================
//isNaN() can be used to check if a certain value or expression evaluates to NaN (Not a Number)
//This function first checks if the value is a number, if not the it tries to convert it in munber
//and then checks if the resulting value is Number or Not
//if Number then return False
//if not a number then return True
//final check is done on second step
//array is considered NaN unless it holds one element whose string representation can be converted to a valid number
isNaN(1); // false: 1 is a number
isNaN(true); // false: converted to 1, which is a number
isNaN(null); // false: converted to 0, which is a number
isNaN(" "); // false: converted to 0, which is a number
isNaN("45.3"); // false: string representing a number, converted to 45.3
isNaN("hello"); // true : conversion fails, no digits at all
isNaN(undefined); // true : converted to NaN
isNaN([1, 2]); // true : converted to "1, 2", which can't be converted to a number
isNaN([34]); // false : converted to "34" , which is converted to 34 a number
isNaN([true]) // true : converted to "true" which is a string
//return false if a number or can be converted into a number
//return true if not a number or conversion in number fails
Number.isNaN(1) //false //just return true if not a number else false
//======================================================================================================================
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment