Javascript Code Snippets

WBOY
リリース: 2024-08-30 21:00:10
オリジナル
245 人が閲覧しました

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 inStrict 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

以上がJavascript Code Snippetsの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!