Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save karkranikhil/c06cadca373aceffcd54a30a01ae7bad to your computer and use it in GitHub Desktop.

Select an option

Save karkranikhil/c06cadca373aceffcd54a30a01ae7bad to your computer and use it in GitHub Desktop.
/***Dates */
//JavaScript counts months from 0 to 11. January is 0. December is 11.
new Date()
// new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date(2018, 11, 24, 10, 33, 30, 0); // month is 0 -11
// new Date(milliseconds)
var d = new Date(86400000);
// JavaScript stores dates as number of milliseconds since January 01, 1970, 00:00:00 UTC (Universal Time Coordinated).
// new Date(date string)
var d = new Date("October 13, 2014 11:13:00");
// Date methods
var d = new Date(1950, 11,24)
d.getFullYear()
d.getYear()
d.getMonth()
d.getDate()
d.getDay() // 0-6 sunday to saturday
//set year
d.setYear("2020")
/******Array syntax *********/
// 1) Array literal
var stringArray = ["one", "two", "three"];
var numericArray = [1, 2, 3, 4];
var decimalArray = [1.1, 1.2, 1.3];
var booleanArray = [true, false, false, true];
var mixedArray = [1, "two", "three", 4];
// 2) Array constructor
var stringArray = new Array();
stringArray[0] = "one";
var numericArray = new Array(3);
numericArray[0] = 1;
numericArray[1] = 2;
numericArray[2] = 3;
var mixedArray = new Array(1, "two", 3, "four");
/********************Array Methods************************* */
var x = ["a", "b","c", "d"]
//Adds one or more elements at the end of an array and returns the new length of the array
x.push("e")
//Removes the last element from an array and returns that element.
x.pop()
//remove the first element and return that element
x.shift()
//add the element to the front of an array and return new array length
x.unshift("a")
//reverse the elements of an array
x.reverse()
//adds and remove elements from an array
x.splice(1,1) // what position add or remove, number of item to be removed
x.splice(1,0, "hurray") //adding at index 1
x.indexOf("c") // index start from 0
// lastIndexOf - Returns the index of the last occurrence of the specified element in the array, or -1 if it is not found.
var x = ["d", "a", "b","c", "d"]
x.lastIndexOf("d")
// join - Returns string of all the elements separated by the specified separator
x.join('')
x.join('$')
/****Slice() ****/
// Returns a new array with specified start to end elements.
var arr = ["1", "2", "3", "4", "5"];
var newArr = arr.slice(1, 3); // start index and the end index but end index is not included while remove
/***concat */
//Returns new array by combining values of an array that is specified as parameter with existing array values
var x = ["a", "d", "b","c", "d"]
var y = [1,2,3,4]
var z = x.concat(y)
/*****Maps */
var x = [
{name:"a", age:10},
{name:"b", age:40},
{name:"c", age:20},
{name:"d", age:9},
]
//loop over the array and return new array based on the value return.
x.map(function(currItem, index, actualArr){
return {"key":currItem.name, "value":currItem.age}
})
/*** every */
//return true or false if every element in the array satisfy the condition
x.every(function(currItem, index, actualArr){
return currItem.age>8
})
/****Filter *****/
//return new array with all the elements that satisfy the condition
x.filter(function(currItem, index, actualArr){
return currItem.age>=20
})
/***Some ***/
//return true if at least one element in the array satisfy the cocndition
x.some(function(currItem, index, actualArr){
return currItem.age>20
})
/****Sort */
// ascending order:
// sort the elements of an array
x.sort(function(a,b){
return a.age - b.age
})
//decending order
x.sort(function(a,b){
return b.age - a.age
})
// sort for string asending
x.sort(function(a,b){
return (a.name > b.name) ? 1 : (a.name < b.name) ? -1 : 0;
})
// sort for decending
x.sort(function(a,b){
return (a.name < b.name) ? 1 : (a.name > b.name) ? -1 : 0;
})
/**reduce */
//this method reduces the array to a single value ( left to right)
// The initialValue, or the previously returned value of the function
var numbers = [10,30,50]
var sum = numbers.reduce(function(total, curr, index, actualArr) {
console.log("total", total)
console.log("current value is ", curr)
return total+ curr;
}, 0)
var sum = numbers.reduceRight(function(total, curr, index, actualArr) {
console.log("total", total)
console.log("current value is ", curr)
return total+ curr;
}, 0)
/********** Looping ********************/
//looping
//1. for loop
var alphabets = [
{ name: 'A' },
{ name: 'B' },
{ name: 'C' },
{ name: 'D' }
]
//for (initialization; condition; iteration)
for (let i = 0; i < alphabets.length; i++) {
console.log("alphabet is ", alphabets[i].name);
}
//2. forEach
alphabets.forEach(function (currItem, index, actualArr) {
console.log("alphabet is ", currItem.name)
})
//when to use forEach over for loop
for (let i = 0; i < alphabets.length; i++) {
console.log("alphabet is ", alphabets[i].name);
if (alphabets[i].name === 'A') {
break;
}
}
// for of loop in es6
for (let alphabet of alphabets) {
console.log("alphabet is ", alphabet.name)
if (alphabet.name === 'A') {
break;
}
}
// for in loop
// This loop is use to iterate over the properties of an object
let oldCar = {
make: 'Toyota',
model: 'Tercel',
year: '1996'
};
for (let key in oldCar) {
console.log(`${key} --> ${oldCar[key]}`);
}
//while loop
// use while loops when testing for a condition before the first iteration of the loop
var a = 0
while (a < 10) {
console.log("The number is " + a)
a++;
}
// do while
//Use do…while when testing for a condition that is found AFTER the first iteration of the loop.
var numb
do {
let input = prompt(`Please enter a number between 1 and 10`);
numb = parseInt(input);
}
while (numb < 10);
// The 'for' loop used only when we already knew the number of iterations.
// The 'while' loop used only when the number of iteration are not exactly known.
/*****Scope ****/
//1. Scope determines the accessibility of variables, objects, and functions from different parts of the code.
//1. Blocks and scope
// as we have seen blocks before in front of functions and if{}
// Blocks help us group one or more statements together and serves as an important structural maker for our code
function logColor(){
let color = 'blue';
console.log(color); // blue
};
logColor()
// block in if statement
if (true) {
let color = 'pink';
console.log(color); // pink
};
console.log(color); // reference error
//2. Global Scope
//In global scope, variables are declared outside of blocks.These variables are called global variables.
//Because global variables are not bound inside a block, they can be accessed by any code in the program, including code in blocks.
var color = 'blue'
function returnSkyColor(){
return color; // blue
};
console.log(returnSkyColor());
//3. Scope pollution is when we have too many global variables that exist in the global namespace, or when we reuse variables across different scopes.Scope pollution makes it makes it difficult to keep track of our different variables and sets us up for potential accidents.
let num = 50;
function logNum() {
num = 100; // Take note of this line of code
console.log(num);
};
logNum(); // Prints 100
console.log(num); // Prints 100
/************Hoisting************** */
// Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope.
/**variable hoisting */
//Variables within a global scope are hoisted to the top of the scope.
console.log(hoist); // Output: undefined
var hoist = 'hello';
/**function scoped variable */
function hoistFun() {
console.log(message);
var message = 'Hello hoisting'
}
hoistFun();
/**hosting of function expression */
console.log(definitionNotHoisted());//error
var definitionNotHoisted = function () {
console.log("Definition not hoisted!");
};
/***strict mode */
//variable declaration is important
"use strict";
x23 = 3.14;
//deleteing
"use strict";
var x = 3.14;
delete x;
// Duplicating a parameter name is not allowed:
"use strict";
function x(p1, p1) {};
/*****Tricky questions ***/
var variable = 10;
function test() {
console.log(variable);
var variable = 20;
console.log(variable);
}
test() // undefined 20
var variable = 10;
function test() {
console.log(variable);
variable = 20;
console.log(variable);
}
test() // 10 , 20
var variable = 10;
function test() {
variable_3 = 35;
console.log(variable_3);
var variable_3 = 45;
variable_2 = 15;
console.log(variable);
}
test()
console.log(variable_2);
console.log(variable_3);
var variable = 30;
// 35 10 15 variable_3 is not defined
/***************this keywords*********************** */
// 1) in a method this refer to the owner of the method
var person = {
firstName: "Nikhil",
lastName : "Karkra",
id : 1,
getFullName : function() {
console.log(this)
return this.firstName + " " + this.lastName;
}
};
// 2) This alone is global
this === window
// 3) this in a function represent the object that own the function
function myFunction() {
console.log(this);
}
myFunction()
// in an event, this refers to the element that received the event.
<button onclick="abc(this)">
click
</button>
function abc(e){
console.log(e)
}
//Explicit Function Binding
var person = {
firstName: "Nikhil",
lastName : "Karkra",
id : 1,
getFullName : function() {
console.log(this)
return this.firstName + " " + this.lastName;
}
};
var person1 = {
firstName:"salesforce",
lastName: "dev",
}
person.getFullName.call(person1); //call(this, argument1, argument2) pass argument to function
// call with parameters
var person = {
firstName: "Nikhil",
lastName : "Karkra",
id : 1,
getFullName : function(a, b) {
console.log(this)
return this.firstName + " " + this.lastName + " " + a + ' ' + b;
}
};
var person1 = {
firstName:"salesforce",
lastName: "dev",
}
person.getFullName.call(person1, "A", "B");
// person.getFullName.apply(person1, ["A", "B"]);
//The call() method takes arguments separately.
// The apply() method takes arguments as an array.
/**********Functions in javascript******* */
/*************FUnctions**************** */
//Function Declarations
function func(a, b) {
return a * b;
}
func(2,3)
//Function Expressions
var x = function (a, b) {return a * b};
x(2,3)
// function constructor
var func = new Function("a", "b", "return a * b");
func(4, 3);
// An Immediately-invoked Function Expression is a way to execute functions immediately, as soon as they are created.
// IIFEs are very useful because they don't pollute the global object, and they are a simple way to isolate variables declarations
(function(a, b) {
return a * b
})(2,3)
/******Closures *****/
function outer() {
var counter = 0;
return function inner() {counter += 1; return counter}
}
var counter = outer()
counter()
/******Object Destructuring *****/
var employee = {
firstName: "Nikhil",
lastName: "Karkra",
position: "Developer",
yearHired: 2017
};
var firstName = employee.firstName;
var lastName = employee.lastName;
var position = employee.position;
var yearHired = employee.yearHired;
//If we use object destructuring it looks cleaner and takes a little time than the old way. The syntax for object destructuring is that if we are getting properties in an object we use the {} and inside that, we specify the properties we want to extract and if we are getting data from an array we use the [].
let { position = "eng", lastName } = employee
/*****Array destructuring ******/
var arr = ["A", "B", "C"]
var [first, second, third, fourth="D"] = arr
// You cannot use Numbers for destructuring.Numbers will throw an error because numbers cannot be variable names
//************Object.freeze****************** */
// It makes an object immutable, i.e. you cannot change its properties.
const person = {
name: "john"
};
Object.freeze(person);
person.name ="nik"
person.age="23" // can't add new property
delete person.name // can't delete
/****Object Prototype and Prototype chain */
// prototype is a property of a function constructor
// __proto__ is a property of a instance created from constructor
//The prototype is an object that is associated with every functions and objects by default in JavaScript unless u create a null object
var o = Object.create(null)
var o = {id:42, name:"nikhil"}
var a = ['john']
function Entity(id, name){
this.id = id;
this.name = name;
}
/****Prototype *****/
// JavaScript is a dynamic language. You can attach new properties to an object at any time as shown below.
var user1 ={
firstName:'nikhil',
lastName:"karkra",
age:23,
grade:'a',
getFullName: function(){
return this.firstName + ' '+ this.lastName
}
}
var user2 ={
firstName:'john',
lastName:"doe",
age:29,
grade:'a',
getFullName: function(){
return this.firstName + ' '+ this.lastName
}
}
var user3 ={
firstName:'steve',
lastName:"smith",
age:20,
grade:'b',
getFullName: function(){
return this.firstName + ' '+ this.lastName
}
}
// will create an constructor function that will act as a blue print
var Person = function(firstName, lastName, age, role){
this.firstName = firstName
this.lastName = lastName
this.age = age
this.role= role
this.getFullName= function(){
return this.firstName + ' '+ this.lastName
}
}
var user1 = new Person("nikhil", "karkra", 23, 'engineer')
var user2 = new Person("john", "doe", 29, 'doctor')
user1.getFullName()
// but if we have 100 function with 100 lines on each function each copy will not be efficient in term of performance
// The prototype is an object that is associated with every functions and objects by default in JavaScript
var Person = function(firstName, lastName, age, role){
this.firstName = firstName
this.lastName = lastName
this.age = age
this.role= role
}
Person.prototype.getFullName= function(){
return this.firstName + ' '+ this.lastName
}
var user1 = new Person("nikhil", "karkra", 23, 'engineer')
var user2 = new Person("john", "doe", 29, 'doctor')
user1.getFullName()
user2.getFullName()
/*****Prototypal inheritance */
// Portotypal inheritance
function Animal(name, age){
this.name=name
this.age = age
}
Animal.prototype.eats= function(){
console.log(this.name + ' is eating')
}
var animal1 = new Animal("animal1", 23)
function Dog(name, age, breed){
this.breed = breed
// this.name
// this.age
Animal.call(this, name, age)
this.logBreed = function(){
console.log(this.name + 'is a' + this.breed)
}
}
Dog.prototype = Object.create(Animal.prototype)
console.log(Dog.eats())
var d2 = new Dog("d1", 2, "bulldog")
d2.eats()
/***********Classes and class inheritance ********/
// Class is a blueprint in which we can define properties and behaviours
class Animal1{
constructor(name, age){
console.log(name + 'is an animal and was created')
this.name = name
this.age = age
}
static iAmAStaticMethod(){
console.log('I am a static method inside of an Animal class')
}
eats(){
console.log(this.name + ' is eating')
}
sleep(){
console.log(this.name + ' is sleepin')
}
logAge(){
console.log(this.name + ' is '+ this.age + ' year old')
}
}
// constructor is the method that get invoked everytime a instance of the class gets created
var animal1 = new Animal1("animal1", 2)
animal1.eats()
animal1.sleep()
// inheritance means we can have common class and extends the properties and behaviours from that classes
class Dog1{
constructor(breed){
this.breed = breed;
}
logBreed(){
console.log(this.breed)
}
}
var dog1 = new Dog1('Bulldog')
dog1.logBreed()
// now if we want to pull the properties of Animal we use extends
class Dog1 extends Animal{
constructor(name, age, breed){
super(name, age) // super call the super constructor which will take care of assigning of name and age
this.breed = breed;
}
logBreed(){
console.log(this.name + 'is a' + this.breed)
}
logDogAge(){
super.logAge()
}
}
var dog1 = new Dog1('Dog1', '4', 'Bulldog')
dog1.logBreed()
dog1.logDogAge()
// The JavaScript provides static methods that belong to the class instead of an instance of that class. So, an instance is not required to call the static method. These methods are called directly on the class itself.
class Test
{
static display()
{
return "static method is invoked"
}
}
// The static keyword is used to declare a static method.
// The static method can be of any name.
// A class can contain more than one static method.
// If we declare more than one static method with a similar name, the JavaScript always invokes the last one.
// The static method can be used to create utility functions.
// We can use this keyword to call a static method within another static method.
// We cannot use this keyword directly to call a static method within the non-static method. In such case, we can call the static method either using the class name or as the property of the constructor.
/*******Decorator******* */
http://jsfiddle.net/wcrowe/o5owvteL/
class Greet {
@readonly
greeting() {
return `hello.`;
}
}
const greet = new Greet();
console.log(greet.greeting());
function readonly(target, name, descriptor) {
descriptor.writable = false;
return descriptor;
}
greet.greeting = ()=>"hurray"
console.log(greet.greeting());
// function target, name, and descriptor as arguments
//A higher-order function is a function that can take another function as an argument, or that returns a function as a result
// target - The target is the target constructor.
// The name is simply the name of the method
// The descriptor is describes either the data or an accessor.
// configurable - can modify
// writable - can assign
// enumerable - show in for in loop
https://stackblitz.com/edit/react-k6szm7?file=utils.js
// Named export
export const programmingList = ["Svelte", "React", "Vue","Angular"]
export const helloSvelteHandler = ()=>{
return "Hello Svelte"
}
export const bookDetails = {
name: "Salesforce JS series",
author: "Nikhil Karkra"
}
// export together
const programmingList = ['Svelte', 'React', 'Vue', 'Angular']
const helloSvelteHandler = () => {
return "Hello Svelte"
}
const bookDetails = {
name: 'Svelte 3',
author: 'Nikhil Karkra'
}
export { programmingList, helloSvelteHandler, bookDetails }
// default export
export default {
}
import UTILS from './utils.js'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment