Security, Tech & Programming
JavaScript Cheatsheet

JavaScript Cheatsheet

ForEach loop in javascript:

your_array.forEach( (item) => {
    // do something
}

Export & Import modules in JavaScript ES6 (node / react / nextjs)

We can export multiple items from a single file in javascript ES6 module.

Check following examples, all can happen in one file.

Note that we also have one default export, also one “as” export (see below on how to import these)

export const one = [1,2,3]

export default function func_1() {}

export class Class_1 {
    constructor() {
        //
    }
}

const a = '123'
const b = '456'
const c = '789'

export {
    a,
    b as b_new,
    c
}

Now we can import the items of this module by using the code:

// default needs to be imported directly
// non defaults are imported inside curly braces { }
import func_1, {one, Class_1, a, b_new, c } from 'file.js'

// or import all "as"

import * from 'file.js' as utils
// then call them as needed:
utils.func_1()

JavaScript Map function

let a = [1,2,3]
let b = a.map( (item) => {
            // do some logic & return the new value for this item
            return item + 10
        })

console.log(b) // will give: [11,12,13]

JavaScript Filter function

Filters out the items from the loop based on the return value (true or false).

let a = [1,2,3]
let b = a.filter ( (item) => {
            // 
            if(item < 3) {
                return true
            }else{
                return false
            }
        })

console.log(b) // will give: [1,2] - not 3 as it is not < 3

JavaScript Reduce function

One of the confusing but really simple to understand! Here’s how to use it with arrays / objects and combine the functionality of both javascript map and filter functions.

var a = [
  {'name': 'a', address: 'a address'},
  {'name': 'b', address: 'b address'},
  {'name': 'c', address: 'c address'},
  {'name': 'd', address: 'd address'}
]

//console.log(a)

// output, item are required, index, arr are optional
// required: output will be returned to b at the end
// required: item is the current item from array in loop
// optional: index is the index of current item / loop
// optional: arr is the original array (a here)
var b = a.reduce( (output, item, index, arr) => {
  if(item.name != 'a'){
      output.push(item.name)
  }
  return output
}, [])

console.log(b) // ["b", "c", "d"]

// Note:
// if we use output[index] then skipped items will be undefined
// [undefined, "b", "c", "d"]

// if we give default value instead of empty [], like ["hello"]
// ["hello", "b", "c", "d"]

SetTimeout to trigger function self

var timing = 250

function loop() {
  // we can change the timing as we want & then trigger again
  timing = timing * 2
  window.setTimeout(loop, timing);
}

loop();

JavaScript Console Cheatsheet

console.log("hello world!")
console.info("hello world!")
console.warn("hello world!")
console.error("hello world!")
console.table([<some array>])
console.time() // displays count each time it's called
console.timeEnd() // clears console.time() counts
console.assert(logic, "output if true")
console.clear()
console.trace()

Use dynamic integer as key in associative array in JavaScript

If we use integer as the key in the javascript array, it converts it into a regular array, resulting in all previous entries as undefined. For example:

let a = []
a["2"] = "something"

console.log(a)
// will output:
// [undefined, undefined, "something"]

To create associative array in javascript, we have to actually use curly braces (object) format. And then add keys and values to the object using spread operator or directly using square brackets, like this:

let a = {}
a = {...a, "2": "something"}

console.log(a)
// will output:
// [object Object] {
//   2: "something"
// }

// We can also add dynamic key (integer or string)
// to add new key value pair like this:
let b = "dynamic_key"
let c = "some value"
// note that for using var as key, use square brackets notation []
// value don't need that, can be hard coded or variable
a = {...a, [b]: c} // or: a = {...a, [b]: "some value"} 
// note, we can also just do this too:
let d = "dynamic_key_2"
let e = "d_value"
a[d] = e

console.log(a)
// will output:
// [object Object] {
//   2: "something",
//   dynamic_key: "some value",
//   dynamic_key_2: "d_value"
// }

Convert a String to number

We can convert a string to a number by simply adding a plus sign before it, like this:

let a = "2"
console.log(+a)

Please let me know if you need any help related to javascript.

pop, push, shift, unshift

It’s important to understand that these functions have a return value, which means you can not chain them in existing logics in all cases like you would want to, so be careful.

JavaScript pop

Removes the item from the end of the array.

let a = ["one", "two", "three", "four", "five"]

let b = a.pop()
// a: ["one", "two", "three", "four"]
// b: five
// a is now the updated array, while the return value is saved in b
// so we can not do following if we want to keep updated array
// let a = ["one", "two", "three", "four", "five"].pop()

JavaScript push

Adds the item to the end of the array

let a = ["one", "two", "three", "four", "five"]

let b = a.push("six")
// a: ["one", "two", "three", "four", "five", "six"]
// b: 6
// a is now the updated array, while the updated count is saved in b
// so we can not do following if we want to keep updated array
// let a = ["one", "two", "three", "four", "five"].push("six")

JavaScript shift and unshift do the same thing but to the first item of the array instead of last one.

Leave a Reply

Your email address will not be published. Required fields are marked *

Hire Me!