Thursday, 15 August 2024

Java Script Basic

  Spread Operator

the operator shap is three consective dots and is written as: 

Usages of sparead operator

1. Expanding String - Convert String into list of array

2. Combining Arrays - Combine array or add value to array

3. Combining Object - Combine Object or add value to Object

4. Create New Shallow Copy of Arrays and Object


sparead operator


1) Arrays


var arry = [a,b,c];

// array indax start from zero

console.log(arry[0]);

console.log(arry[1]);



//2 Object


var obj = {

"name" : "salesforce",

"age"  : "54",

}

console.log(obj.name)

console.log(obj.age)


// Spread Operator


//1. Expanding of string


let greeting = "Hello World"

let charlist = [...greeting]

console.log(charlist[10]);


//2.Combing array


let arr1 = ["amazon","persistent","google"];

let arr2 = ["feedback","instration"]


let arr3 = [...arr1, ...arr2];

console.log(arr3);



// 3.adding values to an array



let arr4 = ["a","b","c"];


let arr5 = [...arr4,"giri"];


console.log(arr5);


// 4. Combining Object


 let obj1 = {name:"salesforce", age:23, date:"23/10/1990}

 let obj2 = {name:"feedback", age:26}

 let obj3 = {...obj1, ...obj2}

 

 

 //5. Shallow copy

 

 var arr10 = ["x","y","z"]

 arr10.push(20)

 console.log(arr10)

 console.log(arr11)

 

 //6. Nasted copy

 

 var arrObj1 = [{name:"giri"},

                {name:"salesforce"}]

var arrobj1 = [...arrobj]


Destructring


The two most used data structure in javaScript are Object and Arrays


Destructring is a special syntax that allows us to "unpack" arrays or objects into a 

bunch of variables as sometimes that's more convenient


. Arrays destructing

. Object destructing 



// array destructing


let arr = ["amazon", "google"]


let [company1, company2] = arr


 console.log(company1)

 console.log(company2)

 

 // object destructing

 

  let options = {

                title:"zero to hero",

age  :23,

type : "CRM"}

let {title, age, type} = options

console.log(title)

console.log(age)

console.log(type)


String interpolation  


. string interpolation allows you to embed expressions in the string

. Template string use back-tick('') rather than the singe or double-quotes


var name = "salesforce troop";

console.log('Hello, ${name}!');



//string Interpolation with expressions


var a= 10;

var b = 20;


console.log('The sum of ${a} and ${b} is ${a+b}');


//string Interpolation


var name = "sales"

var name1 = "force"


console.log(name + name1);


var name = "Giri Kumar"

var age  = 35


var str = "my name is "+ name+"and my age is "+ age 


console.log(str)


var a = 2

var b = 3


var str1 = "the sum of"+a+ "and"+b+ "is" a+b

console.log(str1)


String Method


JavaScript provides many methods to play with strings. Below are some of the most commonly used string methods 

in LWC 


1.includes()

2.indexOf()

3.StartsWith()

4.Slice()

5.toLowerCase()

6.toUpperCase()

7.trim()


let str = "Hello guys i hope your are doing good"


//Include

//The includes() method determines whether a string contains

//the characters of specialfied string


let check = str.includes("hope")

console.log(check)


// indexof

// The indexof() method returns the posities of the first

// occurrence of a specified value in a string


let index = str.indexof("doing")

console.log(index)


//stratWith()

// determines whether a string begins with the characters

// of a specified string


console.log(str.startWith("Hello"))


//slice()

//method extracts parts of a string and returns the 

//extracted parts in a new string


  let newstr = str.slice(0, 5)

  console.log(newstr)

  

  //toLowerCase

  // converts string to lowercases letter

  

  let x = "my name is giri "

  console.log(x.toLowerCase())

  

  //trim() - remove whitespace from both sides of a string

    

  let searchtext = " salesforce lwc "

  console.log(searchtext.trim())

  

  let obj = {

            name: "Salesforce",

age : 23,

dob : '20/03/2024'

}

  console.log(Object.keys(obj))

  

  // Object.keys()

  

  console.log(object.keys(obj))

  

  // Object.values()

  

  console.log(object.values(obj))

  

  //JSON.stringify

   let str = JSON.stringify(obj))

  console.log(str)

  

  //JSON.parse

   console.log(JSON.parse(str))

  

  Arrays Method

  

  1) map() - loop over the array and return new array based on the value return.

  2) every() - return ture or false if every element in the array satisfy the condition.

  3) filter() - return new array with all the element that satisfy the condition

  4) some() - return true if at least one element in the array satisfy

  5) sort() - sort the element of an array

  6) reduce() -  this method reduces the array to asigle value(left to right)

  7) foreach() - this method calls for each array element

  

  let arr = [2,3,4,5,6,7,9,10]

  

 let newArray =  arr.map(funcation(currentItem, index, array){

   console.log('currentItem is ${currentItem},index ${index},array ${array}' )

   return currentItem*2

   })

  console.log(newArray)

  

  //filter()

  

   let filteredvalues = arr.filter(funcation(currentItem, index, array){

     return currentItem > 5

 })

   console.log(filteredvalues)

   

   //every

   let age = [32, 33, 18, 40]

   let agealladult = age.every(funcation(currentItem){

    return currentItem >=18

   })

   

   //some

   let agelist = [32, 33, 18, 40]

   let isadult = agelist.some(funcation(currentItem){

          return currentItem > 32

   })

    console.log(isadult)

//sort()

var names = ["giri","hari","john"]

console.log(names.sort())

//sorting of number

var points = [10,32,12,80,54]

points.sort(funcation(a,b){

 return a-b

})

console.log(sortedValue)

let num = [12, 78, 30]

let sum = num.reduce(funcation(total,currentItem){

  return total+currentItem

},0)

 console.log(sum)

 

 //for Each

 num.forEach(funcation(currentItem){

   console.log(currentItem)

 })

 Promise

 Promise is an object that may produce a single value sometime in the future

 promise are used to handle asynchronous operations in javaScript

 A Promise has three states

 1) pending

 2) fulfilled

 3) rejected

 Use Case from LWC point of view

 1. Fetching data from server 2) Loading file from system

 funcation checkIssuccess(data){

   return new Promise(funcation(resolve, reject){

   if(data === "success"){

    return resolve("successfully executed")

}else{

return resolve("unsuccessfully executed")

}

   })

  

}

checkIssuccess('success').then(funcation(result){

console.log(result)

}).catch(error){

console.log(error)

}

 

feach('https://api.github.com/user/karkranihil').then(function(){

  return return.json()

}).then(funcation(response){

console.log(response)

})

 

modules import and export

 

Exports

 

Exporting Use export keywords to export many variables or many method from a file 

 

export cont name = "giri"

 

  export function getname(){

   return "giri"

  }

 

Default export - use export defult keyword to export only one variable or a method from a file

 

Imports

 

Importing - Use import keyword to import variable or method from a given file path or modules

 

multiple imports

 

import {name,getname} from './filepath'

 

imports all exported members

 

  import * as utils from './filepath'

  

  import a module with a defult members

  

  import user from './filepath'

  

  

  utils

  

  export const PI = 3.14

  

  export funcation add(a,b){

   console.log(a+b)

  }

  //export {PI,add}

  

  export {PI_DATA as PI, add}

  

  export defult function minus(a,b){

   console.log(a-b)

  }

  

  script 

  

  import {PI, add} from '.utils';

  

  import * as UTILS from './utils'

  console.log(UTILS.PI)

  console.log(UTILS.add(2,3))

  console.log(UTILS.minus(8,5))

  

  

  QuerySelect

  ------------

  queryselector

  

  The queryselector() method returns the first element that matches a specified CSS

      selector(s) in the document


      queryselectorAll

      The queryselectorAll() method returns all element in the document that matches a specified CSS selector(s) as a static nodelist object

  example js

  document.querySelectorAll(selector)

  

   let element = document.queryselector('.abc')

   console.log(element.innerText)

   element.style.color="red"

   

   let elementAll = document.querySelectorAll('div')

   console.log(elementAll)

   Array.from(elementAll).foreach(funcation(item){

    return item.style.color="green"

   })

   

   example html

   <html>

    <head>

<title>  First HTML Page </title>

<head>

<body>

<div class="abc"> Hello Everyone </div>

<div> Hello LWC Developers </div>

<script type="module" src="./script.js"></script>

</body>

<html>

Event 

    An event is an action that occurs in the web browser, which the web browser

feedback to you so that you can response to it.

for example, when users click  a button on a webpage, you want to respond to this click

event by displaying a alert box.

Event handler - It is a block of code that will execute when the event occurs. It is also

known as an event listener

Two Common ways to add events

1. HTML Event Handler attribute - When we add event through HTML,Event always begins

  with on keyword like onclick,onchange,onkeyup

  

2. Event Listener - Event Handler provide two main method for dealing with the

  registering/deregistering event listener

. addEventListener() - register an event handler

. removeEventListener() - remove an event handler

 

<html>

  <head>

   <title>First HTML Page </title>

  </head>

  <body onclick="removeHandler()">Click</body>

   <div class="demo"></div>

   <script src = "./script.js"></script>

  </body>

</html>

  

//funcation firstFunction(){

// console.log("Hurray");  

//}

      

//let btn = document.querySelector("button")

// btn.addEventListener("click", firstFunction)

document.addEventListener("mousemovie", handler)

  

funcation handler(){

  document.querySelector(".demo").innerHTML = Math.random()  

}

  

     funcation removeHandler(){

  document.removeEventListener("mousemovie", handler)

}

   

    Event Propagation

Event Propagation explains the order in which events are received on the page from

the element where the event occurs and propagated through the DOM tree.

There are two main event modles

 

1. Event bubbling

2. Event Capturing

Event Bubbling

In the event bubbling model, an event starts at the most specific element and then 

flows upward toward the least specific element(the document or event window)

     

Element Button

Element div

Element body

Element html

Document

 

<html>

  <head>

    <title> First HTML Page </title>

  </head>

   <form onclick="alert('i am form')">

      I am form 

  <div onclick="alert('i am div')">

   <p onclick="alert('i am p')"> I am p </p>

  </div>

   </form>

</html>

  

   Custom Event

   

   In javaScript we can create our own custom event using CustomEvent

   Constructor

   

    Syntax

new customEvent("eventName",{options})

 

Example

                         ||                             Event name

             element.dispatchEvent( new customEvent ("hello",{

  detail : {name:"giri"} (detail property used to pass data)

  })),

  

  

     <html>

  <head>

   <title>First HTML Page  </title>

  </head>

  <body onclick="callcustommethod()">

   Click

  </body>

</html>

  

      js

  

   document.addEventListener("hello",funcation(data){

    console.log("hello has called and send" + data.detail)

   })

  

  funcation callcustommethod(){

   let event =  new customEvent("hello", {

detail: {"giri"}

})

document.dispatchEvent(event)

  }

  

Arrow Function

 

Arrow funcation allow us to write shorter funcation syntax

 

Example

 

funcation getName() {           ---> getName = () => {     --->  getName = () => "giri"

  return "giri"                          return "giri"

  }                                         }

  Normal funcation                Arrow funcation with return       Arrow funcation without return

  

  

  Benefits of Arrow functions

  

  Arrow syntax automatically binds this to the surrounding code's contex

  

<html>

<head>

<title> Arrow Function </title>

</head>

<body>

</body>

</html>

  

    // Arrow Function

funcation sum(data){

  let sum = data+10

  return sum

}

abc()

const sum  = data => {

let sum = data+10

return sum

}

console.log(sum(4,5))

 

const sum  = (data1, data2) => {

  let sum = data1+data2+10

  return sum

}

console.log(sum(4,5))

 

 var arr = [1,2,3,4]

 let newArr = arr.map(item)=>item*2)

 console.log(newArr)

 

 let obj = {

      name:"nikhil",

  getName:funcation(){

   console.log(this.name)

   funcation fullname(){

    console.log(this.name)

    console.log("my full name is" + this.name + "karan")

   }

    fullname()

  }

  }

  console.log(obj.getName())

  

  let obj = {

      name:"nikhil",

  getName:funcation(){

   console.log(this.name)// slip to the 

   cons  fullname =() => {

    console.log(this.name)

    console.log("my full name is" + this.name + "karan")

   }

    fullname()

  }

  }

  console.log(obj.getName())

  

  setTimeout

   The setTimeout() is  a method of the window object. The setTimeout() sets a timer

   and executes a callback function after the time expires 

   

   

   setInterval

   The setInterval() is a method of the window object. The setInterval() 

   repeatedly calls a function with a fixed delay between each call 

   

   

   .js

   

    let timeid = windows.setTimeout(function(){

console.log("hello")

},2000)

console.log(timeid)

 

// setInterval

 

let intervalId = window.setInterval(function(){

  console.log("hello")

}, 5000)

No comments:

Post a Comment