Top Left Text cha

Web & App Development

Just a little reference to recall syntax of some basic Javascript...

List of useful Basic Syntax

Number(value)  //convert to number *same for objects
Boolean(value)  //convert to boolean
String(value)  //convert to string
[Symbol.toPrimitive]
toString() & valueOf()  //converting to string or number
Math.floor & Math.ceil & Math.round  //rounding
.toFixed(n)  //returns string so Number() should be used if needed for calculation
isNaN(value) & ifFinite(value)  
Object.is(a, b)  //compare 2 vaues
parseInt() & parseFloat() //returns number from string (until it gets to a NaN)
Math.random()  //Returns a random number from 0 to 1 (not including 1)
Math.max(a, b, c...) & Math.min(a, b, c...)  //Returns the greatest & smallest from the arbitrary number of arguments.
Math.pow(n, power)
Math.sign(x)  //positive, negative or zero
string.length  //length of the string
string[0]  & string.charAt(0)  //first character
string[string.length - 1]  //last character
for (let char of string) {do something}
toLowerCase() & toUpperCase()
string.indexOf(substr, pos)  // pos = start position (optional)  substr = needle, string = haystack
string.lastIndexOf(pos)  // starts at end of string
string.includes(substr, pos)  // pos = starting position (optional)
.startsWith() & .endsWith()
.slice(0, 5)  & .slice(-5, -1)  //returns chunk of string between 0 and 5 characters; negatives work from the end of the string
.substring(a, b)  //returns chunk between 2 positions
.substr(start pos, length)  //start pos can be negative and start from end

arr.splice(index, delete count[, val1, val2, valN]);
arr.splice(start at, number to delete, add value 1, add value 2);
arr.splice(2, 0, "value1", "value2");  //start at position 2, delete none, then insert value 1 & value 2 (at position 2) & also works with negative index
arr.slice(from index, to before position) //works with negs also
arr.indexOf(item, from) //looks for item starting from index from, and returns the index where it was found, otherwise -1.
arr.lastIndexOf(item, from) //same as ^, but looks from right to left.
arr.includes(item, from) //looks for item starting from index from, returns true if found.
let result = arr.find(function(item, index, array)  // should return true if the item is what we are looking for
let result = arr.map(function(item, index, array) {} // It calls the function for each element of the array and returns the array of results. like:  let lengths = ["Bilbo", "Gandalf", "Nazgul"].map(item => item.length)
arr.sort(); //only works on strings unless you add a function to compare
arr.reverse();  //reverses the order of an array
str.split(delimeter) //let str = "a, b, c"; let arr = str.split(", ") turns string into array like explode in PHP [optional array length as 2nd argument]
arr.join(delimeter); //reverse of split... like PHP implode
Array.isArray(value); //true if value is array
map.set(key, value)  //Probably useless - like array but stores keys of any type (even functions)
map.get(key); map.has(key); map.delete(key); map.clear(); map.size()  //map is just the name of the map in these
map.set('1', 'str1').set(1, 'num1').set(true, 'bool1');  //can be chained - also on new lines for each
new Set(iterable) //has same syntax as map above - only keeps unique values (duplicates thrown out)









Simple function Declaration syntax (can be used anywhere)

function showMessage(msg) {
    alert(msg);
}

let xxx = "hello";
showMessage(xxx); // alerts 'hello'

Function expression syntax (can only be used after declared)

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

Arrow Functions

let func = (arg1, arg2, ...argN) => expression

let sum = (a, b) => a + b;

same as

let sum = function(a, b) {
    return a + b;
};

and...

let double = function(n) { return n * 2 }

is the same as...

let double = n => n * 2;

Objects can be either:

let object = {
key1 = value1,
key2 = value2,
keyN = valueN
}

or similar to PHP (less common)...

let object = new Object();

When using an object, you can do it by either method below... but any variable can be put in square brackets and will be converted

let abc = "key2";
let example = object.key1;
let example = object[key1];
let example = object[abc];  // same as object [key2]

Property values declaration in shorthand... The use-case of making a property from a variable is so common, that there’s a special property value shorthand to make it shorter.

function makeUser(name, age) {
    return {
        name: name,
        age: age
        // ...other properties
    };
}

Can be written as:

function makeUser(name, age) {
    return {
        name,
        age
        // ...other properties
    };
}

For...in Loop

for(let key in object) {
    // do something with the keys in loop (ignores symbols);
    continue; // breaks, then continues from beginning of loop
    break; // ends loop
}

Clone the object, user:

let clone = Object.assign({}, user);

Basic Syntax for assigning both multiple other objects and keys:

Object.assign(dest[, src1, src2, src3...] [,{key = value, keyN = valueN})

Symbols

let id = Symbol("id");  // "id" is just used as directions/notes - not used at ALL

Global Symbols

let id = Symbol.for("id");

to get the name (remember, name is only used for debugging purposes)

let symbolName = Symbol.keyfor(id);

Shorthand for writing method in function:

let user = {
    name: "John",
    age: 30,
    sayHi() { // same as "sayHi: function()"
        alert("Hello");
    }
};

Constructor Function

function User(name) {
     this.name = "John"; 
     this.isAdmin = false;
};
let user = new User("abc");


let user = new function() {  //one use constructor function
     this.name = "John";
     this.isAdmin = false;
};

Arrays

let arr = new Array();
let arr = [];  //same as above, but more common

let arr = ["nissan", "toyota"];  // arr[1] would be toyota

for (let i = 0; i < 5; i++) {do something} // after 2nd value, undefined
for (let i = 0; i < arr.length; i++) {do something} // works - not shortest but fastest and will skip non-numeric keys
for (let key in arr) {do something}  // much easier but slower and will spit out non-numeric keys

lenghtOfArray = arr.length;

arr.pop //removes last item [fast]
arr.push //append element(s) to end [fast]
arr.shift //extracts 1st element, returns it and removes it [slow]
arr.unshift //add element(s) to beginning [slow]

Multidimensional Arrays

let matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ];

Add comment


Security code
Refresh

  • No comments found

Leave your comments

Post comment as a guest

0
Your comments are subjected to administrator's moderation.
X