Skip to content
Search

JavaScript

lastmod 2026-04-01created 2014-02-04207 edits

JavaScript is an object-based scripting programming language. It is best known for its use on websites, but it can also access the built-in objects of other applications. JavaScript was originally developed by Brendan Eich of Netscape Communications Corporation, first under the name Mocha and later under the name LiveScript, and finally became JavaScript. JavaScript has a syntax similar to Sun Microsystems' Java in some respects, but this is because both languages are based on the basic syntax of the C language; Java and JavaScript are not directly related. Apart from the name and syntax, it has more in common with Self than with Java.

As of 2008, the latest version is JavaScript 1.8, which is supported in Firefox 3. The JavaScript version corresponding to the 3rd edition of the ECMA-262 standard is 1.5. Simply put, ECMAScript is the standardized version of JavaScript. With Mozilla 1.8 Beta 1, partial support was added for E4X (ECMA-357), an extension language for XML. The supported version of JavaScript differs from browser to browser, and the most widely supported version is 1.5.

Categories

TypeScript

Runtime

  • Ion.js - A high-performance JavaScript runtime for Rust
  • MicroQuickJS - An ultra-lightweight JavaScript engine designed for embedded systems, able to run with only about 10kB of RAM and 100kB of ROM
  • deno
  • edgejs - A secure WebAssembly-based JS runtime
  • node

Web API

Java vs JavaScript vs JScript

LiveScript was renamed JavaScript at roughly the time Netscape began including support for Java technology in its Netscape Navigator web browser. JavaScript was released and adopted starting with Netscape 2.0B3, released in December 1995. The name JavaScript caused considerable confusion. This is because Java and JavaScript had no real relationship apart from their similar syntax (since both were based on C). The two languages are semantically very different; in particular, their object models are unrelated and largely incompatible.

Spurred by JavaScript's success as a language for enhancing web pages, Microsoft developed a compatible language known as JScript. JScript was first supported in the Internet Explorer 3.0 browser, released in August 1996. Using JavaScript in the IE browser actually meant using JScript. The demand for standardization that followed became the basis of the ECMA-262 standard for ECMAScript, which has been published up to its third edition since November 1996. DOM, a term often used together with JavaScript, is in fact not part of the ECMAScript standard; it is a standard in its own right and is based on XML.

Echosystem

JavaScript is the most widely used programming language, running on every device with a web browser. Over the past 10 years, a huge ecosystem has been built around JavaScript.

  • Webpack: Developers wanted to bundle multiple JavaScript files into one. (bundler)
  • Babel: Developers wanted to write modern JavaScript while supporting older browsers. (transcompilation)
  • Terser: Developers wanted to generate the smallest possible file sizes.
  • Prettier: Developers wanted an opinionated code formatter that just worked.
  • ESLint: Developers wanted to find problems in their code before deploying.

Millions of lines of code have been written and even more bugs fixed, forming the foundation for delivering web applications today. All of these tools are written in JavaScript or TypeScript. This worked well, but optimization with JS has hit its limit. This has inspired a new class of tools designed to drastically improve build performance for the web.

ECMAScript

See the corresponding page.

Curriculum

Start from JavaScript:Basic.

How to create a library

Refer to the packages.json of Tailwind Elements.

Syntax

Class prototype

function Apple (type) {
    this.type = type;
    this.color = "red";
    this.getInfo = function() {
        return this.color + ' ' + this.type + ' apple';
    };
}

// Use:
var apple = new Apple('macintosh');
apple.color = "reddish";
alert(apple.getInfo());

class version:

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  // Getter
  get area() {
    return this.calcArea();
  }
  // Method
  calcArea() {
    return this.height * this.width;
  }
}

const square = new Rectangle(10, 10);
console.log(square.area); // 100

How to check whether a property is included

Standard objects by category

Value properties

These global properties return a simple value and have no properties or methods.

  • Infinity
  • NaN
  • undefined
  • null literal
  • globalThis

Function properties

Functions that are called globally rather than attached to an object, returning their return value directly to the caller.

  • eval()
  • uneval() - This API has not been standardized.
  • isFinite()
  • isNaN()
  • parseFloat()
  • parseInt()
  • encodeURI()
  • encodeURIComponent()
  • decodeURI()
  • decodeURIComponent()

Deprecated:

  • escape()
  • unescape()

Fundamental objects

The fundamental, basic objects upon which all other objects are based. They include objects representing general objects, functions, and errors.

Error objects

Error objects are a special type of fundamental object. They include the basic Error object as well as error types optimized for specific purposes.

  • Error
  • AggregateError
  • EvalError
  • InternalError
  • RangeError
  • ReferenceError
  • SyntaxError
  • TypeError
  • URIError

Numbers and dates

Basic objects representing numbers, dates, and mathematical calculations.

  • Number
  • BigInt
  • Math
  • Date

Text processing

Objects that represent strings and also provide ways to manipulate them.

  • String
  • RegExp

Indexed collections

Represent collections of data ordered by an index value. They include arrays (including typed arrays) and array-like objects.

  • Array
  • Int8Array
  • Uint8Array
  • Uint8ClampedArray
  • Int16Array
  • Uint16Array
  • Int32Array
  • Uint32Array
  • Float32Array
  • Float64Array
  • BigInt64Array
  • BigUint64Array

Keyed collections

Represent collections that use keys. Iterable collections such as Map and Set can iterate over their elements in insertion order.

  • Map
  • Set
  • WeakMap
  • WeakSet

Structured data

Represent and interact with structured data buffers and data written using JavaScript Object Notation (JSON).

Control abstraction objects

Control abstractions help structure code. In particular, they let you write asynchronous code without (for example) deeply nested callback functions.

Reflection

  • Reflect
  • Proxy

Internationalization

Language-sensitive features added to the ECMAScript core.

  • Intl
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.ListFormat
  • Intl.NumberFormat
  • Intl.PluralRules
  • Intl.RelativeTimeFormat
  • Intl.Locale

WebAssembly

  • WebAssembly
  • WebAssembly.Module
  • WebAssembly.Instance
  • WebAssembly.Memory
  • WebAssembly.Table
  • WebAssembly.CompileError
  • WebAssembly.LinkError
  • WebAssembly.RuntimeError

Other

  • arguments

Events

Types of events and their meanings: (event handlers prefix the event name with on)

  • blur when focus moves elsewhere
  • click when a link or form element is clicked
  • change when the selected value changes
  • focus when focus is placed
  • mouseover when the mouse moves over
  • mouseout when the mouse leaves
  • mousedown when the mouse button is pressed
  • mousemove when the mouse moves
  • mouseup when the mouse button is pressed and released
  • select when one of the input fields is selected
  • submit when a form is submitted
  • load when a page or window is loaded by the browser
  • unload when leaving the current browser or window
  • error when an error occurs in a document or image
  • reset when the reset button is pressed
  • dbclick on double-click
  • dragdrop when the mouse is pressed and moved
  • keydown on key input
  • keypress when a key is pressed
  • keyup when a key is pressed and released
  • move when a window or frame is moved
  • resize when a window or frame is resized

Methods:

  • blur() moves the input focus elsewhere
  • click() acts as if the mouse button was pressed
  • focus() acts as if the input focus was given
  • submit() acts as if the form's submit button was pressed
  • select() method selects a specific input field of the form

Properties:

  • event.keyCode the ASCII integer value of the pressed key
  • event.x left of the pressed coordinates, relative to the document
  • event.y top of the pressed coordinates, relative to the document
  • event.clientX left of the pressed coordinates, relative to the document
  • event.clientY top of the pressed coordinates, relative to the document
  • event.screenX left of the pressed coordinates, relative to the container
  • event.screenY top of the pressed coordinates, relative to the container

Event handlers by browser object:

  • Selection list (SELECT) onBlur, onChange, onFocus
  • Text field (TEXT) onBlur, onChange, onFocus, onSelect
  • Text area (TEXTAREA) onBlur, onChange, onFocus, onSelect
  • Button (BUTTON) onClick
  • Checkbox (CHECKBOX) onClick
  • Radio button (RADID) onClick
  • Link onClick, onMouseover
  • RESET button (RESET) onClick
  • SUBMIT button (BUTTON) onClick
  • DOCUMENT onLoad, onUnload
  • WINDOW onLoad, onUnload
  • Form (FORM) onSubmit

DOMContentLoaded/Load/BeforeUnload/Unload

Three main events are involved in the lifecycle of an HTML document.

  • DOMContentLoaded – Fires as soon as the browser has fully read the HTML and built the DOM tree. It does not wait for other resources such as image files (<img>) or stylesheets.
  • load – Fires when not only has the DOM tree been built from the HTML, but all external resources such as images and stylesheets have also finished loading.
  • beforeunload/unload – Fires when the user leaves the page.

The three events can be used in the following situations.

  • DOMContentLoaded – When initializing the interface by finding the desired DOM nodes and registering handlers after confirming that the DOM is ready
  • load – When checking image sizes, etc. Since it comes after external resources are loaded, styles have been applied, so you can check the actual size of elements rendered on screen
  • beforeunload – When the user is about to leave the site, to check whether they have saved unsaved changes
  • unload – When you want to send statistics containing user analytics before the user actually leaves

Tip

For basic debugging, you can use the functions below.

console.log(...);
console.error(...);
console.info(...);
console.warn(...);

for...of vs for...in

for...of
Creates a loop that iterates over iterable objects (including Array, Map, Set, String, TypedArray, the arguments object, etc.), invoking a custom iteration hook with statements to be executed for each individual property value.

:

const array1 = ['a', 'b', 'c'];
for (const element of array1) {
  console.log(element);
}

// "a"
// "b"
// "c"
for...in
Iterates over all enumerable properties of an object that are keyed by strings, including inherited enumerable properties. (Properties keyed by Symbols are ignored.)

:

const array1 = ['a', 'b', 'c'];
for (const element in array1) {
  console.log(element);
}

// "0"
// "1"
// "2"

Remove element in array

array.splice(index, 1);

Number sort

The sort() method sorts the elements of an array In-Place and returns the sorted array. The default sort order is ascending, and it converts the elements to strings and then compares their sequences of UTF-16 code unit values.

The time and space complexity of the sort depends on the implementation and cannot be guaranteed.

var score = [4, 11, 2, 10, 3, 1]; 

/* 오류 */
score.sort(); // 1, 10, 11, 2, 3, 4 
              // ASCII 문자 순서로 정렬되어 숫자의 크기대로 나오지 않음

/* 정상 동작 */
score.sort(function(a, b) { // 오름차순
    return a - b;
    // 1, 2, 3, 4, 10, 11
});

score.sort(function(a, b) { // 내림차순
    return b - a;
    // 11, 10, 4, 3, 2, 1
});

module.exports vs exports

The require keyword returns an object. module.exports and exports point to the same object by Call by reference, and the returned value is always module.exports.

In other words, a module is basically an object, both module.exports and exports point to this object, and what is ultimately Returned is always module.exports.

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res) {
    res.render('index', { title: 'Express' });
});

module.exports = router;

The source above can be interpreted as follows: some properties of the "object" returned by express.Router() are modified, and then this object itself is returned as the module.

'use strict'

strict mode is a keyword added in ES5(ECMA Script 5).

strict mode raises error messages for errors that JavaScript used to silently ignore. You can think of it as "I will check syntax strictly."

Declaring "use strict" (or 'use strict') at the start of a script or function lets you write code in strict mode.

with keyword

By analogy, it can be used in the same sense as namespace in C++.

The @ symbol in imports

It can be used as a string that is substituted in a file such as config.json.

resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
    '@': path.join(__dirname, '..', dir)
    }
},

onClick on mobile devices

On mobile, you must write javascript in events and the like.

<!-- ... -->
<a href="javascript:funcBoo()">클릭</a>
<!-- ... -->
<span onclick="javascript:funcBoo()">클릭</span>
<!-- ... -->

Equal to(==) vs Strict equal(===)

typeof vs instanceof

typeof returns the primitive type of the given variable as a string. The primitive types it returns are as follows.

  • 'undefined'
  • 'boolean'
  • 'number'
  • 'string'
  • 'object'
  • 'function'

Since it returns one of the basic types above as a string, you can tell which type it is by comparing strings. That is, to determine whether something is an object using typeof, do the following.

if(typeof yourVariable === 'object') {
    /* 오브젝트 처리 */
}

instanceof "compares" using the prototype.

Default condition check

At least know what happens when you put a value directly into a conditional statement (if (statements) { ... }). Comparison table:

Statements

Result

undefined

false

null

false

Empty Array object (e.g. new Array<string>())

true

Empty Map object (e.g. new Map<string, string>())

true

Empty String object (e.g. new String())

true

Empty object (e.g. {})

true

Empty string (e.g. "")

false

0

false

var, let, const

The differences are as follows:

  • var: Function scoped, mutable
  • let: Block scoped, mutable
  • const: Block scoped, immutable

(function(global){...})(this)

The function is immediately executed, you do not execute it by calling it.

(function(global) {
    // the function code comes here
})(this);

Removing the decimal part

It can be removed with a bitwise operation as below.

console.log(0.5 | 0); // 0
console.log(-1 | 0);  // -1
console.log(1 | 0);   // 1

fmt-style formatting strings

console.log(`This is ${soMany} times easier!`);

To JSON String

The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.

JSON.stringify(obj);

How to insert a comma every 3 digits (thousands separator)

Using a regular expression:

const n1 = 12345.6789;
const n2 = -12345.6789;

const cn1 = n1.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ","); // 12,345.6789
const cn2 = n2.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ","); // -12,345.6789

Using the toLocaleString function.

const n1 = 12345.6789;
const n2 = -12345.6789;

const cn1 = n1.toLocaleString('ko-KR'); // 12,345.679
const cn2 = n2.toLocaleString('ko-KR'); // -12,345.679

Select content

function selectText(containerid) {
    if (document.selection) {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(containerid));
        range.select();
    } else if (window.getSelection) {
        var range = document.createRange();
        range.selectNode(document.getElementById(containerid));
        window.getSelection().addRange(range);
    }
}

Style animation Property

// Code for Safari 4.0 - 8.0
document.getElementById("myDIV").style.WebkitAnimation = "mynewmove 4s 2";

// Standard syntax
document.getElementById("myDIV").style.animation = "mynewmove 4s 2";

XMLHttpRequest send

<!DOCTYPE html>
<html lang='en'>
<head>
    <meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
    <script>
    function onLoad() {
        var oReq = new XMLHttpRequest();
        oReq.addEventListener("load", function() {
            console.log('Response Text:');
            console.log(this.responseText);
        });
        oReq.open("GET", "test2.html");
        oReq.send();
    }
    </script>
</head>
<body onload='onLoad()'>
</body>
</html>

Errors

A list of errors commonly encountered in javascript:

  • Uncaught TypeError: Cannot read property - ...
  • TypeError: 'undefined'is not an object (evaluating - ...
  • TypeError: null is not an object (evaluating - ...
  • (unknown): Script error - ...
  • TypeError: Object doesn't support property - ...
  • Type Error: 'undefined' is not a function - ...
  • Uncaught RangeError: Maximum call stack - ...
  • TypeError: Cannot read property 'length' - ...
  • Uncaught TypeError: Cannot set property - ...
  • ReferenceError: event is not defined - ...

How to use JavaScript libraries without a build system

When writing JavaScript without a build system, importing libraries can be complicated, because many libraries write their setup instructions assuming you use a build system.

  • The three main file formats provided by JavaScript libraries
  • How to identify the file format from a library's build files
  • How to import each file format

Example

A collection of Javascript example code.

Hello world

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html" charset="UTF-8" />
    <title>자바스크립트 페이지</title>
    <script type="text/javascript">
        document.write("<p>Hello World!</p>");
    </script>
</head>
<body>
    <noscript> 
    <p>브라우저가 자바스크립트 기능을 지원하지 않거나 자바스크립트 기능이 꺼져 있습니다.</p>
    </noscript>
</body>
</html>

Implementing an SPA routing system

async function

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');
  const result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: "resolved"
}

asyncCall();

Getting the last day of the month

// 3월 1일
let date = new Date(2019, 2, 1);
document.write(date.toLocaleString()  + '<br>');

// 2월 28일(말일)
let lastDate = new Date(2019, 2, 0);
document.write(lastDate.toLocaleString()  + '<br>');
document.write(lastDate.getDate() + '<br>');

// 2월 27일
let lastDateBefore = new Date(2019, 2, -1);
document.write(lastDateBefore.toLocaleString()  + '<br>');

RGB to HEX convert

function componentToHex(c: number) {
  const hex = c.toString(16);
  return hex.length == 1 ? '0' + hex : hex;
}

function rgbToHex(r: number, g: number, b: number) {
  return '#' + componentToHex(r) + componentToHex(g) + componentToHex(b);
}

function hexToRgb(hex: string) {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16),
  } : undefined;
}

Video PlayList Autoplay

let videoSource = new Array();
videoSource[0] = 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4';
videoSource[1] = 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerEscapes.mp4';
let i = 0; // global
const videoCount = videoSource.length;
const element = document.getElementById("videoPlayer");

function videoPlay(videoNum) {
    element.setAttribute("src", videoSource[videoNum]);
    element.autoplay = true;
    element.load();
}
document.getElementById('videoPlayer').addEventListener('ended', myHandler, false);

videoPlay(0); // load the first video
ensureVideoPlays(); // play the video automatically

function myHandler() {
    i++;
    if (i == videoCount) {
        i = 0;
        videoPlay(i);
    } else {
        videoPlay(i);
    }
}

function ensureVideoPlays() {
    const video = document.getElementById('videoPlayer');

    if(!video) return;

    const promise = video.play();
    if(promise !== undefined){
        promise.then(() => {
            // Autoplay started
        }).catch(error => {
            // Autoplay was prevented.
            video.muted = true;
            video.play();
        });
    }
}

Documentation

JavaScript - The Good Parts
http://bdcampbell.net/javascript/book/javascript_the_good_parts.pdf
Javascript_the_good_parts.pdf

Troubleshooting

App not updated to the latest version after deployment unless the browser cache is cleared

See Cache Busting.

See also

Favorite site

Online Tools

=

  • JavaScript engines zoo - Compares 114 JS engines
    • Compares various JS engines developed in C/C++/C#/D/Go/Haskell/Java/JS/TS/Lisp/Lua/Pascal/Python, etc.
    • Organizes benchmark scores (based on V8's tests), binary size, LOC, whether there is a JIT, ES support coverage, GitHub star count, license, short description, etc. in a table
      • Provides separate benchmark results for arm64 (Mac M4 3.5Ghz) and amd64 (i9-10900K 3.7Ghz)
    • Code provided in the GitHub Repo: Dockerfiles for the engines, a unified JSON of engine information, benchmark and Conformance information

Tutorials

Guide

Problems

Debugging

Article

References


  1. JavaScript:Libraries, JavaScript:Library, Node.js:Libraries, Npm:Libraries, Node:Libraries, TypeScript:Libraries, CSS:Libraries, HTML:Libraries, WebProgramming:Libraries, Frontend:Libraries all link to the same page. ↩

  2. Looah_-_How_it_feels_to_learn_JavaScript_in_2016.pdf ↩

  3. Vanilla_JS_-spa_route_tutorial-_Dev_DY.pdf ↩

  4. JavaScript_Garden.pdf ↩

  5. Deadfire_hihome_com.7z ↩

  6. Math88_com_ne_kr-computer-js-JSmanual.zip ↩

  7. A_Study_Plan_To_Cure_JavaScript_Fatigue_-_ko.pdf ↩

  8. Meetup_TOAST_Cloud_-_JavaScript_and_Event_Loop.pdf ↩

  9. Create_the_latest_JavaScript_web_frontend_development_environment_with_Webpack_and_Babel.pdf ↩

  10. Looah_-_How_it_feels_to_learn_JavaScript_in_2016.pdf ↩

  11. Javascript-audio-effectors-practice_-_Evans_Library.pdf ↩

author Zer0 sitemap