Skip to content

Instantly share code, notes, and snippets.

@sunil-bagde
Last active October 18, 2024 20:41
Show Gist options
  • Save sunil-bagde/fa1e88cce76a8078ed121cdcd365968f to your computer and use it in GitHub Desktop.
Save sunil-bagde/fa1e88cce76a8078ed121cdcd365968f to your computer and use it in GitHub Desktop.
Js notes

JS

What is compilations vs polyfilling

Babel to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments.

Other compiler

TypeScript
SWC 
Rollup

Polyfilling Polyfills are pieces of code that provide modern functionality to older browsers that lack native support for those features e,g core-js es6-shim webcomponentsjs

What is use strict and what does it do?

e.g

"use strict";
x = 3.14;       // This will cause an error because x is not declared

Future Proof! Keywords reserved for future JavaScript versions can NOT be used as variable names in strict mode.

Disallows duplicate parameter names Makes eval() and arguments safer

Does javascript pass variables by reference or by value

primitive are pass by value number string boolean symbol null undefined non-primitive data are passed by ref Object Array

What are the rest operators

The rest parameter syntax allows a function to accept an indefinite number of arguments as an array

function sum(...theArgs) {
  let total = 0;
  for (const arg of theArgs) {
    total += arg;
  }
  return total;
}

What is the spread operator

Spread syntax "expands" an array into its elements, while rest syntax collects multiple elements

const numbers = [1, 2, 3];

console.log(sum(...numbers));

What are template strings

Template literals are literals delimited with backtick (`) multi-line strings,

console.log(`string text line 1 \
string text line 2`);

string interpolation with embedded expression console.log(`Fifteen is ${10 + 5} and

and special constructs called tagged templates.

function myTag(strings, ...values) {
  console.log(strings);  // Array of strings
  console.log(values);   // Array of values
  
  return strings.reduce((result, str, i) => result + str + (values[i] || ''), '');
}

// Using the tagged template
const name = "Sunil";
const age = 20;

const result = myTag`Hello, my name is ${name} and I am ${age} years old.`; // HERE
console.log(result);  // Output: "Hello, my name is Sunil and I am 20 years old.
function styled(tag) {
  return (strings, ...values) => {
    const styleString = strings.reduce(
      (acc, str, i) => acc + str + (values[i] || ""),
      ""
    );
    
    // Create the element and apply the styles
    const element = document.createElement(tag);
    element.style.cssText = styleString;
    
    return element;
  };
}

// Example usage for a styled div
const StyledDiv = styled ('div')`
  background-color: lightblue;
  color: white;
  padding: 20px; 
  font-size: 1.5em;
  text-align: center;
  border-radius: 10px;
`;

// Adding the styled element to the DOM
document.body.appendChild(StyledDiv);
StyledDiv.textContent = "Hello, I'm a styled div!";

Type & Equality

Number String Boolean Null Undefined BigInt Symbol Object

What is the difference between == and ===

=== — strict equality (triple equals) type + value check == — loose equality (double equals) only check value

What is NaN and how can we check for it

The NaN global property is a value representing Not-A-Number. isNaN("hello world");

Scope & Variable

lifetime of variable or where a variable accessible

window.SNS_API_KEY // global

fuction scope

 function login() { // fn scope
   var user =""
   console.log(user)
 } 
 es6  block scope let or const 
 {
  let name =""
 }
 // errpr
 console.log(name) // Reference Error ||   Unexpected identifier 'name'

What is variable hoisting

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution

console.log(name)
var name = "raj"

What is the scope chain

JavaScript uses to resolve variable references. When JavaScript encounters a variable name, it searches for the variable in the current scope. If the variable is not found in the current scope, the JavaScript interpreter searches the outer scope, and so on.

The current scope The outer scope The global scope

What is an IIFE and why might you use it

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.

Use cases Avoid polluting the global namespace Execute an async function The module pattern For loop with var before ES6

What are function closures

A closure in JavaScript is a function that has access to variables in its parent scope, even after the parent function has returned.

Destructuring & Looping

JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

e.g

 let a, b, rest;
 [a, b] = [10, 20];

Looping

for (let i = 0; i < 9; i++) {
  console.log(i);
}

// object looping using in operator

const capitals = {
  a: "Athens",
  b: "Belgrade",
  c: "Cairo"
};

for (let key in capitals) {
  console.log(key + ": " + capitals[key]);
}

for of can use with arrray , string , Map , set like Iterables

const arr = [ "Fred", "Tom", "Bob" ];

for (let i of arr) {
  console.log(i);
}

This

What does the this keyword mean

let user = {
	checkThis: function() {
	 console.log(this) 
	}
}
user.checkThis() // Object user 
let fn = user.checkThis
fn() // Window 

What do the functions call, bind and apply do

JavaScript, call(), bind(), and apply() are methods that allow you to control the context (this value) of a function,

1.call()

The call() method invokes a function with a specific this context and arguments passed individually. person.greet.call(anotherPerson, 30,40,50);

2.apply() The apply() method is similar to call(), but it accepts arguments as an array instead of individually. person.greet.apply(anotherPerson, [25]); 3. bind() The bind() method returns a new function, where this is permanently set to the specified context. Unlike call() and apply(), bind() doesn't immediately invoke the function.

const greetJane = person.greet.bind(anotherPerson);

What is a fat arrow function

  • An arrow function expression is a compact alternative to a traditional function expression,

  • Arrow functions don't have their own bindings to this, arguments, or super, and should not be used as methods.

  • Arrow functions cannot be used as constructors. Calling them with new throws a TypeError. They also don't have access to the new.target keyword.

  • Arrow functions cannot use yield within their body and cannot be created as generator functions.

Object Orientation

  • Prototypes are the mechanism by which JavaScript objects inherit features from one another.

What is the difference between prototypal and classical inheritance

Async js

Callback A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action

What is callback hell Callback hell is a phenomenon that happens when multiple callbacks are nested on top of each other

Promise & Async await

promise represents the eventual completion or failure of an asynchronous operation. Async/await simplifies writing asynchronous code, offering a more readable and concise syntax.

let promise = new Promise(function(resolve, reject) {
  // executor (the producing code)
})
promise to one of these states

state — initially "pending", then changes to either

"fulfilled" when resolve is called or

"rejected" when reject is called.

Events

Events are things that happen in the system you are programming, which the system tells you about so your code can react to them.

  • The user selects, clicks, or hovers the cursor over a certain element.
  • The user chooses a key on the keyboard.

event bubbling

When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.

<form onclick="alert('form')">FORM
  <div onclick="alert('div')">DIV
    <p onclick="alert('p')">P</p>
  </div>
</form>

A click on the inner

first runs onclick:

  • On that

  • Then on the outer
  • Then on the outer
  • And so on upwards till the document object

Stopping bubbling

    event.stopPropagation()

Capturing

Capturing phase – the event goes down to the element.

Target phase – the event reached the target element.

  elem.addEventListener(..., {capture: true})

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. Bubbling phase – the event bubbles up from the element.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment