Friday, July 2, 2021

JavaScript Cheatsheet

let – block-scoped var – function-scoped === NEVER USE!!!

Prefer const userNa = and template literal `I ${userNa} pay ${bill + tip}`; No need for \n === newline in ` `. const value can be changed in array. only primitive const value  is immutable

Use ===, !==. Do not use ==, !=

'Let\'s go!' // with ' ' escaping with \ should be used

'Tommy is ' + age + ' years old.';  // String concatenation

`Tommy is ${age} years old.`; // String interpolation


https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/JavaScript_basics

Data types: Number (always float 10.0, 5.0), String, Boolean, Null, Undefined, BigInt (integers Number can't use) // check type with typeof

type conversion – manual conversion

type coercion – automatic covenrsion by JS – AVOiD!!!

Number(constName): converts string to number but original value still be a string

String(constName)

NaN – Not a Number === invalid number


Falsy values: 0, ' ', undefined, null, NaN converted to Boolean(constName); others are truethy


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

Arithmetic operators: + addition – subtraction * multiplication / division ** exponentiation // 2 ** 3 === 2 * 2 * 2

% modulo (remainder operator) returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.

console.log(12 % 5); // expected output: 2 console.log(-12 % 5); // expected output: -2

console.log(4 % 2); // expected output: 0 console.log(-4 % 2); // expected output: -0


Assignment operator: assigns a value to its left operand based on a value of its right operand:

+= addition assignment // x += 10 === x = x + 10

-= subtraction assignment // x -= 10 === x = x - 10

*= multiplication assignment // y *= 10 === y = y * 10

/= division assignment y /= 10 === y = y / 10

x++ // x = x + 1

x-- // x = x -1


Comparison operators: === strict equal !== strict not equal > greater than >= greater than or equal < less than <= less than or equal


Logical Operator ! (NOT) precedes OR/AND

let lateToWork = true;

let oppositeValue = !lateToWork;

console.log(oppositeValue);


Logical Operator || (OR)

false || false;       // false

10 > 5 || 10 > 20;    // true

true || false;        // true!!!

10 > 100 || 10 > 20;  // false

Has short-circuiting!!!


Logical Operator && (AND)

true && true;      // true

1 > 2 && 2 > 1;    // false

true && false;     // false!!!

4 === 4 && 3 > 1;  // true

Has short-circuiting!!!


Nullish coalescing operator ??

const foo = null ?? 'default string';

console.log(foo); // expected output: "default string"


const baz = 0 ?? 42;

console.log(baz); // expected output: 0

// Nullish values: null, undefined

optional chaining operator ?.

const adventurer = {

  name: 'Alice',

  cat: {

    name: 'Dinah'

  }

};

const dogName = adventurer.dog?.name; // if dog exists than output name

console.log(dogName); // expected output: undefined

console.log(adventurer.someNonExistentMethod?.()); // expected output: undefined


Conditional or Ternary Operator ? :

let price = 10.5;

let day = "Monday";

day === "Monday" ? price -= 1.5 : price += 1.5;


if Statement

const isMailSent = true;

if (isMailSent) {

  console.log('Mail sent to recipient');

}


else Statement

const isTaskCompleted = false;

if (isTaskCompleted) {

  console.log('Task completed');

} else {

  console.log('Task incomplete');

}


else if Clause

const size = 10;

if (size > 100) {

  console.log('Big');

} else if (size > 20) {

  console.log('Medium');

} else if (size > 4) {

  console.log('Small');

} else {

  console.log('Tiny');

}


switch Statement

const food = 'salad';

switch (food) {

  case 'oyster':

    console.log('The taste of the sea 🦪');

    break;

  case 'pizza':

    console.log('A delicious pie 🍕');

    break;

  default:

    console.log('Enjoy your meal');

}


Expression – code that produces value

// 3+4 // 1991 // true && false && !false

Statement – big code which do not produce value; program === sequence of actions or statements. Statements consist expressions.


Method - functions attached to object: push, pop, shift, unshift…


Function – reusable piece of code.

Built-in functions: console.log, console.table,  debugger; alert, prompt

Function parameters are the names listed in the function definition.

Function arguments are the real values passed to (and received by) the function.

https://www.w3schools.com/js/js_function_parameters.asp

=> Arrow Functions (ES6)

NEVER use => as method!!! => uses this keyword from parent scope!!!

Old-fashioned arguments keyword is not available in arrow functions!!!

Use regular functions as methods with this keyword!!!


=> Arrow function with two arguments 

const sum = (firstParam, secondParam) => { 

  return firstParam + secondParam; 

}; 

console.log(sum(2,5)); // Prints: 7 

 

=> Arrow function with no arguments 

const printHello = () => { 

  console.log('hello'); 

}; 

printHello(); // Prints: hello

 

=> Arrow functions with a single argument 

const checkWeight = weight => { 

  console.log(`Baggage weight : ${weight} kilograms.`); 

}; 

checkWeight(25); // Prints: Baggage weight : 25 kilograms.

 

=> Concise arrow functions

const multiply = (a, b) => a * b; 

console.log(multiply(2, 30)); // Prints: 60 


// Anonymous function

const rocketToMars = function() {

  return 'BOOM!';

}

// Named function

function rocketToMars() {

  return 'BOOM!';

}


// Function Expressions

const dog = function() {

  return 'Woof!';

}


// Function Parameters

function sayHello(name) {

  return `Hello, ${name}!`;

}


return Keyword

Functions return (pass back) values using the return keyword. return ends function execution and returns the specified value to the location where it was called. Forget the return keyword === return undefined.

// With return

function sum(num1, num2) {

  return num1 + num2;

}

// Without return, no output of sum

function sum(num1, num2) {

  num1 + num2;

}


Function Declaration

function add(num1, num2) {

  return num1 + num2;

}


Calling Functions

// Defining the function

function sum(num1, num2) {

  return num1 + num2;

}

// Calling the function

sum(2, 4); // 6

Functions Assigned to Variables

let plusFive = (number) => {

  return number + 5;  

};

// f is assigned the value of plusFive

let f = plusFive;

plusFive(3); // 8

// Since f has a function value, it can be invoked. 

f(9); // 14


Callback Functions

const isEven = (n) => {

  return n % 2 == 0;

}

let printMsg = (evenFunc, num) => {

  const isNumEven = evenFunc(num);

  console.log(`The number ${num} is an even number: ${isNumEven}.`)

}

// Pass in isEven as the callback function

printMsg(isEven, 4); 

// Prints: The number 4 is an even number: True.


Higher-Order Functions

In Javascript, functions can be assigned to variables in the same way that strings or arrays can. They can be passed into other functions as parameters or returned from them as well. A “higher-order function” is a function that accepts functions as parameters and/or returns a function.


Data structures 

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Arrays 

// An array containing numbers

const numberArray = [0, 1, 2, 3];

// An array containing different data types

const mixedArray = [1, 'chicken', false];


Property .length

const numbers = [1, 2, 3, 4];

numbers.length // 4


Index

// Accessing an array element

const myArray = [100, 200, 300];

console.log(myArray[0]); // 100

console.log(myArray[1]); // 200

console.log(myArray[2]); // 300


Method .push()

// Adding a single element:

const cart = ['apple', 'orange'];

cart.push('pear'); 

// Adding multiple elements:

const numbers = [1, 2];

numbers.push(3, 4, 5);


Method .pop()

const ingredients = ['eggs', 'flour', 'chocolate'];

const poppedIngredient = ingredients.pop(); // 'chocolate'

console.log(ingredients); // ['eggs', 'flour']


Method .shift()

Method .unshift()

.includes()  better than .indexOf()

.indexOf()


Objects

console.log(object.propertyName);

console.log(object['propertyName'];

const nameKey = 'Name';

console.log(object['last' + nameKey]; === console.log(object.lastName);


object.property = 'Value'; // adding to object with dot notation

object['property'] = 'Value';// adding to object with brackets


function attached to object is called method === property holding value


Delete operator

const person = {

  firstName: "Matilda",

  age: 27,

  hobby: "knitting",

  goal: "learning JavaScript"

};

delete person.hobby; // or delete person[hobby];

console.log(person);

/*

{

  firstName: "Matilda"

  age: 27

  goal: "learning JavaScript"

}

*/

JavasSript passing objects as arguments

When JavaScript objects are passed as arguments to functions or methods, they are passed by reference, not by value. This means that the object itself (not a copy) is accessible and mutable (can be changed) inside that function.

const origNum = 8;

const origObj = {color: 'blue'};

const changeItUp = (num, obj) => {

  num = 7;

  obj.color = 'red';

};

changeItUp(origNum, origObj);

// Will output 8 since integers are passed by value.

console.log(origNum);

// Will output 'red' since objects are passed 

// by reference and are therefore mutable.

console.log(origObj.color);


destructuring

const arr = [2, 4, [8, 9]]; // array to be destructured

const [a, , [c, d]] = arr; // skipping second element 4

console.log(a, c, d);

// default values possible

const { name, hr, place } = objectName; // object data to be destructured

console.log(name, hr, place); // destructured variables

// default values possible

const { name: nameName, hr: herHR, place: placePlace } = objectName; // variables with new names


... spread operator syntax // extracts all values from iterables

Iterables: arrays, strings, maps, sets, but NOT objects

function sum(x, y, z) {

  return x + y + z;

}

const numbers = [1, 2, 3];

console.log(sum(...numbers)); // expected output: 6

console.log(sum.apply(null, numbers)); // expected output: 6

... spread operator can be used for creating objects, arrays, passing values into functions

// ... spread operators is used when there is need to write values separated by comma

// ... rest operator is used when there is need to write variable names separated by comma

... rest operator // packs all values into array

const [a, b, ...others] = [1, 2, 3, 4, 5]; // rest elements will be included in others array

console.log(a, b, others);


const {a, ...data } = obj.database;

console.log(database);


for...of statement creates a loop iterating over iterable objects.

for (variable of iterable) {

  statement

}


loop runs while condition is true


For Loop

for (let i = 0; i < 4; i += 1) {

  console.log(i);

};


Nested For Loop

for (let outer = 0; outer < 2; outer += 1) {

  for (let inner = 0; inner < 3; inner += 1) {

    console.log(`${outer}-${inner}`);

  }

}

/* 


While Loop

while (condition) {

  // code block to be executed

}

let i = 0;

while (i < 5) {        

  console.log(i);

  i++;

}


Reverse Loop

const items = ['apricot', 'banana', 'cherry'];

for (let i = items.length - 1; i >= 0; i -= 1) {

  console.log(`${i}. ${items[i]}`);

}

// Prints: 2. cherry

// Prints: 1. banana

// Prints: 0. apricot


Do…While Statement

x = 0

i = 0

do {

  x = x + i;

  console.log(x)

  i++;

} while (i < 5);


JavaScript for...in loop

The JavaScript for...in loop can be used to iterate over the keys of an object. In each iteration, one of the properties from the object is assigned to the variable of that loop.

let mobile = {

  brand: 'Samsung',

  model: 'Galaxy Note 9'

};

for (let key in mobile) {

  console.log(`${key}: ${mobile[key]}`);

}


break keyword

for (let i = 0; i < 99; i += 1) {

  if (i > 5) {

     break;

  }

  console.log(i)}

break completely terminates loop


continue keyword

for (let i = 0; i < array.length; i +=) {

  if (typeof i  !== 'string')  continue; 

     console.log(array[i], typeof array[i]);

  }

continue exits iteration


JavaScript engine V8 workflow:

parsing -> compilation -> execution

parsing = reading code and creating abstract syntax tree (AST), checking for errors; compilation is just-in time


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

https://hackr.io/blog/javascript-cheat-sheet

https://websitesetup.org/javascript-cheat-sheet/

https://www.interviewbit.com/javascript-cheat-sheet/

No comments:

Post a Comment