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.

Filter by
Sorted by
Tagged with
11647 votes
149 answers

How can I remove a specific item from an array in JavaScript?

How do I remove a specific value from an array? Something like: array.remove(value); Constraints: I have to use core JavaScript. Frameworks are not allowed.
Walker's user avatar
  • 129k
8619 votes
65 answers

How do I check if an element is hidden in jQuery?

How do I toggle the visibility of an element using .hide(), .show(), or .toggle()? How do I test if an element is visible or hidden?
Philip Morton's user avatar
8431 votes
31 answers

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

Recently, I ran some of my JavaScript code through Crockford's JSLint, and it gave the following error: Problem at line 1 character 1: Missing "use strict" statement. Doing some searching, ...
Mark Rogers's user avatar
  • 96.6k
7702 votes
58 answers

How do I redirect to another webpage?

How can I redirect the user from one page to another using jQuery or pure JavaScript?
venkatachalam's user avatar
7619 votes
86 answers

How do JavaScript closures work?

How would you explain JavaScript closures to someone with a knowledge of the concepts they consist of (for example functions, variables and the like), but does not understand closures themselves? I ...
7588 votes
41 answers

var functionName = function() {} vs function functionName() {}

I've recently started maintaining someone else's JavaScript code. I'm fixing bugs, adding features and also trying to tidy up the code and make it more consistent. The previous developer used two ways ...
Richard Garside's user avatar
7406 votes
3 answers

How to check whether a string contains a substring in JavaScript?

Usually I would expect a String.contains() method, but there doesn't seem to be one. What is a reasonable way to check for this?
7406 votes
38 answers

How do I remove a property from a JavaScript object?

Given an object: let myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*" }; How do I remove the property ...
johnstok's user avatar
  • 96.4k
6629 votes
42 answers

How do I return the response from an asynchronous call?

How do I return the response/result from a function foo that makes an asynchronous request? I am trying to return the value from the callback, as well as assigning the result to a local variable ...
Felix Kling's user avatar
6256 votes
71 answers

How do I include a JavaScript file in another JavaScript file?

How do I include a JavaScript file inside another JavaScript file, similar to @import in CSS?
Alec Smart's user avatar
  • 94.2k
6172 votes
38 answers

What is the difference between "let" and "var"?

ECMAScript 6 introduced the let statement. I've heard that it's described as a local variable, but I'm still not quite sure how it behaves differently than the var keyword. What are the differences? ...
TM.'s user avatar
  • 108k
5647 votes
48 answers

Which equals operator (== vs ===) should be used in JavaScript comparisons?

I'm using JSLint to go through JavaScript, and it's returning many suggestions to replace == (two equals signs) with === (three equals signs) when doing things like comparing idSele_UNVEHtype.value....
bcasp's user avatar
  • 57.4k
5628 votes
41 answers

Loop (for each) over an array in JavaScript

How can I loop through all the entries in an array using JavaScript?
Dante1986's user avatar
  • 58.4k
5476 votes
79 answers

How can I validate an email address in JavaScript?

I'd like to check if the user input is an email address in JavaScript, before sending it to a server or attempting to send an email to it, to prevent the most basic mistyping. How could I achieve this?...
5412 votes
78 answers

How do I replace all occurrences of a string in JavaScript?

Given a string: s = "Test abc test test abc test test test abc test test abc"; This seems to only remove the first occurrence of abc in the string above: s = s.replace('abc', ''); How do I ...
Ali's user avatar
  • 262k
5283 votes
73 answers

How do I create a GUID / UUID?

How do I create GUIDs (globally-unique identifiers) in JavaScript? The GUID / UUID should be at least 32 characters and should stay in the ASCII range to avoid trouble when passing them around. I'm ...
5168 votes
67 answers

What is the most efficient way to deep clone an object in JavaScript?

What is the most efficient way to clone a JavaScript object? I've seen obj = eval(uneval(o)); being used, but that's non-standard and only supported by Firefox. I've done things like obj = JSON.parse(...
5150 votes
68 answers

How do I check whether a checkbox is checked in jQuery?

I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery. For example, if the age checkbox is checked, then I need to show a textbox to enter ...
5121 votes
102 answers

How do I make the first letter of a string uppercase in JavaScript?

How do I make the first character of a string uppercase if it's a letter, but not change the case of any of the other letters? For example: "this is a test" → "This is a test" &...
Robert Wills's user avatar
  • 51.9k
4856 votes
62 answers

How do I check if an array includes a value in JavaScript?

What is the most concise and efficient way to find out if a JavaScript array contains a value? This is the only way I know to do it: function contains(a, obj) { for (var i = 0; i < a.length; i++...
brad's user avatar
  • 73.9k
4777 votes
43 answers

How do I get a timestamp in JavaScript?

I want a single number that represents the current date and time, like a Unix timestamp.
Pablo Fernandez's user avatar
4557 votes
44 answers

Setting "checked" for a checkbox with jQuery

I'd like to do something like this to tick a checkbox using jQuery: $(".myCheckBox").checked(true); or $(".myCheckBox").selected(true); Does such a thing exist?
tpower's user avatar
  • 56.1k
4506 votes
15 answers

"Thinking in AngularJS" if I have a jQuery background? [closed]

Suppose I'm familiar with developing client-side applications in jQuery, but now I'd like to start using AngularJS. Can you describe the paradigm shift that is necessary? Here are a few questions that ...
Mark Rajcok's user avatar
4463 votes
8 answers

Why does Google prepend while(1); to their JSON responses?

Why does Google prepend while(1); to their (private) JSON responses? For example, here's a response while turning a calendar on and off in Google Calendar: while (1); [ ['u', [ ['smsSentFlag', ...
Jess's user avatar
  • 42.4k
4410 votes
56 answers

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

The following are two methods of building a link that has the sole purpose of running JavaScript code. Which is better, in terms of functionality, page load speed, validation purposes, etc.? ...
4346 votes
27 answers

How do I copy to the clipboard in JavaScript?

How do I copy text to the clipboard (multi-browser)? Related: How does Trello access the user's clipboard?
Santiago Corredoira's user avatar
4177 votes
32 answers

How to insert an item into an array at a specific index?

I am looking for a JavaScript array insert method, in the style of: arr.insert(index, item) Preferably in jQuery, but any JavaScript implementation will do at this point.
tags2k's user avatar
  • 82.2k
4098 votes
42 answers

What is the !! (not not) operator in JavaScript?

I saw some code that seems to use an operator I don't recognize, in the form of two exclamation points, like so: !!. Can someone please tell me what this operator does? The context in which I saw ...
Hexagon Theory's user avatar
4072 votes
92 answers

How to round to at most 2 decimal places, if necessary

I'd like to round at most two decimal places, but only if necessary. Input: 10 1.7777777 9.1 Output: 10 1.78 9.1 How can I do this in JavaScript?
stinkycheeseman's user avatar
4060 votes
61 answers

Sort array of objects by string property value

I have an array of JavaScript objects: var objs = [ { first_nom: 'Laszlo', last_nom: 'Jamf' }, { first_nom: 'Pig', last_nom: 'Bodine' }, { first_nom: 'Pirate', last_nom: '...
Tyrone Slothrop's user avatar
3990 votes
33 answers

Checking if a key exists in a JavaScript object?

How do I check if a particular key exists in a JavaScript object or array? If a key doesn't exist, and I try to access it, will it return false? Or throw an error?
Adam Ernst's user avatar
  • 52.6k
3966 votes
46 answers

Loop through an array in JavaScript

In Java, you can use a for loop to traverse objects in an array as follows: String[] myStringArray = {"Hello", "World"}; for (String s : myStringArray) { // Do something } Can ...
Mark Szymanski's user avatar
3936 votes
54 answers

How do I check for an empty/undefined/null string in JavaScript?

Is there a string.Empty in JavaScript, or is it just a case of checking for ""?
casademora's user avatar
  • 67.8k
3893 votes
42 answers

How do I test for an empty JavaScript object?

After an AJAX request, sometimes my application may return an empty object, like: var a = {}; How can I check whether that's the case?
falmp's user avatar
  • 39.3k
3703 votes
81 answers

How do I correctly clone a JavaScript object?

I have an object x. I'd like to copy it as object y, such that changes to y do not modify x. I realized that copying objects derived from built-in JavaScript objects will result in extra, unwanted ...
soundly_typed's user avatar
3698 votes
26 answers

Get the current URL with JavaScript?

All I want is to get the website URL. Not the URL as taken from a link. On the page loading I need to be able to grab the full, current URL of the website and set it as a variable to do with as I ...
user avatar
3668 votes
92 answers

What is the JavaScript version of sleep()?

Is there a better way to engineer a sleep in JavaScript than the following pausecomp function (taken from here)? function pausecomp(millis) { var date = new Date(); var curDate = null; do ...
3556 votes
48 answers

How do I loop through or enumerate a JavaScript object?

I have a JavaScript object like the following: var p = { "p1": "value1", "p2": "value2", "p3": "value3" }; How do I loop ...
Tanmoy's user avatar
  • 44.5k
3464 votes
104 answers

How can I convert a string to boolean in JavaScript?

Can I convert a string representing a boolean value (e.g., 'true', 'false') into a intrinsic type in JavaScript? I have a hidden form in HTML that is updated based upon a user's selection within a ...
3460 votes
24 answers

What is the difference between call and apply?

What is the difference between using Function.prototype.apply() and to invoke a function? const func = function() { alert("Hello world!"); }; func.apply() vs. ...
John Duff's user avatar
  • 38.1k
3442 votes
69 answers

How do I format a date in JavaScript?

How do I format a Javascript Date object as a string? (Preferably in the format: 10-Aug-2010)
leora's user avatar
  • 189k
3403 votes
43 answers

Creating multiline strings in JavaScript

I have the following code in Ruby. I want to convert this code into JavaScript. What is the equivalent code in JS? text = <<"HERE" This Is A Multiline String HERE
Newy's user avatar
  • 39k
3380 votes
34 answers

How can I change an element's class with JavaScript?

How can I change the class of an HTML element in response to an onclick or any other events using JavaScript?
Nathan Smith's user avatar
  • 36.9k
3351 votes
32 answers

pretty-print JSON using JavaScript

How can I display JSON in an easy-to-read (for human readers) format? I'm looking primarily for indentation and whitespace, with perhaps even colors / font-styles / etc.
Mark's user avatar
  • 67.3k
3316 votes
51 answers

How can I check if an object is an array? [duplicate]

I'm trying to write a function that either accepts a list of strings, or a single string. If it's a string, then I want to convert it to an array with just the one item so I can loop over it without ...
mpen's user avatar
  • 273k
3265 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 ...
Mr Jedi's user avatar
  • 33.8k
3235 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 ...
3230 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. ...
RaYell's user avatar
  • 69.7k
3222 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); ...
nickf's user avatar
  • 537k
3202 votes
49 answers

Detecting an undefined object property

How do I check if an object property in JavaScript is undefined?
Matt Sheppard's user avatar

2 3 4 5