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.
2,530,383
questions
11905
votes
154
answers
12.6m
views
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.
8679
votes
66
answers
3.2m
views
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?
8483
votes
32
answers
1.2m
views
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, ...
7701
votes
58
answers
7.9m
views
How do I redirect to another webpage?
How can I redirect the user from one page to another using jQuery or pure JavaScript?
7636
votes
42
answers
1.2m
views
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 ...
7619
votes
86
answers
1.6m
views
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 ...
7489
votes
39
answers
3.2m
views
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 ...
7406
votes
3
answers
8.0m
views
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?
6695
votes
42
answers
2.1m
views
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 ...
6318
votes
72
answers
4.4m
views
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?
6270
votes
38
answers
2.3m
views
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? ...
5695
votes
41
answers
5.3m
views
Loop (for each) over an array in JavaScript
How can I loop through all the entries in an array using JavaScript?
5647
votes
48
answers
2.1m
views
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....
5474
votes
79
answers
4.7m
views
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?...
5465
votes
50
answers
4.5m
views
How do I replace all occurrences of a string in JavaScript?
Given a string:
string = "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:
string = string.replace('abc', ...
5381
votes
75
answers
3.1m
views
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 ...
5225
votes
106
answers
4.1m
views
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"
&...
5188
votes
68
answers
4.9m
views
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 ...
5165
votes
67
answers
2.9m
views
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(...
4934
votes
62
answers
3.6m
views
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++...
4840
votes
44
answers
4.3m
views
How do I get a timestamp in JavaScript?
I want a single number that represents the current date and time, like a Unix timestamp.
4587
votes
44
answers
3.8m
views
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?
4506
votes
15
answers
854k
views
"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 ...
4488
votes
8
answers
601k
views
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', ...
4435
votes
57
answers
2.5m
views
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
3.0m
views
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?
4256
votes
34
answers
3.5m
views
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.
4185
votes
93
answers
4.5m
views
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?
4159
votes
36
answers
935k
views
What is the !! (not not) operator in JavaScript?
I saw this code:
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
It seems to be using !! as an operator, which I don't recognize. What does it do?
4138
votes
61
answers
3.3m
views
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: '...
4061
votes
33
answers
3.6m
views
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?
4022
votes
55
answers
5.5m
views
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 ""?
4019
votes
46
answers
5.4m
views
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 ...
3892
votes
41
answers
4.2m
views
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?
3782
votes
95
answers
4.9m
views
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 ...
3760
votes
26
answers
3.8m
views
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 ...
3748
votes
82
answers
2.4m
views
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 ...
3584
votes
48
answers
2.8m
views
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 ...
3523
votes
107
answers
3.4m
views
How can I convert a string to boolean in JavaScript?
Can I convert a string representing a boolean value (e.g., 'true', 'false') into an intrinsic type in JavaScript?
I have a hidden form in HTML that is updated based on a user's selection within a list....
3509
votes
71
answers
6.7m
views
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)
3478
votes
24
answers
820k
views
What is the difference between call and apply?
What is the difference between using Function.prototype.apply() and Function.prototype.call() to invoke a function?
const func = function() {
alert("Hello world!");
};
func.apply() vs. ...
3459
votes
43
answers
2.3m
views
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
3438
votes
32
answers
1.8m
views
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.
3421
votes
34
answers
3.5m
views
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?
3329
votes
51
answers
2.1m
views
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 ...
3311
votes
15
answers
6.3m
views
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 ...
3296
votes
69
answers
2.0m
views
How can I merge properties of two JavaScript objects?
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 ...
3249
votes
14
answers
938k
views
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. ...
3243
votes
45
answers
482k
views
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);
...
3219
votes
49
answers
1.5m
views
Detecting an undefined object property
How do I check if an object property in JavaScript is undefined?