Home > Web Front-end > JS Tutorial > body text

Javascript Code Snippets

WBOY
Release: 2024-08-30 21:00:10
Original
245 people have browsed it

Javascript Code Snippets

Datatypes

Primitive Data Types

Number

let age = 25; 
Copy after login

String

let name = "John";
Copy after login

Boolean

let isStudent = true;
Copy after login

Undefined:

let address;
Copy after login

Null

let salary = null;
Copy after login

Symbol

let sym = Symbol("id");
Copy after login

BigInt

let bigIntNumber = 1234567890123456789012345678901234567890n;
Copy after login

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
Copy after login

How to check datatype?

console.log(typeof a);
Copy after login

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);
Copy after login

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;
    }
}
Copy after login

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);
Copy after login

Immediately Invoked Function Expression (IIFE)

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

(function() {
    console.log("IIFE executed!");
})();
Copy after login

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!"
Copy after login

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();
Copy after login

Accessing HTML Elements in JavaScript

There are several ways to access HTML elements in JavaScript:

Select element by ID:

document.getElementById("elementId");
Copy after login

Select element by Classname:

document.getElementsByClassName("className");
Copy after login

Select element by Tagname:

document.getElementsByTagName("tagName");
Copy after login

Css selector:

document.querySelector(".className");
document.querySelectorAll(".className");
Copy after login

Pass by value

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

let num = 5;
changeValue(num);
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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]
Copy after login

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
Copy after login

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
Copy after login

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
}
Copy after login

const
It declares a constant variable that cannot be reassigned.

const PI = 3.14;
Copy after login

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
Copy after login

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
Copy after login

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>;
  }
}
Copy after login

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");
};
Copy after login

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
Copy after login

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"
Copy after login

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>;
}
Copy after login

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>
  );
}
Copy after login

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');
Copy after login

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
Copy after login

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 }
Copy after login

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

The above is the detailed content of Javascript Code Snippets. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!