Javascript Code Snippets

Madhav Ganesan - Aug 30 - - Dev Community

Datatypes

Primitive Data Types

Number

let age = 25; 
Enter fullscreen mode Exit fullscreen mode

String

let name = "John";
Enter fullscreen mode Exit fullscreen mode

Boolean

let isStudent = true;
Enter fullscreen mode Exit fullscreen mode

Undefined:

let address;
Enter fullscreen mode Exit fullscreen mode

Null

let salary = null;
Enter fullscreen mode Exit fullscreen mode

Symbol

let sym = Symbol("id");
Enter fullscreen mode Exit fullscreen mode

BigInt

let bigIntNumber = 1234567890123456789012345678901234567890n;
Enter fullscreen mode Exit fullscreen mode

Not-a-Number (NaN)
NaN stands for "Not-a-Number" and represents a value that is not a legal number

console.log(0 / 0); // NaN
console.log(parseInt("abc")); // NaN
Enter fullscreen mode Exit fullscreen mode

How to check datatype?

console.log(typeof a);
Enter fullscreen mode Exit fullscreen mode

Class

1) Class can only have one constructor

class gfg {
    constructor(name, estd, rank) {
        this.n = name;
        this.e = estd;
        this.r = rank;
    }

    decreaserank() {
        this.r -= 1;
    }
}

const test = new gfg("tom", 2009, 43);

test.decreaserank();

console.log(test.r);
console.log(test);
Enter fullscreen mode Exit fullscreen mode

Inheritance

class car {
    constructor(brand) {
        this.carname = brand;
    }

    present() {
        return 'I have a ' + this.carname;
    }
}
class Model extends car {
    constructor(brand, model) {
        super(brand);
        super.present();
        this.model = model;
    }

    show() {
        return this.present() + ', it is a ' + this.model;
    }
}
Enter fullscreen mode Exit fullscreen mode

Get and Set

class car {
    constructor(brand) {
        this.carname = brand;
    }

    // Getter method
    get cnam() {
        return "It is " + this.carname;  // Return a value
    }

    // Setter method
    set cnam(x) {
        this.carname = x;
    }
}

const mycar = new car("Ford");
console.log(mycar.cnam);
Enter fullscreen mode Exit fullscreen mode

Immediately Invoked Function Expression (IIFE)

An IIFE is a function that runs as soon as it is defined

(function() {
    console.log("IIFE executed!");
})();
Enter fullscreen mode Exit fullscreen mode

Higher Order Functions

Higher-order functions are functions that take other functions as arguments or return functions as their result

function higherOrderFunction(callback) {
    return callback();
}

function sayHello() {
    return "Hello!";
}

console.log(higherOrderFunction(sayHello)); // "Hello!"
Enter fullscreen mode Exit fullscreen mode

Variable Shadowning

Variable Shadowing occurs when a local variable has the same name as a variable in an outer scope.
The local variable overrides or hides the outer variable within its own scope.
The outer variable remains intact and can be accessed outside of the local scope.

var name = "John";

function sayName() {
  console.log(name);
  var name = "Jane";
}

sayName();
Enter fullscreen mode Exit fullscreen mode

Accessing HTML Elements in JavaScript

There are several ways to access HTML elements in JavaScript:

Select element by ID:

document.getElementById("elementId");
Enter fullscreen mode Exit fullscreen mode

Select element by Classname:

document.getElementsByClassName("className");
Enter fullscreen mode Exit fullscreen mode

Select element by Tagname:

document.getElementsByTagName("tagName");
Enter fullscreen mode Exit fullscreen mode

Css selector:

document.querySelector(".className");
document.querySelectorAll(".className");
Enter fullscreen mode Exit fullscreen mode

Pass by value

function changeValue(x) {
  x = 10;
  console.log("Inside function:", x)
}

let num = 5;
changeValue(num);
Enter fullscreen mode Exit fullscreen mode

Pass by reference

function changeProperty(obj) {
  obj.name = "Alice";
  console.log("Inside function:", obj.name); // Output: Inside function: Alice
}

let person = { name: "Bob" };
changeProperty(person);
console.log("Outside function:", person.name); // Output: Outside function: Alice
Enter fullscreen mode Exit fullscreen mode

use strict

It switches the JavaScript engine to strict mode, which catches common coding mistakes and throws more exceptions.

"use strict";
x = 10; // Throws an error because x is not declared
Enter fullscreen mode Exit fullscreen mode

Spread operator

It allows an iterable such as an array or string to be expanded in places where zero or more arguments or elements are expected

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

const numbers = [1, 2, 3];
console.log(sum(...numbers)); // Output: 6
Enter fullscreen mode Exit fullscreen mode

InstanceOf

The operator checks whether an object is an instance of a specific class or constructor function.

class Animal {
  constructor(name) {
    this.name = name;
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name);
    this.breed = breed;
  }
}

const myDog = new Dog('Buddy', 'Golden Retriever');

console.log(myDog instanceof Dog);   // true
console.log(myDog instanceof Animal); // true
console.log(myDog instanceof Object); // true
console.log(myDog instanceof Array);  // false
Enter fullscreen mode Exit fullscreen mode

Find

This method is used to find a particular element

let present = books.find(each => each.id == id);
Enter fullscreen mode Exit fullscreen mode

Findindex

This method is used to find a particular element by index

var index = books.findIndex(each => each.id == param_id);
books[index].title = title;
books[index].author = author;
books[index].year = year;
Enter fullscreen mode Exit fullscreen mode

Splice

array.splice(start, deleteCount, item1, item2, ...);
Enter fullscreen mode Exit fullscreen mode
books.splice(index, 1); // deletion

let arr = [1, 2, 3, 4, 5];
arr.splice(1, 2); // Removes elements starting at index 1, count of 2
Enter fullscreen mode Exit fullscreen mode

Filter

This method creates a new array with all elements that pass the test implemented by the provided function.

const numbers = [1, 2, 3, 4, 5, 6];

const evenNumbers = numbers.filter(num => num % 2 === 0);

console.log(evenNumbers); // [2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

Reduce

This method executes a reducer function on each element of the array, resulting in a single output value.

const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((sum, value) => sum + value, 0);
// sum = 0 initially

console.log(sum); // 15
Enter fullscreen mode Exit fullscreen mode

Rest

This parameter syntax allows a function to accept an indefinite number of arguments as an array.

function sum(...numbers) {
  return numbers.reduce((sum, value) => sum + value, 0);
}

console.log(sum(1, 2, 3)); // 6
console.log(sum(5, 10, 15, 20)); // 50
Enter fullscreen mode Exit fullscreen mode

Types of Declarations

Implicit Global variable
An implicit global variable is a variable that is created automatically in the global scope when it is assigned a value without being explicitly declared with a keyword like var, let, or const. But this throws error if it is in Strict mode

function myFunction() {
    x = 10; // no error
}
Enter fullscreen mode Exit fullscreen mode

const
It declares a constant variable that cannot be reassigned.

const PI = 3.14;
Enter fullscreen mode Exit fullscreen mode

let
It declares a block-scoped variable.
It cannot be re-intialized with same name

let c=1;
let c=3;// throws error
let count = 0;
if (true) {
    let count = 1;
    console.log(count); // Output: 1
}
console.log(count); // Output: 0
Enter fullscreen mode Exit fullscreen mode

var
It declares a function-scoped or globally-scoped variable. It encourages hoisting and reassignment.

var name = 'John';
if (true) {
    var name = 'Doe';
    console.log(name); // Output: Doe
}
console.log(name); // Output: Doe

console.log(a)
var a=2 // prints undefined
Enter fullscreen mode Exit fullscreen mode

Synthetic Event

Synthetic Events: React provides a SyntheticEvent wrapper around the native browser events. This wrapper normalizes the event properties and behavior across different browsers, ensuring that your event handling code works the same way regardless of the browser.

import React from 'react';

class MyComponent extends React.Component {
  handleClick = (event) => {
    // `event` is a SyntheticEvent
    console.log(event.type); // Always 'click' regardless of browser
    console.log(event.target); // Consistent target property
  }

  render() {
    return <button onClick={this.handleClick}>Click Me</button>;
  }
}
Enter fullscreen mode Exit fullscreen mode

Hoisting in JavaScript

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compile phase, allowing them to be used before they are declared in the code. However, only the declarations are hoisted, not the initializations.

console.log(x); // Output: undefined
var x = 5;
console.log(x); // Output: 5

// Function hoisting
hoistedFunction(); // Output: "Hoisted!"
function hoistedFunction() {
    console.log("Hoisted!");
}

// Function expressions are not hoisted
notHoisted(); // Error: notHoisted is not a function
var notHoisted = function() {
    console.log("Not hoisted");
};
Enter fullscreen mode Exit fullscreen mode

Type coercion

It is the automatic conversion of values from one data type to another. There are two types of coercion: implicit and explicit.

Implicit Coercion

Ex.

let result = 5 + "10"; // "510"
let result = "5" * 2; // 10
let result = "5" - 2; // 3
let result = "5" / 2; // 2.5
Enter fullscreen mode Exit fullscreen mode

Explicit Coercion

It happens when we manually convert a value from one type to another using built-in functions.

let num = 5;
let str = String(num); // "5"
let str2 = num.toString(); // "5"
let str3 = `${num}`; // "5"
Enter fullscreen mode Exit fullscreen mode

Truthy Values

Non-zero numbers (positive and negative)
Non-empty strings
Objects (including arrays and functions)
Symbol
BigInt values (other than 0n)

Falsy Values

0 (zero)
-0 (negative zero)
0n (BigInt zero)
"" (empty string)
null
undefined
NaN (Not-a-Number)

Props (Properties)

To pass data from a parent component to a child component. It is immutable (read-only) within the child component.

// Parent Component
function Parent() {
  const data = "Hello from Parent!";
  return <Child message={data} />;
}

// Child Component
function Child(props) {
  return <div>{props.message}</div>;
}
Enter fullscreen mode Exit fullscreen mode

State

To manage data that can change over time within a component. It is mutable within the component.

// Function Component using useState
import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Closure

A closure in JavaScript is a feature where an inner function has access to the outer (enclosing) function's variables and scope chain even after the outer function has finished executing.

function outerFunction(outerVariable) {
  return function innerFunction(innerVariable) {
    console.log('Outer Variable:', outerVariable);
    console.log('Inner Variable:', innerVariable);
  };
}

const newFunction = outerFunction('outside');
newFunction('inside');
Enter fullscreen mode Exit fullscreen mode

Currying

Currying is a technique of transforming a function that takes multiple arguments into a sequence of functions that each take a single argument.

function add(a) {
  return function(b) {
    return a + b;
  };
}

const add5 = add(5);
console.log(add5(3)); // Output: 8
console.log(add(2)(3)); // Output: 5
Enter fullscreen mode Exit fullscreen mode

Generators

Generators are special functions that can be paused and resumed, allowing you to generate a sequence of values over time.

function* generateSequence() {
  yield 1;
  yield 2;
  yield 3;
}

const generator = generateSequence();

console.log(generator.next()); // { value: 1, done: false }
console.log(generator.next()); // { value: 2, done: false }
console.log(generator.next()); // { value: 3, done: false }
console.log(generator.next()); // { value: undefined, done: true }
Enter fullscreen mode Exit fullscreen mode

Stay Connected!
If you enjoyed this post, don’t forget to follow me on social media for more updates and insights:

Twitter: madhavganesan
Instagram: madhavganesan
LinkedIn: madhavganesan

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .