”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > JavaScript 代码片段

JavaScript 代码片段

发布于2024-08-30
浏览:730

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]删除
最新教程 更多>
  • 极简生活的艺术
    极简生活的艺术
    什么是极简生活? 极简生活是一种有意减少拥有的财产数量和生活中杂乱的生活方式。这不仅是为了整理您的空间,也是为了简化您的生活,专注于真正重要的事情,并减少干扰。 为什么采用极简主义? 头脑清晰:拥有的东西越少,需要担心的事情就越少,头脑就越清晰。 财务自由:通过减少...
    编程 发布于2024-11-06
  • Java 混淆之谜
    Java 混淆之谜
    Come play with our Java Obfuscator & try to deobfuscate this output. The price is the free activation code! Obfuscated Java code Your goal...
    编程 发布于2024-11-06
  • 如何在没有图像的 Outlook 电子邮件中创建圆角?
    如何在没有图像的 Outlook 电子邮件中创建圆角?
    在没有图像的 Outlook 中设置圆角样式使用 CSS 在电子邮件客户端中创建圆角可以非常简单。但是,使用 CSS border-radius 属性的传统方法在 Microsoft Outlook 中不起作用。在设计具有圆角元素的电子邮件时,此限制提出了挑战。不用担心,有一种解决方案可以让您在 O...
    编程 发布于2024-11-06
  • 如何在Python中高效比较字典中相等的键值对?
    如何在Python中高效比较字典中相等的键值对?
    比较字典是否相等的键值对在Python中,比较字典以检查键值对是否相等是一项常见任务。一种方法是迭代字典并使用 zip 和 iteritems 方法比较每一对字典。然而,还有一些替代方法可以提供更好的代码优雅性。其中一种方法是使用字典理解来创建仅包含共享键值对的新字典。代码如下:shared_ite...
    编程 发布于2024-11-06
  • 如何在 PHP 中使用数组函数向左旋转数组元素?
    如何在 PHP 中使用数组函数向左旋转数组元素?
    在 PHP 中向左旋转数组元素在 PHP 中旋转数组,将第一个元素移动到最后一个元素并重新索引数组,可以使用 PHP 的 array_push() 和 array_shift() 函数组合来实现。PHP 函数:PHP 没有专门用于旋转的内置函数数组。但是,以下代码片段演示了如何模拟所需的旋转行为:$...
    编程 发布于2024-11-06
  • 如何解决Java访问文件时出现“系统找不到指定的路径”错误?
    如何解决Java访问文件时出现“系统找不到指定的路径”错误?
    解决 Java 中遇到“系统找不到指定的路径”时的文件路径问题在 Java 项目中,尝试访问文本时遇到错误来自指定相对路径的文件。此错误是由于 java.io.File 类无法定位指定路径而产生的。要解决此问题,建议从类路径中检索文件,而不是依赖文件系统。通过这样做,您可以消除相对路径的需要,并确保...
    编程 发布于2024-11-06
  • Laravel 中的 defer() 函数如何工作?
    Laravel 中的 defer() 函数如何工作?
    Taylor Otwell 最近宣布了 Laravel 中的新函数 defer()。这只是对 defer() 函数如何工作以及使用它可能遇到的问题进行非常基本的概述。 找出问题 还记得您曾经需要从 API 获取某些内容,然后在幕后执行一些用户不关心但仍在等待的操作的路由吗?是的,我们都至少经历过一次...
    编程 发布于2024-11-06
  • 在 Python Notebook 中探索使用 PySpark、Pandas、DuckDB、Polars 和 DataFusion 的数据操作
    在 Python Notebook 中探索使用 PySpark、Pandas、DuckDB、Polars 和 DataFusion 的数据操作
    Apache Iceberg Crash Course: What is a Data Lakehouse and a Table Format? Free Copy of Apache Iceberg the Definitive Guide Free Apache Iceberg Crash ...
    编程 发布于2024-11-06
  • Vue + Tailwind 和动态类
    Vue + Tailwind 和动态类
    我最近在做的一个项目使用了Vite、Vue和Tailwind。 使用自定义颜色一段时间后,我遇到了一些困惑。 在模板中添加和使用自定义颜色不是问题 - 使用 Tailwind 文档使该过程非常清晰 // tailwind.config.js module.exports = { them...
    编程 发布于2024-11-06
  • 端到端(E 测试:综合指南
    端到端(E 测试:综合指南
    端到端测试简介 端到端(E2E)测试是软件开发生命周期的重要组成部分,确保整个应用程序流程从开始到结束都按预期运行。与专注于单个组件或几个模块之间交互的单元或集成测试不同,端到端测试从用户的角度验证整个系统。这种方法有助于识别应用程序不同部分交互时可能出现的任何问题,确保无缝且无错误的用户体验。 ...
    编程 发布于2024-11-06
  • 可以在 Go 结构标签中使用变量吗?
    可以在 Go 结构标签中使用变量吗?
    在 Go 结构体标签中嵌入变量Go 的结构体标签通常用于注释和元数据,通常涉及简单的字符串文字。但是,用户可能会遇到在这些标签中需要动态或计算值的情况。考虑以下结构,其中带有为 JSON 封送注释的“类型”字段:type Shape struct { Type string `json:&q...
    编程 发布于2024-11-06
  • 如何增强 Visual Studio 的构建详细程度以实现深入洞察?
    如何增强 Visual Studio 的构建详细程度以实现深入洞察?
    熟悉 Visual Studio 的构建详细程度需要全面了解 Visual Studio 构建过程背后的复杂细节?别再犹豫了!虽然使用 vcbuild 不会产生所需的详细输出,但 Visual Studio 的设置中隐藏着一个解决方案。采取以下简单步骤即可解锁大量信息:导航至 Visual Stud...
    编程 发布于2024-11-06
  • 开发者日记# 谁写的?
    开发者日记# 谁写的?
    有一个想法困扰着我。也许,我们无法识别它,但日复一日,我们周围越来越多的人工智能生成的内容。 LinkedIn 或其他平台上的有趣图片、视频或帖子。我对帖子的媒体内容没有疑问(很容易识别它何时生成、从库存中获取或创建),但我对帖子的内容表示怀疑。几乎每次我读一篇文章时,我都会想这是谁写的?是作者分享...
    编程 发布于2024-11-06
  • 哪种方法计算数据库行数更快:PDO::rowCount 或 COUNT(*)?为什么?
    哪种方法计算数据库行数更快:PDO::rowCount 或 COUNT(*)?为什么?
    PDO::rowCount 与 COUNT(*) 性能在数据库查询中计算行数时,选择使用 PDO:: rowCount 和 COUNT(*) 会显着影响性能。PDO::rowCountPDO::rowCount 返回受最后一个 SQL 语句影响的行数。但是,对于 SELECT 语句,某些数据库可能会...
    编程 发布于2024-11-06
  • PART# 使用 HTTP 进行大型数据集的高效文件传输系统
    PART# 使用 HTTP 进行大型数据集的高效文件传输系统
    让我们分解提供的HTML、PHP、JavaScript和CSS代码对于分块文件上传仪表板部分。 HTML 代码: 结构概述: Bootstrap for Layout:代码使用 Bootstrap 4.5.2 创建一个包含两个主要部分的响应式布局: 分块上传部分:用于...
    编程 发布于2024-11-06

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3