Javascript code snippets
- var -> function scoped. variable declared with var is visible everywhere inside the function its declared in.
- let -> block scoped. variable declared with let is visible everywhere inside the block its declared in. A let variable can only be declared once, defined multiple times.
- const -> block scoped. variable declared with const is visible everywhere inside the block its declared in. A const variable can only be declared once. Value has to be assigned at the time of declaration.
Syntax for regular JS functions:
const square = function(num) { return num * num; }
Syntax for arrow functions:
const square = (num) => { return num * num; }
or
const square = num => num * num; //note that we can remove the parentheses in the parameters in case of only 1 parameter being passed.
In case of no parameter,
const dummy = () => console.log("dummy function");
Note: Arrow functions don't rebind the 'this' keyword.
Note: Template literals allow us to have multi-line strings. For example, see this.
ES6 spread operator helps us construct new arrays/objects by 'spreading' the existing arrays/objects.
Spreading arrays, spreading objects
The padStart function is used for padding the start of a string. The padEnd function is used for padding the end of a string.
- In JS, functions are objects.
- Using JS 'bind' method, one can bind a method to a JS object to avoid ambiguous behavior of JS 'this' keyword.