Questions tagged [javascript]

For questions about programming in ECMAScript (JavaScript/JS) and its different dialects/implementations (except for ActionScript). Note that JavaScript is NOT Java. Include all tags that are relevant to your question: e.g., [node.js], [jQuery], [JSON], [ReactJS], [angular], [ember.js], [vue.js], [typescript], [svelte], etc.

JavaScript (a dialect of ECMAScript) is a high-level, dynamic, multi-paradigm, object-oriented, prototype-based, weakly-typed, and interpreted language traditionally used for client-side scripting in web browsers. JavaScript can also be run outside the browser using a framework like Node.js, Nashorn, Wakanda, or Google Apps Script. Despite the name, it is unrelated to the Java programming language and shares only superficial similarities.

When asking a JavaScript question, you should:

  1. Debug your JavaScript code (see Creativebloq, MDN, Google, & MSDN).
  2. Isolate the problematic code and reproduce it in a Stack Overflow code snippet or an external online environment such as JSFiddle, JS Bin or PasteBin (remember to also include the code in the question itself). When possible, prefer to use Stack Overflow code snippets over external sites.
  3. If a library or framework is used, then tag the question with the appropriate tags: for jQuery, for Prototype, for MooTools, and so on. However, if a framework is not used or necessary, do not include these tags.
  4. If the issue is client-side, mention which browser the code is having problems on, and what error messages, if any, were thrown by the browser. Use the Developer Tools for your browser (see "Useful Tools" below) to see these messages. If the question is browser-specific, use tags , , , , , , etc.
  5. Only tag the question as or if you are asking about an issue that concerns the combination of one of those with JavaScript and could only be answered with information specifically regarding either of those subjects.

Note: Unless a tag for a framework or library is also included, a pure JavaScript answer is expected for questions with the tag.

About JavaScript

JavaScript runs on nearly every operating system, and an engine is included in mainstream web browsers. Developed in 1995 by Brendan Eich at Netscape Communications, it was originally called LiveScript but was renamed to JavaScript due to Netscape's friendly relationship with Sun Microsystems (creators of Java) at the time.

Stand-alone JavaScript engines or interpreters are available as well, including:

  • Mozilla's Spidermonkey is the first JavaScript engine ever written and currently used in Mozilla Firefox.
  • Google's JavaScript engine, Chrome V8 used in Google Chrome and Chromium.
  • Google Apps Script, a cloud-based/server-side interpreter that provides programmatic "macro-like" control of Google Apps services and documents.
  • Node.js, built on top of V8, a platform that enables server-side applications to be written in JavaScript.
  • Windows includes JScript, a JavaScript variant in Windows Script Host.
  • Chakra, a fork of JScript, is developed by Microsoft and used in Edge;
  • Mozilla also offers Rhino an implementation of JavaScript built-in Java, typically embedded into Java applications to provide scripting to end-users.
  • WebKit (except for the Chromium project) implements the JavaScriptCore engine.
  • ActionScript (derived initially from HyperTalk) is now an ECMAScript dialect and uses a lot of ECMAScript APIs.
  • Duktape Embeddable, a portable ECMAScript engine in C with a small memory footprint.
  • Wakanda, a framework, IDE, and Server built on V8 supporting server-side JavaScript.
  • Meteor: a Meteor application is a mix of client-side JavaScript that runs inside a web browser or PhoneGap mobile app and the server-side JavaScript that runs on the Meteor server inside a Node.js container. (according to Meteor documentation).
  • Nashorn, a JavaScript engine developed in the Java programming language, based on the Da Vinci Machine (JSR 292).

The Mozilla Developer Network contains high-quality documentation on JavaScript.

JavaScript is typically used to manipulate the Document Object Model (DOM) and Cascading Style Sheets (CSS) within the browser. This allows user interface scripting, animation, automation, client-side validation and more.

With the recent emergence of platforms such as Node.js, JavaScript can now be used to write server-side applications. In addition, it is also used in environments that aren't web-based, like PDF documents, site-specific browsers, desktop widgets, etc.

Nomenclature

Although it was developed under the name Mocha, the language was officially called LiveScript when it first shipped in beta releases of Netscape Navigator 2.0 in September 1995, but it was renamed JavaScript when it was deployed in the Netscape browser version 2.0B3.

The name change from LiveScript to JavaScript roughly coincided with Netscape adding support for Java technology in its Netscape Navigator web browser. The final choice of name caused confusion, giving the impression that the language was a spin-off of the Java programming language, and the choice has been characterized as a marketing ploy by Netscape to give JavaScript prestige by connection (if in name only) with what was then the hot, new web-programming language.

People often use the term JavaScript informally. The language and the term originated from Netscape. ECMAScript, JavaScript, and JScript are terms that are easy to confuse.

ECMAScript was developed as a standardization of Netscape's JavaScript and Microsoft's independently-developed JScript. The canonical reference is the ECMAScript® 2015 Language Specification. While JavaScript and JScript aim to be compatible with ECMAScript, they also provide additional features (and other deviations) not described in the ECMA specifications. Other implementations of ECMAScript also exist.

The differences today for those who use JavaScript are negligible; people generally do not distinguish the JavaScript and JScript variations from ECMAScript.

ECMAScript versions

Most modern browsers implement JavaScript based on the ECMAScript 6 specification, although some fail to implement some ES6 features. However, older browsers such as Internet Explorer 8 implement the ECMAScript 3 specification, which does not contain functions such as Function.prototype.bind or even JSON.parse, among others. You can see the current browser support of ES6 features

The current version of ECMAScript is ECMAScript 12, properly known as ECMAScript 2021, which was published in June 2021.

Example JavaScript code

This script displays "Hello World" in a browser, once the website it is contained in finished loading.

window.onload = function() {
    alert('Hello World!');
};

Demo!

Learning JavaScript

Interactive JavaScript learning

Free JavaScript Programming Books

Videos

Security

JavaScript and the DOM provide the potential for entities with malicious intent to deliver scripts that run on a client computer via the Web. Developers of browsers contain this risk using two restrictions. First, scripts run in a sandbox where they can only perform web-related actions, not general-purpose programming tasks such as creating files. Second, scripts are constrained by the same-origin policy: scripts from one website do not have access to information such as usernames, passwords, or cookies sent to another site. Most JavaScript-related security bugs are breaches of either the same-origin policy or the sandbox.

Content Security Policy is the primarily intended method of ensuring that only trusted code is executed on a webpage.

Cross-site scripting (XSS) attacks are attempts to steal data or harm a website via JavaScript.

Useful Tools

Wisdom from Stack Overflow

Useful links

Frequently Asked Questions

Find some answers to some of the more frequently asked questions about JavaScript and related technology below.

Q: I have this JSON structure. How can I access property x.y.z? A: How can I access and process nested objects, arrays, or JSON?

Q: I'm adding events in a for loop, but all handlers do the same thing. Why? A: JavaScript closure inside loops – simple practical example

Q: I want to compare something against multiple values. Is there an easy way to do it? A: Concise way to compare against multiple values

Q: How to set up proper inheritance? A: Objects don't inherit prototyped functions

Q: How do JavaScript closures work? A: How do JavaScript closures work?

Q: Why does setTimeout() inside a for loop always use the latest value? A: setTimeout in for-loop does not print consecutive values

Q: How to return the response from an AJAX call from a function? A: How do I return the response from an asynchronous call?

Q: Why don't my handlers hooked up in a loop work correctly, and what can I do about it? A: Javascript: generate dynamically handler

Q: How can I get query string values? A: How can I get query string values in JavaScript?

Q: What does use strict do in JavaScript? A: What does "use strict" do in JavaScript, and what is the reasoning behind it?

Q: How can I make a redirect page in jQuery/JavaScript? A: How do I redirect to another webpage?

Q: How to sort an array of objects by a property value? A: Sort array of objects by string property value

Q: From an array of objects, how do I extract the value of a property as an array? A: From an array of objects, extract value of a property as array

Q: I'm adding elements with JavaScript or jQuery at a later point and adding events, but they're not firing. Why? A: You might want event delegation.

Q: How can I only keep items of an array that match a specific condition? A: How can I only keep items of an array that match a certain condition?

Q: How can I debug my JavaScript code? A: How can I debug my JavaScript code?

Q: What does this symbol mean in JavaScript? A: What does this symbol mean in JavaScript?

More information

Chat Room

2510972 questions
3256
votes
15 answers

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

Mod note: This question is about why XMLHttpRequest/fetch/etc. on the browser are subject to the Same Access Policy restrictions (you get errors mentioning CORB or CORS) while Postman is not. This question is not about how to fix a "No…
Mr Jedi
  • 33,658
  • 8
  • 30
  • 40
3232
votes
69 answers

How can I merge properties of two JavaScript objects dynamically?

I need to be able to merge two (very simple) JavaScript objects at runtime. For example I'd like to: var obj1 = { food: 'pizza', car: 'ford' } var obj2 = { animal: 'dog' } obj1.merge(obj2); //obj1 now has three properties: food, car, and…
JC Grubbs
  • 39,191
  • 28
  • 66
  • 75
3228
votes
14 answers

event.preventDefault() vs. return false

When I want to prevent other event handlers from executing after a certain event is fired, I can use one of two techniques. I'll use jQuery in the examples, but this applies to plain-JS as well: 1. event.preventDefault() $('a').click(function (e) { …
RaYell
  • 69,610
  • 20
  • 126
  • 152
3221
votes
45 answers

JavaScript closure inside loops – simple practical example

var funcs = []; // let's create 3 functions for (var i = 0; i < 3; i++) { // and store them in funcs funcs[i] = function() { // each should log its value. console.log("My value:", i); }; } for (var j = 0; j < 3; j++) { // and now…
nickf
  • 537,072
  • 198
  • 649
  • 721
3201
votes
49 answers

Detecting an undefined object property

How do I check if an object property in JavaScript is undefined?
Matt Sheppard
  • 116,545
  • 46
  • 111
  • 131
3151
votes
20 answers

Is it possible to apply CSS to half of a character?

What I am looking for: A way to style one HALF of a character. (In this case, half the letter being transparent) What I have currently searched for and tried (With no luck): Methods for styling half of a character/letter Styling part of a character…
SimplyAzuma
  • 25,214
  • 3
  • 23
  • 39
3134
votes
34 answers

How can I upload files asynchronously with jQuery?

I would like to upload a file asynchronously with jQuery. $(document).ready(function () { $("#uploadbutton").click(function () { var filename = $("#file").val(); $.ajax({ type: "POST", url:…
Sergio del Amo
  • 76,835
  • 68
  • 152
  • 179
3127
votes
47 answers

Is there an "exists" function for jQuery?

How can I check the existence of an element in jQuery? The current code that I have is this: if ($(selector).length > 0) { // Do something } Is there a more elegant way to approach this? Perhaps a plugin or a function?
Jake McGraw
  • 55,558
  • 10
  • 50
  • 63
3051
votes
40 answers

How can I know which radio button is selected via jQuery?

I have two radio buttons and want to post the value of the selected one. How can I get the value with jQuery? I can get all of them like this: $("form :radio") How do I know which one is selected?
juan
  • 80,295
  • 52
  • 162
  • 195
3046
votes
24 answers

How to store objects in HTML5 localStorage/sessionStorage

I'd like to store a JavaScript object in HTML5 localStorage, but my object is apparently being converted to a string. I can store and retrieve primitive JavaScript types and arrays using localStorage, but objects don't seem to work. Should…
Kristopher Johnson
  • 81,409
  • 55
  • 245
  • 302
3026
votes
47 answers

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

Is there a universal JavaScript function that checks that a variable has a value and ensures that it's not undefined or null? I've got this code, but I'm not sure if it covers all cases: function isEmpty(val){ return (val === undefined || val ==…
Alex
  • 34,699
  • 13
  • 75
  • 158
3022
votes
16 answers

How can I check for "undefined" in JavaScript?

What is the most appropriate way to test if a variable is undefined in JavaScript? I've seen several possible ways: if (window.myVariable) Or if (typeof(myVariable) != "undefined") Or if (myVariable) // This throws an error if undefined. Should…
makerofthings7
  • 60,103
  • 53
  • 215
  • 448
3000
votes
41 answers

How do I pass command line arguments to a Node.js program and receive them?

I have a web server written in Node.js and I would like to launch with a specific folder. I'm not sure how to access arguments in JavaScript. I'm running node like this: $ node server.js folder here server.js is my server code. Node.js help says…
milkplus
  • 33,007
  • 7
  • 30
  • 31
2999
votes
33 answers

Using async/await with a forEach loop

Are there any issues with using async/await in a forEach loop? I'm trying to loop through an array of files and await on the contents of each file. import fs from 'fs-promise' async function printFiles () { const files = await getFilePaths() //…
Saad
  • 49,729
  • 21
  • 73
  • 112
2995
votes
44 answers

Length of a JavaScript object

I have a JavaScript object. Is there a built-in or accepted best practice way to get the length of this object? const myObject = new Object(); myObject["firstname"] = "Gareth"; myObject["lastname"] = "Simpson"; myObject["age"] = 21;
Gareth Simpson
  • 36,943
  • 12
  • 47
  • 50