Javascript

Javascript

Tutorials

Javascript tutorial

Destructuring objects

Arrow Functions

Basics

variables

let variable = value

let user = 'John', age = 25, message = 'Hello';

constants

const constant = value

const myBirthday = '18.04.1982';

There is a widespread practice to use constants as aliases for difficult-to-remember values that are known prior to execution. .. const COLOR_RED = “#F00”; const COLOR_GREEN = “#0F0”;

Datatypes

Number

let n = 123;
n = 12.345;

NaN represents a computational error

BigInt

Added to represent integers of arbitrary length.

// the "n" at the end means it's a BigInt
const bigInt = 1234567890123456789012345678901234567890n;

String

let str = "Hello";
let str2 = 'Single quotes are ok too';
let phrase = `can embed another ${str}`;

there is no Character type in js

Boolean

let nameFieldChecked = true; // yes, name field is checked
let ageFieldChecked = false; // no, age field is not checked

Conversions

Values that are intuitively “empty”, like 0, an empty string, nullundefined, and NaN, become false, other values become true.

alert( Boolean(1) ); // true
alert( Boolean(0) ); // false
alert( Boolean("hello") ); // true
alert( Boolean("") ); // false

null/undefined

null is not a “reference to a non-existing object” or a “null pointer” undefined is “value is not assigned”.

typeof

typeof operator returns the type of the argument

It supports two forms of syntax, as operator: typeof x and as a function: typeof(x).

typeof undefined // "undefined"
typeof 0 // "number"
typeof 10n // "bigint"
typeof true // "boolean"
typeof "foo" // "string"
typeof Symbol("id") // "symbol"
typeof Math // "object"  (1)
typeof null // "object"  (2)
typeof alert // "function"  (3)

Comparison

expressionvalue
'2' > 1true
'01' == 1true
true == 1true
false == 0true
0 == falsetrue
'' == falsetrue
null == undefinedtrue
null == 0false
undefined == 0false

strict equality operator === checks the equality without type conversion.** if a and b are of different types, then a === b immediately returns false without an attempt to convert them.

expressionvalue
0 === falsefalse
null === undefinedfalse

Functions

with default values

function showMessage(from, text = "no text given") {
  alert( from + ": " + text );
}
showMessage("Ann"); // Ann: no text given

A function with an empty return or without it returns undefined

Function Expression

let sayHi = function() {
  alert( "Hello" );
};

Arrow functions

const add = (a, b) => a + b;

Without curly braces: (...args) => expression – the right side is an expression: the function evaluates it and returns the result. With curly braces: (...args) => { body } – brackets allow us to write multiple statements inside the function, but we need an explicit return to return something.

arrow functions do not have this. If this is accessed, it is taken from the outside. Arrow functions also have no arguments variable.

To indicate that instead you want a single expression that happens to be an object, you wrap the object with parentheses:

(name, description) => ({name: name, description: description});

There’s a subtle difference between an arrow function => and a regular function called with .bind(this):

  • .bind(this) creates a “bound version” of the function.
  • The arrow => doesn’t create any binding. The function simply doesn’t have this. The lookup of this is made exactly the same way as a regular variable search: in the outer lexical environment.

Objects

let user = new Object(); // "object constructor" syntax
let user = {};  // "object literal" syntax
let user = {
  name: "John",
  age: 30,
  "likes birds": true  // multiword property name must be quoted
};

user.name = 'New name'

user["likes birds"] = true;

Javascript promises

const  doCall = () => {
 let  promise = new  Promise(function(resolve, reject) {
	 setTimeout(() =>  resolve("done!"), 1000);
    });
   return  promise
 }
 
 // resolve runs the first function in .then
 doCall().then(
    result  =>  log(result), // shows "done!"
    error  =>  log(error) // doesn't run
  );
    
 const  getCall = async () => {
  let  x = await  doCall()  
  log(x)
}

/* other example */
const add = (a, b) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (a < 0 || b < 0) {
return reject('Numbers must be non-negative')
}
resolve(a + b)
}, 2000)
})
}


add(1, 2).then((sum) => {
console.log(sum) // Will print 3
return add(sum, 4)
}).then((sum2) => {
console.log(sum2) // Will print 7
}).catch((e) => {
console.log(e)
})

const doWork = async () => {
const sum = await add(1, 99)
const sum2 = await add(sum, 50)
const sum3 = await add(sum2, 3)
return sum3
}
doWork().then((result) => {
console.log('result', result)
}).catch((e) => {
console.log('e', e)
})
   

Notes


/* parse object entries */
Object.entries(obj)

/* Check Object Empy */
Object.keys(obj).length === 0 && obj.constructor === Object


/* check if Array */
Array.isArray(obj)

/* check if Array not Empty */
if (Array.isArray(array) && array.length) {
    // array exists and is not empty
}

   

Use Reducers

['a','b'].reduce(function(result, item, index, array) {
  result[item] = item; //a, b, c
  return result;
}, {})

/* example */
var result = list.reduce((acc,item) => {
      acc.push(item)
      return acc
    },[])

For each

arr.forEach(callback(currentValue[, index[, array]]) {
  // execute something
}[, thisArg]);

/* async */
ratings.forEach(async function(rating) {
  sum = await sumFunction(sum, rating)
})


/* with arrow */
someValues.forEach((element, index) => {
    console.log(`Current index: ${index}`);
    console.log(element);
});

Array.find

let result = arr.find(function(item, index, array) {
  // if true is returned, item is returned and iteration is stopped
  // for falsy scenario returns undefined
});

ex:
let user = users.find(item => item.id == 1);

Leave a Reply

Your email address will not be published.