Skip to content

Instantly share code, notes, and snippets.

@boraseoksoon
Last active August 18, 2023 07:37
Show Gist options
  • Save boraseoksoon/2bce41e7dbf948934c8bca0a21081559 to your computer and use it in GitHub Desktop.
Save boraseoksoon/2bce41e7dbf948934c8bca0a21081559 to your computer and use it in GitHub Desktop.
javascript syntax
`for
loop
javascript
`
`for
loop
javascript2
`
// Variables and Constants
var v1;
let v2 = 2;
const v3 = 3;
// Data Types
let s = 'string';
let n = 100;
let b = true;
let o = { key: 'value' };
let a = [1, 2, 3];
let sym = Symbol();
let u;
let nl = null;
// Arithmetic Operations
let add = 1 + 2;
let sub = 2 - 1;
let mul = 2 * 3;
let div = 6 / 2;
let mod = 7 % 5;
let inc = n++;
let dec = n--;
let exp = 2 ** 3;
// String Operations
let concat = s + ' append';
let tpl = `Hello ${s}`;
// Comparison
let eq = 1 == '1';
let seq = 1 === 1;
let neq = 1 != '1';
let sneq = 1 !== 1;
let gt = 2 > 1;
let lt = 1 < 2;
let gte = 2 >= 1;
let lte = 1 <= 2;
// Logical
let and = true && false;
let or = true || false;
let not = !true;
let tern = b ? 'A' : 'B';
// Control Structures
if (b) v1 = 1;
else v1 = 0;
for (let i = 0; i < 3; i++) v2 = 2;
while (b) { b = false; }
do { v1 = 1; } while (b);
switch (v1) { case 0: v2 = 1; break; default: v2 = 2; }
// Functions
function fn1() { return; }
let fn2 = function() { return; };
let fn3 = () => { return; };
// Objects
o.key = 'new value';
let val = o.key;
delete o.key;
// Arrays
a.push(4);
let first = a[0];
a[0] = 2;
a.pop();
// Loops
for (let item of a) v1 = item;
for (let key in o) val = o[key];
// Exceptions
try { throw new Error('err'); } catch (e) { v1 = 0; } finally { v2 = 1; }
// Classes
class C1 { constructor() { this.prop = 0; } method() { return this.prop; } }
// Destructuring
let { key } = o;
let [el1, el2] = a;
// Spread/Rest
let o2 = { ...o, newKey: 'newValue' };
let a2 = [...a, 5];
function fn4(...args) { return args.length; }
// Ternary
let result = n > 1 ? 'greater' : 'lesser';
// Modules
import * as mod2 from 'module';
export { fn1 };
// Promises
let p = new Promise((resolve, reject) => resolve());
p.then(() => {}).catch(() => {});
// Async/Await
async function asyncFn() { await p; }
// Generators
function* gen() { yield 1; }
// Maps & Sets
let m = new Map();
m.set('k', 'v');
let sm = new Set();
sm.add(1);
// BigInt
let bigInt = 123n;
// Optional Chaining
let chain = o?.key?.property;
// Nullish Coalescing
let nullish = v1 ?? 'default';
// Loop Control
loop1: for (let i = 0; i < 3; i++) { break loop1; }
// typeof and instanceof
let type = typeof v1;
let instance = v1 instanceof C1;
// Bitwise
let bitwiseAnd = 1 & 2;
let bitwiseOr = 1 | 2;
let bitwiseXor = 1 ^ 2;
let bitwiseNot = ~1;
let shiftLeft = 2 << 1;
let shiftRight = 2 >> 1;
let zeroFillShift = 2 >>> 1;
// Comma Operator
let comma = (v1 = 1, v2 = 2);
// in and delete
let presence = 'key' in o;
delete o.key;
// Global Objects
let date = new Date();
let reg = new RegExp('\\d+');
// JSON
let strJson = JSON.stringify(o);
let objJson = JSON.parse(strJson);
// setTimeout & setInterval
setTimeout(() => {}, 1000);
setInterval(() => {}, 1000);
// Data Manipulation
let sliceStr = s.slice(1, 3);
let sliceArr = a.slice(1, 3);
// Prototype
let proto = Object.getPrototypeOf(o);
// Property Descriptors
let descriptor = Object.getOwnPropertyDescriptor(o, 'key');
// This keyword
function fnWithThis() { this.v1 = 1; }
// New Operator
let instanceOfClass = new C1();
// eval
eval('v1 = 1;');
// Prototypal Inheritance
C1.prototype.newMethod = function() {};
// Tagged Templates
function tag(strings, ...values) { return strings[0]; }
tag`template string`;
// Array Buffer
let buffer = new ArrayBuffer(8);
// Typed Arrays
let int32 = new Int32Array(buffer);
// Floats
let float = 1.23;
// parseInt & parseFloat
let parsedInt = parseInt('123');
let parsedFloat = parseFloat('1.23');
// encodeURI & decodeURI
let uri = encodeURI('https://www.example.com/');
let original = decodeURI(uri);
// Math
let round = Math.round(1.5);
let random = Math.random();
// Unicode Escape Sequences
let unicode = '\u03A9';
// New Target
function fnWithNewTarget() { if (new.target) { v1 = 1; } }
new fnWithNewTarget();
// Object.is
let isSame = Object.is(v1, v2);
// Proxy
let proxy = new Proxy(o, {});
// Strings & Literals
const multiStr = `
string
like
this
`;
const singleStr = 'single-line';
const doubleStr = "double-line";
// Numbers
const hexNum = 0x12F;
const binNum = 0b1010;
const octNum = 0o74;
const bigNum = 1234567890n;
const floatNum = 123.456;
// Arrays
const arrayLiteral = [1, 2, 3, 4];
arrayLiteral.push(5);
const secondElement = arrayLiteral[1];
arrayLiteral[0] = 0;
const arrayLength = arrayLiteral.length;
// Sets
const setLiteral = new Set([1, 2, 3]);
setLiteral.add(4);
setLiteral.delete(2);
const hasValue = setLiteral.has(1);
// Maps (Dictionaries)
const mapLiteral = new Map([
['key1', 'value1'],
['key2', 'value2']
]);
mapLiteral.set('key3', 'value3');
const mapVal = mapLiteral.get('key1');
mapLiteral.delete('key1');
const hasKey = mapLiteral.has('key2');
// JSON
const jsonObj = {
key1: 'value1',
key2: {
subKey: 'subValue'
}
};
const jsonStringify = JSON.stringify(jsonObj);
const jsonParse = JSON.parse('{"key": "value"}');
// Object Property Descriptors
const objDesc = {
prop: 42
};
Object.defineProperty(objDesc, 'prop', {
writable: false
});
const desc = Object.getOwnPropertyDescriptor(objDesc, 'prop');
// Promises and Async
function asyncFunc() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Done!');
}, 1000);
});
}
asyncFunc()
.then(result => {
console.log(result);
})
.catch(err => {
console.log(err);
});
async function anotherAsyncFunc() {
const result = await asyncFunc();
console.log(result);
}
// Regular Expressions
const regexLiteral = /abc/g;
const regexTest = regexLiteral.test('abcdef');
const regexMatch = 'abcdef'.match(regexLiteral);
// Classes & Inheritance
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Rex');
dog.speak();
// Prototypes
const prototypeObj = {
prop: 'value'
};
Object.getPrototypeOf(prototypeObj);
Object.setPrototypeOf(prototypeObj, null);
// Iterators
const arrayToIterate = [1, 2, 3];
const iterator = arrayToIterate[Symbol.iterator]();
const iteratedVal = iterator.next();
// Symbols
const symbolLiteral = Symbol('description');
const uniqueObject = {
[symbolLiteral]: 'symbolValue'
};
// Template Literals
const variable = 'world';
const templateLiteral = `Hello, ${variable}!`;
// Object Methods
const objectToAssign = {
key1: 'value1'
};
const assignedObject = Object.assign({}, objectToAssign, {
key2: 'value2'
});
// String Methods
const stringBase = 'Hello, world!';
const slicedString = stringBase.slice(0, 5);
const replacedString = stringBase.replace('world', 'there');
// Array Methods
const arrayBase = [1, 2, 3, 4];
const filteredArray = arrayBase.filter(num => num > 2);
const mappedArray = arrayBase.map(num => num * 2);
// Destructuring with default values
const objToDestructure = {
key: 'value'
};
// Function with default parameters
function defaultParamsFunc(x = 1, y = 2) {
return x + y;
}
defaultParamsFunc();
// More Generators
function* moreGenFunc() {
yield 1;
yield 2;
yield 3;
}
const genIterator = moreGenFunc();
genIterator.next();
// For of loop
for (const element of [1, 2, 3]) {
console.log(element);
}
// For in loop
for (const property in jsonObj) {
console.log(property, jsonObj[property]);
}
// Unary Operators
const stringToNumber = +'123';
const numberToString = 123 + '';
// Void Operator
const undefinedResult = void 0;
// More Bitwise Operations
const bitwiseNotResult = ~2;
const logicalShiftRight = -2 >>> 1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment