」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > JavaScript 程式碼片段

JavaScript 程式碼片段

發佈於2024-08-30
瀏覽:713

Javascript Code Snippets

Datatypes

Primitive Data Types

Number

let age = 25; 

String

let name = "John";

Boolean

let isStudent = true;

Undefined:

let address;

Null

let salary = null;

Symbol

let sym = Symbol("id");

BigInt

let bigIntNumber = 1234567890123456789012345678901234567890n;

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

How to check datatype?

console.log(typeof a);

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);

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;
    }
}

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);

Immediately Invoked Function Expression (IIFE)

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

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

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!"

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();

Accessing HTML Elements in JavaScript

There are several ways to access HTML elements in JavaScript:

Select element by ID:

document.getElementById("elementId");

Select element by Classname:

document.getElementsByClassName("className");

Select element by Tagname:

document.getElementsByTagName("tagName");

Css selector:

document.querySelector(".className");
document.querySelectorAll(".className");

Pass by value

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

let num = 5;
changeValue(num);

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

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

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

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

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]

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

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

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
}

const
It declares a constant variable that cannot be reassigned.

const PI = 3.14;

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

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

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 ;
  }
}

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

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

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"

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 Component
function Child(props) {
  return 
{props.message}
; }

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 (
    

Count: {count}

); }

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');

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

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 }

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

版本聲明 本文轉載於:https://dev.to/madgan95/javascript-code-snippets-56d3?1如有侵犯,請聯繫[email protected]刪除
最新教學 更多>
  • 如何正確使用與PDO參數的查詢一樣?
    如何正確使用與PDO參數的查詢一樣?
    在pdo 中使用類似QUERIES在PDO中的Queries時,您可能會遇到類似疑問中描述的問題:此查詢也可能不會返回結果,即使$ var1和$ var2包含有效的搜索詞。錯誤在於不正確包含%符號。 通過將變量包含在$ params數組中的%符號中,您確保將%字符正確替換到查詢中。沒有此修改,PD...
    程式設計 發佈於2025-04-16
  • Java開發者如何保護數據庫憑證免受反編譯?
    Java開發者如何保護數據庫憑證免受反編譯?
    在java 在單獨的配置文件保護數據庫憑證的最有效方法中存儲憑據是將它們存儲在單獨的配置文件中。該文件可以在運行時加載,從而使登錄數據從編譯的二進製文件中遠離。 使用prevereness class import java.util.prefs.preferences; 公共類示例{ 首選...
    程式設計 發佈於2025-04-16
  • FastAPI自定義404頁面創建指南
    FastAPI自定義404頁面創建指南
    response = await call_next(request) if response.status_code == 404: return RedirectResponse("https://fastapi.tiangolo.com") else: ...
    程式設計 發佈於2025-04-16
  • 如何在其容器中為DIV創建平滑的左右CSS動畫?
    如何在其容器中為DIV創建平滑的左右CSS動畫?
    通用CSS動畫,用於左右運動 ,我們將探索創建一個通用的CSS動畫,以向左和右移動DIV,從而到達其容器的邊緣。該動畫可以應用於具有絕對定位的任何div,無論其未知長度如何。 問題:使用左直接導致瞬時消失 更加流暢的解決方案:混合轉換和左 [並實現平穩的,線性的運動,我們介紹了線性的轉換。...
    程式設計 發佈於2025-04-16
  • Android如何向PHP服務器發送POST數據?
    Android如何向PHP服務器發送POST數據?
    在android apache httpclient(已棄用) httpclient httpclient = new defaulthttpclient(); httppost httppost = new httppost(“ http://www.yoursite.com/script.p...
    程式設計 發佈於2025-04-16
  • .NET中如何獲取AssemblyVersion和AssemblyFileVersion?
    .NET中如何獲取AssemblyVersion和AssemblyFileVersion?
    從assemblyInfo To retrieve the AssemblyVersion, you can use the code snippet:Version version = assembly.getEntryAssembly()。 getName()。版本; 此代碼獲取活動彙編,檢索...
    程式設計 發佈於2025-04-16
  • `console.log`顯示修改後對象值異常的原因
    `console.log`顯示修改後對象值異常的原因
    foo = [{id:1},{id:2},{id:3},{id:4},{id:id:5},],]; console.log('foo1',foo,foo.length); foo.splice(2,1); console.log('foo2', foo, foo....
    程式設計 發佈於2025-04-16
  • Django CSRF驗證為何在Ajax POST請求中失敗?
    Django CSRF驗證為何在Ajax POST請求中失敗?
    Django CSRF Check Failing with Ajax Post RequestAs outlined in Django's documentation, enabling CSRF protection helps prevent malicious cross-site...
    程式設計 發佈於2025-04-16
  • 如何在GO編譯器中自定義編譯優化?
    如何在GO編譯器中自定義編譯優化?
    在GO編譯器中自定義編譯優化 GO中的默認編譯過程遵循特定的優化策略。 However, users may need to adjust these optimizations for specific requirements.Optimization Control in Go Compi...
    程式設計 發佈於2025-04-16
  • 在細胞編輯後,如何維護自定義的JTable細胞渲染?
    在細胞編輯後,如何維護自定義的JTable細胞渲染?
    在JTable中維護jtable單元格渲染後,在JTable中,在JTable中實現自定義單元格渲染和編輯功能可以增強用戶體驗。但是,至關重要的是要確保即使在編輯操作後也保留所需的格式。 在設置用於格式化“價格”列的“價格”列,用戶遇到的數字格式丟失的“價格”列的“價格”之後,問題在設置自定義單元...
    程式設計 發佈於2025-04-16
  • 切換到MySQLi後CodeIgniter連接MySQL數據庫失敗原因
    切換到MySQLi後CodeIgniter連接MySQL數據庫失敗原因
    Unable to Connect to MySQL Database: Troubleshooting Error MessageWhen attempting to switch from the MySQL driver to the MySQLi driver in CodeIgniter,...
    程式設計 發佈於2025-04-16
  • Java中Arrays與Lists:何時選擇哪種以優化性能?
    Java中Arrays與Lists:何時選擇哪種以優化性能?
    在java中,您在存儲大量字符串時會選擇一個選擇:數組或列表。這個決定可能會影響性能,特別是在處理數千個元素時。 陣列的優勢但是,數組也有限制: 固定的大小:數組需要一個預定的大小,如果您的數據集會動態地成長或縮小數據集就會變得有問題。效率低下。 列表 附加功能:列表提供內置功能,例如迭代器,排序...
    程式設計 發佈於2025-04-16
  • jQuery AJAX調用接收數據錯誤,但PHP已返回JSON
    jQuery AJAX調用接收數據錯誤,但PHP已返回JSON
    PHP將JSON返回jquery Ajax調用 ,儘管您努力通過JQUERY的AJAX功能與PHP進行通信,但您仍在繼續遇到“選擇器激活”錯誤。此外,檢索到的數據似乎不正確。 Let's delve into the issue and identify the potential ca...
    程式設計 發佈於2025-04-16
  • 如何解決由於Android的內容安全策略而拒絕加載腳本... \”錯誤?
    如何解決由於Android的內容安全策略而拒絕加載腳本... \”錯誤?
    Unveiling the Mystery: Content Security Policy Directive ErrorsEncountering the enigmatic error "Refused to load the script..." when deployi...
    程式設計 發佈於2025-04-16
  • HTML格式標籤
    HTML格式標籤
    HTML 格式化元素 **HTML Formatting is a process of formatting text for better look and feel. HTML provides us ability to format text without us...
    程式設計 發佈於2025-04-16

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3