Java Script Basics

1. JavaScript is Dynamic Data Type Example
            
/*
Vanilla Javascript (ES5 Below)
ECMA (Electronics computer Manufacturer Association)
Modern(Advanced) Java Script ES6
javascript is dynamic data type language
*/

var studentName="SrinivasaRao";
console.log(studentName);
console.log(typeof(studentName));
studentName=345;
console.log(studentName);
console.log(typeof(studentName));
studentName=true;
console.log(studentName);
console.log(typeof(studentName));
studentName={id:1,name:"ramu",course:"java"};
console.log(studentName);
console.log(typeof(studentName));
studentName=[1,2,3,4];
console.log(studentName);
console.log(typeof(studentName));
var course;
console.log(course);
console.log(typeof(course));

            
        
2 Let, Var, Const Scopes Example
            
//let, const is block scope variable
//var global scope variables
{
    var c=25;//global scope
    let x=20;//block scope
    const a=10;//block scope
    console.log("Block 1 " + c);
    console.log("Block 1 " + x);
    {
       console.log("Block 1 " + x); 
    }
    console.log(a);
}
{
    let x=30;//block scope
    console.log("Block 2 " + c); 
    console.log("Block 1 " + x);
    // console.log(a);
}            
        
3. Hoisting , Reference Error, Undefine Example
            
//Hoisting 
//Hoisting is a mechanisam of V8Chrom engine
//It works only ES6 below versions functions
//when the reference erro raised
//if your try to acces variable with out declration
//undefined (Your declared variable but not assign any thing)
let a=10;
console.log(a);

console.log(sum(10,20));
function sum(a,b)
{
    return(a+b);
}
// const sum=(a,b)=>a+b;

            
        
4 Arithmetic Operators
            
//Operators
var a=25,b=12,c=2;
console.log("A+B=",(a+b));
console.log("A-B=",(a-b));
console.log("A*B=",(a*b));
console.log("A/B=",(a/b));
console.log("A%B=",(a%b));
console.log("A**B=",(a**c));

            
        
5 Relational Operators
            
//Relational Operators
let a=20,b=15,c="15",d=15;
console.log("A>B",(a>b));//true
console.log("A>=B",(a>=b));//true
console.log("A<B",(a<b));//false
console.log("A<=B",(a<=b));//false
console.log("A!=B",(a!=b));//true
console.log("B==D",(b==d));//true
console.log("b==c",(c==d));//true
console.log("b===c",(c===d));//false


            
        
6 Logical Operators
            
//Logical Operators
let a=24,b=34,c=33;
console.log(a>b && a>c)
console.log(a>b || a>c)
console.log(a>b == a>c)

console.log(b>a && b>c)
console.log(b>a || b>c)
console.log(b>a != b
        
7 Assignent Operators
            
//Assignent Operators
let a=12,b=2;
console.log("A=A**B ",a**=b);
console.log("A=A+B",a+=b);
console.log("A=A-B ",a-=b);
console.log("A=A*B ",a*=b);
console.log("A=A/B ",a/=b);
console.log("A=A%B ",a%=b);

            
        
8 Incremental and Decremental Operators
            
//Incremental and Decremental Operators
let i = 10;
console.log(i);
//pre increment
console.log(++i);
//post increment
console.log(i++);
console.log(i); //the previous operation effect this statement

//pre decrement
console.log(--i);
console.log(i--);
console.log(i); //the previous operation effect this statement

            
        
9 Bitwise Operators
            
//Bitwise Operators
console.log(5&9);
console.log(5|9);
console.log(5^9);
console.log(5<<9);
console.log(9>>5);
console.log(15>>>19);

            
        
10 tricky Questions
            
//tricky Questions
console.log(3+3);
console.log(3+"3");
console.log(3+ +"3");
console.log(20-"3");
console.log(20*"3");
console.log(20/"3");
console.log(20%"3");
console.log(33+"3"+5);//should be concate
console.log("33"+3 +5);//should be concate
console.log((33+"3")+5);//should be concate
console.log(("33"+3) +5)//should be concate
console.log(33+5+"3");

let a;
console.log(a);
console.log(typeof a)
let b=null;
console.log(b);
console.log(typeof b)


            
        
11 /Let vs Var vs Constant
            
//Let vs Var vs Constant
//constans can allow the initialization only declaration time
//it can't support re-initialization
//constants are block scoped variables
//let also block scope
//var global scope and block scope
const a=10;
var b = 20;
console.log(a);

{
  console.log("First Block");
  var b = 0;
  const a = 20;
  console.log(a);
  console.log("B=",b);
  b = b + 20;
  console.log("B=",b);
}
{
  console.log("Second Block");
  const a = 30;
  console.log(a);
  b = b + 20;
  console.log(b);
}
b = b + 20;
console.log(b);

const c = 10;
let d = 20;
console.log("C=", c);
console.log("D=", d);
{
  console.log("Third Block");
  console.log("C=", c);
  console.log("D=", d);
  const e =20;
  let f = 40;
  console.log("E=", e);
  console.log("F=", f);
  {
    // e=e+20;
    f = f + 40;
    console.log("E=", e);
    console.log("F=", f);
  }
}

            
        
12 Arrays
            
//Arrays
let nums=[1,2,3,4,5,6];
console.log(nums);
console.log("Length of Array:",nums.length);
nums.push(7);//push always add the element at the end of the array
nums.push(8);
console.log(nums);
nums.pop()//it remove last added element
console.log(nums);
nums.pop()
console.log(nums);
nums.shift()//it removes the first element of the array
console.log(nums);
nums.unshift(1);//it adds the element begining of the array
console.log(nums);
nums=nums.splice(2,5);//extracts the speicified data
console.log("After Delete:",nums);
            
        
13 Arrays & Loops
            
let nums = [1, 2, 3, 4, 5, 6];
//Modern For Loop
for (x in nums) {
  console.log(nums[x]);
}
let l = nums.length;
//Traditional Loop
for (let i = 0; i < l; i++) {
  console.log(nums[i]);
}
console.log(nums[0]);
console.log(nums[1]);




            
        
14 tricky Question
            
//tricky Question
let x=[1,2];
x[100]=20;
console.log(x.length);
console.log(x);
            
        
15 Array Methods
            
let nums=[5,2,3,1,4,10,6,14,22,32,45,101];
console.log(nums);
console.log(nums.sort());
console.log(nums.reverse());
let nums1=[5,55,66,77];
//combine two arrays using concat
let total=nums.concat(nums1);
console.log(nums);
console.log(nums1);
console.log(total);

//spread operator
//combine two arrays using spread operator
let totalnums=[...nums,...nums1];
console.log(totalnums);

//de-structure

let values=[44,55,66];
// let [a,b,c]=values;
// console.log(a);
// console.log(b);
// console.log(c);
let [a,,c]=values;
console.log(a);
console.log(c);
            
        
16 Splice(),Slice()
            
let nums=[1,2,3,4,5,6,7,8];
//syntax array.splice(startindex,noofelement,addingelements)
nums.splice(2,0,"a","b","c");
console.log(nums);

//syntax array.slice(startindex,endindex)
let ornums=nums.slice(2,5);
console.log(ornums)

//remove the specified index value
console.log(nums);
delete nums[0];
console.log(nums);

nums="Hello How are you".split('');
if(Array.isArray(nums))
{
    console.log("its Array");
}
else
{
    console.log("its not Array");
}

//includes

let names=["Ramesh","Kishore","Ram","Sita","Krihsna"];
console.log(names.includes("Kishore"));
            
        
17 Arrays and keys,values,reduce functions
              
const nums = [11, 22, 33, 44, 55];
//it returns keys(indexs)
for (let x in nums) {
  console.log(x + "->" + nums[x]);
}
//it returns values
for (let x of nums.values()) {
  console.log(x);
}
//it returns values
for (let x of nums) {
  console.log(x);
}

//reduce

// const sum=nums.reduce((acc,currentValue)=>acc+currentValue);
// console.log(sum);
function sum(acc, currentValue) {
  return acc + currentValue;
}
const sunofNums = nums.reduce(sum);
console.log(sunofNums);

              
            
18 forEach,map,filter functions
              
// const nums=[1,2,3,4,5,6];
let nums;
nums?.forEach((element)=>console.log(element));

// var result=nums.map((element)=>{
//     if(element>3)
//     {
//         return(element);
//     }
//     else
//     {
//         return null;
//     }
// });
var result=nums?.map((element)=>element>3 ? element : null)
console.log(result)

var result=nums?.filter((element)=>element>2 && element<4);
console.log(result)

              
            
19 fill,at functions
              
const months=["jan","Feb","Mar","Apr"];
console.log(months[0]);
console.log(months.at(0));
//it return array values
const reulst=months.values();
for(x of months)
{
    console.log(x)
}
//it returns array keys
for(x of months.keys())
{
    console.log(x)
}

//it fills upt  to 3 elements
const nums=[1,2,3,4,5,6];
console.log(nums);
console.log(nums.fill('x',nums.length-5,nums.length-2))
              
            
20 find,every functions
              
const nums=[1,2,3,4,5,6];

//it returns after find first element
let result=nums.find((element)=>element>3);
console.log(result);

function checkValue(element)
{
    return element>4;
}
result=nums.find(checkValue);
console.log(result);

result=nums.every((element)=>element>0)
function checkEvery(element)
{
    return element>3;
}
result=nums.every(checkEvery)
console.log(result);
              
            
21 Objects
              
//objects
const person={
    id:1,
    name:"SrinivasaRao",
    course:"java",
    place:"ongole"
};
//shallow copy ( it copies the reference)
//const student=person;
//Deep copy (it copies the data to new reference)
const student={...person}
console.log(person);
console.log(student);
console.log(person["id"]);
console.log(person["name"]);
console.log(person.id);
console.log(person.name);
person.name="Kunchala SrinivasaRao";
console.log(person.name);
console.log(person);
console.log(student);
person.state="AP";
console.log(person);
console.log(student);

              
            
22 Object,Array Destructuring, rest Operators
              
const person={
    id:1,
    name:"John",
    designation:"Engg"
};
const address={
    area:"Newyork",
    city:"Newyork",
    state:"NewYork City",
    country:"America"
}
//object spreading
const fullDetails={...person,...address};
console.log(person);
console.log(address);
console.log(fullDetails);

//object destructuring
const {name,designation,id}=person;
console.log(id);
console.log(name);
console.log(designation);

//Arrya Destructure
const nums=[1,2,3];
[a,,c]=nums;
console.log(a);
// console.log(b);
console.log(c);
              
            
23 Array Object Destructuring
              
//array destructring
const nums=[45,67,78];
const [a,,c]=nums;
console.log(a);
// console.log(b);
console.log(c);

//object destructuring
const person={
    id:1,
    name:"Ramesh",
    desig:"engg",
    city:"ongole"
}
const {name,city,id}=person;
console.log(name);
console.log(id);
console.log(city)
              
            
24 Function Declaration
              
//1.Function Declaration
const result=sum(45,56);
console.log(result)

function sum(arg1, arg2) {
  return arg1 + arg2;
}
//function declartions should always moves on top while execution of the javascript
//that is called hoisting


              
            
25 Function Expression
              
//2. function expression
//this is not apply hoisting
const sum = function (arg1, arg2) {
  return arg1 + arg2;
};

console.log(sum(10, 20));

              
            
26 Arrow Functions
              
//3.Arrow functions nothing but expression functions
//this will not apply the hoisting because arrow functions can works  es6 onwards
const sum = (arg1, arg2) => arg1 + arg2;

console.log(sum(34, 45));

const big = (arg1, arg2) => {
  if (arg1 > arg2) {
    return arg1;
  } else {
    return arg2;
  }
};
console.log(big(45, 77));
              
            
27 Ananonmous functions
              
//4 Ananonmous functions
console.log("1");
setTimeout(() => {
  console.log("2");
}, 0);

console.log("3");



              
            
28 Immediatly Invoked Function
              
 //5.iif (Immediatly Invoked Function)
(function () {
  console.log("Hai");
})();

              
            
29 Higher-Order Function
              
//6. Higher-Order Function
//A function that takes another function as an argument or returns a function.
function  sum(a,b)
{
    return(a+b)
}
function operate(a, b, sum) {
  return sum(a, b);
}

//const result=operate(6, 4, (x, y) => x + y);
const result=operate(6, 4, sum);
console.log(result)
              
            
30 Callback Function
              
//7. Callback Function
//A function passed into another function to be executed later.
function greet(name, callback) {
  console.log("Hello " + name);
  callback();
}

greet("Srinivas", function () {
  console.log("Welcome to JavaScript!");
});
console.log("--------------");
function fun(msg) {
  console.log("This Message Came from First Funciton " + msg);
}
const showMessage = (msg, fun) => {
  console.log("First Function Execution completed");
  fun(msg);
};

showMessage("Hi Call Back Function", fun);

              
            
31 Constructor Function Deep Copy
              
//8. Constructor Function
//Used to create objects (before ES6 class).
function Person(name=null, age=null) {
  this.name = name;
  this.age = age; 
}
//like deep copy
const p1 = new Person("Ravi", 25);
const p2 = new Person("Sree", "44");
const p3 = new Person();
console.log(p1.name);
console.log(p1.age);
p1.age = 60;
console.log(p1.age);
console.log(p2.name);
console.log(p2.age);

console.log(p3.name);
console.log(p3.age);
p3.name="SrinivasaRao";
p3.age=54;
console.log(p3.name);
console.log(p3.age);

              
            
32 Generator Function
              
//9. Generator Function
function* numbers() {
  yield showMessage();
  yield 2;
  yield 3;
}

function showMessage()
{
    return(1);
}
const gen = numbers();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
              
            
33 functions with rest operator
              
//functions with rest operator
function sum(a, b, ...d) {
  let total = a + b;
  for (let i = 0; i < d.length; i++) {
    total += d[i];
  }
  return total;
}

console.log(sum(34, 45));
console.log(sum(34, 45, 88));
console.log(sum(34, 45, 88, 99));
console.log(sum(34, 45, 88, 100, 78));

              
            
34 API Calling
              
//api calling
//https://jsonplaceholder.typicode.com/
const URL = "https://jsonplaceholder.typicode.com/users";

// fetch(URL)
//   .then((response) => response.json())
//   .then((data) => console.log(data))
//   .catch((err) => console.log(err));

const getData = async () => {
  const data = await fetch(URL).then((response) => response.json());
  data.map((user) => {
    console.log(
      user.id + " - " + user.name + " - " + user.username + " - " + user.email
    );
  });
};

getData();
              
            
35 Invterview Q & A
              
              
            
35 Invterview Q & A
              
let number = max(17, 22);
console.log(number);

function max(a, b) { 
  return (a > b) ? a : b;
}
              
            
36 Invterview Q & A
              
const result=isLandscape(600, 300)
// if(result)
// {
//   console.log("Landscape");
// }
// else{
//   console.log("Portrait");
// }
console.log(result ? "Landscape": "Portrait");

function isLandscape(width, height) {
  return (width > height);
}
              
            
37 Invterview Q & A
              
const output = fizzBuzz(15);
console.log(output);

function fizzBuzz(input) {

  if (typeof input !== "number") 
    return NaN;
  
  if (input <0) 
  return "Negative values not Accepted";

  if (input % 3 === 0 && input % 5 === 0) 
    return "FizzBuzz";

  if (input % 3 === 0) 
    return "Fizz";

  if (input % 5 === 0) 
    return "Buzz";

  return input;
}

              
            
38 Invterview Q & A
              
checkSpeed(130);

function checkSpeed(speed) {
  const speedLimit = 70;
  const kmPerPoint = 5;

  if (speed < speedLimit + kmPerPoint) {
    console.log ('Ok');
    return; 
  }
  const points = Math.floor((speed - speedLimit) / kmPerPoint);
  if (points >= 12)
    console.log('License suspended');
  else
    console.log('Points', points);
}
              
            
39 Invterview Q & A
              

//showNumbers(15);

// function showNumbers(limit) {
//   for (let i = 0; i <= limit; i++) {
//     const message = (i % 2 === 0) ? 'EVEN' : 'ODD';
//     console.log(i, message);
//   }
// }

let min=1,max=100;
function printPrimeNumbers(min,max)
{
  for(let i=min;i<=max;i++)
  {
    count=0;
    for(let j=2;j<i;j++)
    {
      if(i%j===0)
      {
        count++;
      }
    }
    if(count==0) console.log(i + " ");
  }
}
printPrimeNumbers(1,100);
              
            
40 Invterview Q & A
              
const array = [-1, null, undefined, "a", 2, 3, 5];

console.log(countTruthy(array));

function countTruthy(array) {
  let count = 0;
  for (let value of array) if (value) count++;
  return count;
}

console.log(null && "True")
              
            
41 Invterview Q & A
              
const movie = {
  title: "a",
  releaseYear: 2018,
  rating: 4.5,
  director: "b",
};

showProperties(movie);

function showProperties(obj) {
  for (let key in obj) {
    if (typeof obj[key] == "string") 
      console.log(key, ":", obj[key]);
  }
}

let values=Object.keys(movie);
console.log(values);
values.forEach((element)=>console.log(element));

values=Object.values(movie);
console.log(values);
values.forEach((element)=>console.log(element));
values=Object.entries(movie);
              
            
42 Invterview Q & A
              

console.log(sum(10));

function sum(limit) { 
  let sum = 0; 
  for (let i = 0; i <= limit; i++)
    if (i % 3 === 0 || i % 5 === 0)
      // sum += i;
    sum++;
  
  return sum; 
}
              
            
43 Invterview Q & A
              

function calculateGrade(marks) { 
  const average = calculateAverage(marks);
  if (average < 60) return 'F';
  if (average < 70) return 'D';
  if (average < 80) return 'C';
  if (average < 90) return 'B';
  return 'A';
}

function calculateAverage(array) {
  let sum = 0; 
  for (let value of array)
    sum += value; 
  return sum / array.length; 
}

const marks=[[33,44,55,66,77,88,87],[33,44,55,66,77,88,87]];
console.log(calculateAverage(marks))
marks.forEach((element)=>console.log(calculateGrade(element)))

              
            
44 Invterview Q & A
              

let n=5;
pyrmidTop(n);
pyramidBottom(n-1)
function pyrmidTop(rows) { 
  for (let row = 1; row <= rows; row++) {
    let pattern = ''; 
    for (let i = 0; i < row; i++)
      pattern += '*';
    console.log(pattern);
  }
}
function pyramidBottom(rows) { 
  for (let row = rows; row >=1; row--) {
    let pattern = ''; 
    for (let i = 0; i < row; i++)
      pattern += '*';
    console.log(pattern);
  }
}
              
            
45 Invterview Q & A
              

function showPrimes(limit) {
  for (let number = 2; number <= limit; number++) 
    if (isPrime(number)) console.log(number);
}

function isPrime(number) {
  for (let factor = 2; factor < number; factor++)
    if (number % factor === 0)
      return false; 
  
  return true; 
}

showPrimes(200)
              
            
46 OOPs in Java Script
              
//class
class Student{
    constructor()
    {
        this.code=100;
        this.name="Ram";
    }
    setData(code,name)
    {
        this.code=code;
        this.name=name;
    }
    showData()
    {
        console.log("Code:" + this.code);
        console.log("Name:"+ this.name);
    }
}

const ramesh=new Student();
ramesh.showData();
code=200;
name="Rajesh";
ramesh.setData(code,name);
ramesh.showData();
              
            
47 OOPS in JavaScript
              
class Student {
  constructor(code, name) {
    this.code = code;
    this.name = name;
  }
  getCode() {
    return this.code;
  }
  setCode(code) {
    this.code = code;
  }
  getName() {
    return this.name;
  }
  setName(name) {
    this.name = name;
  }
}
code = 100;
name = "Prasanth";
const ramesh = new Student(code, name);
console.log(ramesh.getCode());
console.log(ramesh.getName());
ramesh.setCode(200);
ramesh.setName("Kishore");
console.log(ramesh.getCode());
console.log(ramesh.getName());