Skip to content

Instantly share code, notes, and snippets.

@marta-krzyk-dev
Last active April 12, 2020 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marta-krzyk-dev/e1791d8ca6b74a85b3bf995db2b7a029 to your computer and use it in GitHub Desktop.
Save marta-krzyk-dev/e1791d8ca6b74a85b3bf995db2b7a029 to your computer and use it in GitHub Desktop.
Basic JavaScript ES6
// Array
array = new Array()
array[0] = "Zack";
array[1] = "Unicorn";
array.push('Parrot');
array[8] = "Unidolphin";
array.push('Parrot');
console.log("Array with undefined elements: " + array)
console.log("Non-existing array element: " + array[40])
array.pop()
array.pop()
array.push(['Ladybug','Ladybird'])
array.sort()
array.reverse()
console.log(array)
array2 = ["Love", "Peace"]
console.log("Concatted array: " + array2.concat(['Undestanding']))
console.log("Sliced array: " + array.slice(5,7))
console.log("Joined array: " + array2.join(" * "))
const myArray = [23,23,23]
myArray.push(3)
console.log(myArray)
myArray.pop()
console.log(myArray)
const myObject = { name: "Chris" }
console.log(myObject.name)
myObject.name = "Dolphin"
console.log(myObject.name)
[23, 23, 23, 3]
[23, 23, 23]
"Chris"
"Dolphin"
// Hoisting and functions
hoistedFunction();
const myName = "Chris";
hoistedFunction();
function hoistedFunction() {
if (!myName){
console.log(myName);
console.log("Hoisted Hi !!!" + myName);
}
console.log("Hoisted Hi " + myName);
}
var sayHi = function() {
if (!myName){
const myName = "BoB";
console.log("sayHi " + myName);
console.log("Hi !!!" + myName);
}
console.log("Hi " + myName);
}
sayHi();
sayHi();
/*
undefined
"Hoisted Hi !!!undefined"
"Hoisted Hi undefined"
"Hoisted Hi Chris"
"Hi Chris"
"Hi Chris"
*/
// Function expression
const squaredNumber = function(num) {
return num * num;
}
const numberAdder = function(squarer, num2) {
//squarer is a function expression!
return squarer(4) + num2;
}
console.log(numberAdder(squaredNumber,10))
const info = { name: "Chris", age: 31};
//This func will change the original :(
function changeAge(myObj){
myObj.age = 100;
}
console.log(info); //[object Object] {age: 31, name: "Chris"}
changeAge(info);
console.log(info); //[object Object] {age: 100, name: "Chris"}
const numbers = [1,2,3,4,5]
//This func will change the original :(
function addToArray(arr){
arr.push(6);
}
console.log(numbers); //[1, 2, 3, 4, 5]
addToArray(numbers);
console.log(numbers); //[1, 2, 3, 4, 5, 6]
// Nested functions == CLOSURES
function squareAndMultiply(num) {
const hey = "hey";
function squarer(x){
console.log(hey); //Closure can access variables from outer func but NOT VICE VERSA
return x * x;
}
return squarer(num) + num;
}
var x = squareAndMultiply(80);
console.log(x);
function formatter(name, surname, age) {
function formatNames(arg1, arg2) {
return arg1 + " " + arg2;
}
function dataFormatter(fullName, number) {
const formattedData = {
name: fullName,
age: number
}
return formattedData;
}
const n = formatNames(name, surname);
return dataFormatter(n, age);
}
console.log(formatter("Chris","Dolphin",88));
/*
"hey"
6480
[object Object] {
age: 88,
name: "Chris Dolphin"
}
*/
// ADVANCED FUNCTIONS
// THIS IS FUNCTION EXPRESSION
var sayHi = function() {
console.log("Hi!")
}
sayHi();
// ARROW FUNCTIONS - more concise way
var sayHi2 = () => {
console.log("Hi from arrow function!");
}
sayHi2();
const multiplier = (num1, num2) => {
return num1 * num2;
}
console.log(multiplier(3,5));
const users = [
{ name: "Chris", age : 60},
{ name: "Dolpih", age : 5},
{ name:"Parrot", age : 101}
];
//Built-in map func
users.map(function(user) {
console.log("map " + user.name)
});
const userNameList = users.map(function(user){
return user.name;
});
console.log(userNameList);
users.map((user) => {
console.log("arrow => " + user.name)
});
const userAgeList = users.map((user) => {
return user.age;
});
console.log(userAgeList);
//NORMAL VERSION
function mapUserNames(myArr){
const lista = myArr.map(function(user) {
return user.name + " =)";
});
return lista;
}
console.log(mapUserNames(users));
//ARROW VERSION
const mapUserNames2 = (myArr) => myArr.map((user) => user.name + " <3");
console.log(mapUserNames2(users));
//ONE LINERS DO NOT REQUIRE { }
const multiply = (x, y) => x * y;
console.log(multiply(5,5));
// DROP () if there's ONE PARAMETER
const square = num => num * num;
console.log(square(3));
// FILTER
const numbers2 = [1,2,3,4,5,6,7,8,9,10];
const filteredNumbers = numbers2.filter(function(num){
return num % 2 === 1;
});
console.log(filteredNumbers);
const filteredNumbersArray = numbers2.filter(num => num % 2 === 0);
console.log(filteredNumbersArray);
// FOR EACH - built-in function
const doubledNumbers = (num) => {
const numberContainer = [];
num.forEach((x) => numberContainer.push(x * 2));
return numberContainer;
};
// DEFAULT VALUES
const defaultNumber = 8;
const multiplier = (x=defaultNumber,y=1) => x*y;
console.log(multiplier());
console.log(multiplier(5));
console.log(multiplier(5,5));
// arguments is a reserved keyword in JS
function logAllArgs(x,y,z) {
console.log(arguments);
//get array of additional, unexpected arguments
const args = Array.prototype.slice.call(arguments, logAllArgs.length);
console.log("There are : " + args.sort());
};
logAllArgs(1,"x",false,9,8,7,5,6);
// REST PARAMETERS
function logAllArgs2(x, ...nums) {
console.log(nums); //nums is an array
console.log("There are " + nums.length + " ...rest arguments");
};
logAllArgs2(1,"x",false,9,8,7,5,6);
function multiplier(multi, ...nums) {
return nums.map( (x) => multi * x )
}
console.log(multiplier(100, 1,2,3));
// CONSTRUCTORS
// CREATE new version of a FUNCTION WITH NEW
function Dog(years, breed) {
this.age = years;
this.type = breed;
let that = this;
//Arrow function will inherit context from enclosing context. It will know this of the object
setInterval(() => {
console.log(that);
this.age += 1;
console.log(this)
}, 2000);
setInterval(function() {
console.log(that);
this.age += 1;
console.log(this); //This function will not inherit's constructor's context, it needs "that" variable
}, 2000);
}
const spike = new Dog(3, "Golden German Shephard");
const piesa = new Dog(2, "White Chihuahua");
function test() {
'use strict';
console.log(this); //in strick mode this is undefined, otherwise it's
}
test();
function sayHi() {
let shouldSayHi = true;
var reallySayHi = true;
if (shouldSayHi) {
let myName = 'Chris'; //let is scoped to the block
console.log("Hi " + myName + " " +shouldSayHi );
}
console.log("Hi " + myName + " " ); //Can't access let variables!
}
sayHi();
"Hi Chris true"
"error"
"ReferenceError: myName is not defined
at sayHi (muzemid.js:14:48)
at muzemid.js:17:1
at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:13924
at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:10866"
// Objects are key-value pair collections
// Object literal syntax
var myObject = {
1: "Chris",
2: "Dolphin",
3: "Parrot",
phone: {
mobile: "666-666-666",
home: "123-33-333"
}
}
console.log(myObject.phone['home'])
console.log(myObject['phone']['home'])
// Object syntax
newObject = new Object();
newObject['1'] = "Chris"
newObject['xRay'] = 'zray'
newObject['age'] = 17
console.log(newObject)
// Function
function sayHi() {
console.log("Hi")
}
var donut = {
type: "coconut",
glazed: true,
eat: function() {
console.log("Yummy!")
},
sayType: function() {
console.log("Type: "+ this.type)
}
}
donut.eat()
donut.sayType()
3-33-333"
"123-33-333"
[object Object] {
1: "Chris",
age: 17,
xRay: "zray"
}
"Yummy!"
"Type: coconut"
"Array with undefined elements: Zack,Unicorn,Parrot,,,,,,Unidolphin,Parrot"
"Non-existing array element: undefined"
[undefined, undefined, undefined, undefined, undefined, "Zack", "Unicorn", "Parrot", ["Ladybug", "Ladybird"]]
"Concatted array: Love,Peace,Undestanding"
"Sliced array: Zack,Unicorn"
"Joined array: Love * Peace"
true
3.141592653589793
"Convert from string to number via + notation: 2"
10
"s"
"Hello world!"
"I WANNA BE BIG"
"i wanna be small"
"true === true true"
"true == true true"
"null === false false"
"null == false false"
"Boolean(-1) = true"
"Boolean(0) = false"
"Unassigned variable: undefined type: undefined"
"Array is truthy true"
"Empty array is truthytrue"
"Undefined array is falsey false"
"null === undefined false"
"null == undefined true"
function fruitLogger(fruit) {
switch (fruit) {
//uses === for comparison
case "apple": console.log("It's an apple!"); return;
case "orange" : console.log("It's an orange!"); break;
case "candy":
case "fastfood":
console.log("Not good!"); break;
default: console.log("I dunno what it is " + myFruit); break;
}
}
const myFruit = "orange"
fruitLogger(myFruit)
//Types in JavaScript
// Numbers
console.log(isNaN(parseInt("jikj + 4")))
console.log(Math.PI)
console.log("Convert from string to number via + notation: " +( +"2"))
//String
console.log("superduper".length)
console.log("Piesa".charAt(3))
console.log("Hello" + " world" + "!")
console.log("i wanna be big".toUpperCase())
console.log("I WANNA BE SMALl".toLowerCase())
//Booleans
var t = true
console.log("true === true " + (t === true))
console.log("true == true " + (t == true))
t = null
console.log("null === false " + (t === false))
console.log("null == false " + (t == false))
console.log("Boolean(-1) = " + Boolean(-1))
console.log("Boolean(0) = " + Boolean(0))
var unassigned;
console.log("Unassigned variable: " + unassigned + " type: " + typeof(unassigned))
var array = [0, 0, 0]
console.log("Array is truthy " + Boolean(array))
var emptyArray = []
console.log("Empty array is truthy" + Boolean(emptyArray))
var uArray
console.log("Undefined array is falsey " + Boolean(uArray))
console.log("null === undefined " + (null === undefined))
console.log("null == undefined " + (null == undefined))
function sayHi() {
var shouldSayHi = true;
var reallySayHi = true;
if (shouldSayHi) {
var myName = 'Chris'; //This variable is scoped to the entire function
if (reallySayHi) {
var myLastName = "Smith"
}
}
/*
// Hoisting and functions
hoistedFunction();
const myName = "Chris";
hoistedFunction();
function hoistedFunction() {
if (!myName){
console.log(myName);
console.log("Hoisted Hi !!!" + myName);
}
console.log("Hoisted Hi " + myName);
}
var sayHi = function() {
if (!myName){
const myName = "BoB";
console.log("sayHi " + myName);
console.log("Hi !!!" + myName);
}
console.log("Hi " + myName);
}
sayHi();
sayHi();
*/
myName = 'Sally';
myLastName = 'Dolphin'
console.log("Hi " + myName + " " + myLastName); //I have access to myName variable , but I SHOUDLN'T!
}
sayHi()
console.log(myName) //Can't access it because it's in function's scope
/*"Hi Sally Dolphin"
"error"
"ReferenceError: myName is not defined
at muzemid.js:23:38
at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:13924
at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:10866"*/
@marta-krzyk-dev
Copy link
Author

2020-04-09_11h18_08

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment