var name = "Yasas Sandeepa";
console.log(name);
// var <- outdated
// next gen js-> let and const
// let for variables and const for constants
Functions
summerizeUser = (number) => {
console.log("ECMA Script 6 function");
return number + 1;
};
//console.log(summerizeUser(0));
---------- ES5 ----------
function getNum() {
return 10;
}
---------- ES6 ----------
const getNum = () => 10;
// function in a object
const person = {
name: "Max",
age: 29,
greet: () => {
console.log(this.name);
},
};
/*this greet function output as undefined-> refer the global variable (There is no any)
So if you need calling to a variable inside the object
call like this->
*/
greet () {
console.log(this.name);
},
person.greet();
Arrays
const hobbies = ["Sports", "Cooking"];
//for of loop <- new standard of ES6
// difference between for of and for in?
for (let hobby of hobbies) {
console.log(hobby);
}
//map - to trasnform value in arrays ==
//map always get a new array (not the existing one)
console.log(hobbies.map((hobb) => "Hobby :" + hobb));
//old array not changed
console.log(hobbies);
hobbies.push("newSport");
console.log(hobbies);
Spread And Rest
//spred => ... <- coping array to new array
const copyArray = [...hobbies];
console.log(copyArray);
//rest => ... (same operator) <-pushing data into array
(very flexible..we can pass any element to get an array)
const toArray = (...args) => {
return args;
};
console.log(toArray(1, 2, 3, 4, 5));
Destructuring
/* allows to extract only needed elements
pulled out of the incoming object
other properties will be dropped
stored in a variable
so we can use this directly
*/
const printName = ({ name, greet }) => {
console.log(name);
};
printName(person); <-passing the previous person object
//destructioring outside a function
const { name, age } = person;
console.log(name, age);
const [hobb1, hobb2] = hobbies;
console.log(hobb1, hobb2);
//bactic -> `
//With this syntax, you can dynamically add data into a string like this:
const sch = "RCG";
const old = 29;
console.log(`My Scholl is ${sch} and I am ${old} years old.`);
Asynchronous code
//DO not block the code //Used for http requests
//As named ->Callback function
setTimeout(() => {
console.log("Print when time is done (5 sec)");
}, 5000);
//Synchronous ones...>
// executes with no problem
console.log("printing this after the set time out..");
//how to set a counter that executes 1 sec?
//<div id='seconds-counter'> </div> <- html element
var seconds = 0;
var el = document.getElementById('seconds-counter');
function incrementSeconds() {
seconds += 1;
el.innerText = "You have been here for " + seconds + " seconds.";
}
var cancel = setInterval(incrementSeconds, 1000);
Promises
looking forward to it
const fetchData = () => {
console.log("Fetching Started");
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Done..!");
}, 7000);
});
return promise;
};
fetchData().then((text) => {
console.log(text);
});

0 Comments