Skip to content

Instantly share code, notes, and snippets.

View suhailgupta03's full-sized avatar
:octocat:

Suhail Gupta suhailgupta03

:octocat:
View GitHub Profile
// closure is a function having access to the parent
// scope
function greet() {
var message = "Good evening";
function sayHi() {
console.log(message);
} // Here closure is created,
// sayHi function has access to message variable
// setInterval(function() {
// console.log("Playing MP4");
// },500); // continuous loop
// // every 500 ms, it will print "Playing MP4"
setTimeout(function() {
console.log("Downloaded MP4");
}, 3000); // 3s
setInterval(function() {
console.log("Playing MP4");
}, 1000);
// the first argument is the callback
// function
// the reason we call it as a callback
// function is because it is called back
// after a certain time interval
console.log(x);
var x = 1;
// Here x is undefined
// because JavaScript hoists declarations
// which means that the declaration is
// automatically moved to the top of
// the current scope
greet();
// greet function is hoisted
function calculator(operation, a, b) {
if(operation == "add") {
return a + b;
}else if(operation == "subtract") {
return a - b;
}else if(operation == "multiply") {
return a * b;
}else if(operation == "divide") {
return a / b;
}else {
let numbers = [100, 0, 99, -1, 999, 4]
let sorted = numbers.sort((a, b) => a - b); // by default sort sorts in ascending order
// when a - b > 0, this means a > b, so a should be after b
// which means that larger number a should be after smaller number b
console.log(sorted)
let sortedDesc = numbers.sort((a, b) => b - a); // sort in descending order
// when b - a > 0, this means b > a, so b should be after a
// which means that larger number b should be after smaller number a
let i = 0;
function greet() {
i++;
console.log("Hello, World! ", i);
if( i >= 500) {
return;
} // it is very important to have a base case
// if you do not have a base case, you will
// have an infinite loop
// IIFE
// Immediately Invoked Function Expression
(function() {
var x = ".."
var y = "...."
var z = "......"
console.log(x)
console.log(y)
console.log(z)
// function sum(a, b) {
// return a + b;
// }
// const x = function sum(a, b) {
// return a + b;
// } // function expression
// // because it is assigned to a variable
const x = function (a, b) {
// function sum(a, b) {
// return a + b;
// }
// let v = sum(99, 1);
// console.log(v);
var x = function sum(a, b) {
return a + b;
} // x is a function
// the reason x is a function is because it is a