JavaScript Dialogue Boxes
JavaScript Dialogue Boxes
JAVASCRIPT
Java Script Objects, Methods, Events and Functions, Tags, Operators, Data Types, Literals
and Type Casting in JavaScript, Programming Construct, Array and Dialog Boxes, Relating
JavaScript to DHTML, Dynamically Changing Text, Style, Content
Dialogue boxes are a kind of popup notification, this kind of informative functionality is used
to show success, failure, or any particular/important notification to the user.
JavaScript uses 3 kinds of dialog boxes:
Alert
Prompt
Confirm
These dialog boxes can be of very much help in making our website look more attractive.
Alert Box: An alert box is used on the website to show a warning message to the user that
they have entered the wrong value other than what is required to fill in that position.
Nonetheless, an alert box can still be used for friendlier messages. The alert box gives only
one button “OK” to select and proceed.
Example:
JavaScript
function Warning() {
alert ("Warning danger you have not filled everything");
console.log ("Warning danger you have not filled everything");
Output:
Confirm box: A confirm box is often used if you want the user to verify or accept
something. When a confirm box pops up, the user will have to click either “OK” or “Cancel”
to proceed. If the user clicks on the OK button, the window method confirm() will return true.
If the user clicks on the Cancel button, then confirm() returns false and will show null.
Example:
JavaScript
function Confirmation() {
var Val = confirm("Do you want to continue ?");
if (Val == true) {
console.log(" CONTINUED!");
return true;
} else {
console.log("NOT CONTINUED!");
return false;
}
}
Output:
Prompt Box: A prompt box is often used if you want the user to input a value before
entering a page. When a prompt box pops up, the user will have to click either “OK” or
“Cancel” to proceed after entering an input value. If the user clicks the OK button, the
window method prompt() will return the entered value from the text box. If the user clicks the
Cancel button, the window method prompt() returns null.
Example:
JavaScript
function Value(){
var Val = prompt("Enter your name : ", "Please enter your name");
console.log("You entered : " + Val);
}
Output:
Line Breaker: If you want a break in your dialogue box message, you can put a line
breaker(“\n”) there.
Example:
JavaScript
Output:
---------------------------------------------------------------
String
Number
Bigint
Boolean
Undefined
Null
Symbol
Object
The object data type can contain both built-in objects, and user defined objects:
Examples
// Numbers:
let length = 16;
let weight = 7.5;
// Strings:
let color = "Yellow";
let lastName = "Johnson";
// Booleans
let x = true;
let y = false;
// Object:
const person = {firstName:"John", lastName:"Doe"};
// Array object:
const cars = ["Saab", "Volvo", "BMW"];
// Date object:
const date = new Date("2022-03-25");
Note
let x = 16 + "Volvo";
Does it make any sense to add "Volvo" to sixteen? Will it produce an error or will it produce
a result?
When adding a number and a string, JavaScript will treat the number as a string.
Example
let x = 16 + "Volvo";
Example
let x = "Volvo" + 16;
JavaScript evaluates expressions from left to right. Different sequences can produce different
results:
JavaScript:
let x = 16 + 4 + "Volvo";
Result:
20Volvo
JavaScript:
let x = "Volvo" + 16 + 4;
Result:
Volvo164
In the first example, JavaScript treats 16 and 4 as numbers, until it reaches "Volvo".
In the second example, since the first operand is a string, all operands are treated as strings.
JavaScript has dynamic types. This means that the same variable can be used to hold different
data types:
Example
let x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String
JavaScript Strings
Strings are written with quotes. You can use single or double quotes:
Example
// Using double quotes:
let carName1 = "Volvo XC60";
You can use quotes inside a string, as long as they don't match the quotes surrounding the
string:
Example
// Single quote inside double quotes:
let answer1 = "It's alright";
JavaScript Numbers
Example
// With decimals:
let x1 = 34.00;
// Without decimals:
let x2 = 34;
Exponential Notation
Extra large or extra small numbers can be written with scientific (exponential) notation:
Example
let y = 123e5; // 12300000
let z = 123e-5; // 0.00123
Note
JavaScript BigInt
JavaScript BigInt is a new datatype (ES2020) that can be used to store integer values that are
too big to be represented by a normal JavaScript Number.
Example
let x = BigInt("123456789012345678901234567890");
JavaScript Booleans
Example
let x = 5;
let y = 5;
let z = 6;
(x == y) // Returns true
(x == z) // Returns false
Booleans are often used in conditional testing.
JavaScript Arrays
The following code declares (creates) an array called cars, containing three items (car
names):
Example
const cars = ["Saab", "Volvo", "BMW"];
Array indexes are zero-based, which means the first item is [0], second is [1], and so on.
JavaScript Objects
Example
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
The object (person) in the example above has 4 properties: firstName, lastName, age, and
eyeColor.
You can use the JavaScript typeof operator to find the type of a JavaScript variable.
Example
typeof "" // Returns "string"
typeof "John" // Returns "string"
typeof "John Doe" // Returns "string"
Example
typeof 0 // Returns "number"
typeof 314 // Returns "number"
typeof 3.14 // Returns "number"
typeof (3) // Returns "number"
typeof (3 + 4) // Returns "number"
Undefined
In JavaScript, a variable without a value, has the value undefined. The type is also undefined.
Example
let car; // Value is undefined, type is undefined
Any variable can be emptied, by setting the value to undefined. The type will also
be undefined.
Example
car = undefined; // Value is undefined, type is undefined
Empty Values
Example
let car = ""; // The value is "", the typeof is "string"
-----------------
JAVASCRIPT VARIABLES
Variables are Containers for Storing Data
Automatically
Using var
Using let
Using const
Example
x = 5;
y = 6;
z = x + y;
Note
The var keyword was used in all JavaScript code from 1995 to 2015.
The var keyword should only be used in code written for older browsers.
The two variables price1 and price2 are declared with the const keyword.
3. Always use const if the type should not be changed (Arrays and Objects)
let x = 5;
let y = 6;
let z = x + y;
From the example above, you can guess that the total is calculated to be 11.
Note
ADVERTISEMENT
JavaScript Identifiers
Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
Note
In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator.
This is different from algebra. The following does not make sense in algebra:
x=x+5
(It calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5.)
Note
JavaScript variables can hold numbers like 100 and text values like "John Doe".
JavaScript can handle many types of data, but for now, just think of numbers and strings.
Strings are written inside double or single quotes. Numbers are written without quotes.
Example
const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';
You declare a JavaScript variable with the var or the let keyword:
var carName;
or:
let carName;
carName = "Volvo";
You can also assign a value to the variable when you declare it:
In the example below, we create a variable called carName and assign the value "Volvo" to it.
Example
<p id="demo"></p>
<script>
let carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
Note
It's a good programming practice to declare all variables at the beginning of a script.
Start the statement with let and separate the variables by comma:
Example
let person = "John Doe", carName = "Volvo", price = 200;
Example
let person = "John Doe",
carName = "Volvo",
price = 200;
Value = undefined
In computer programs, variables are often declared without a value. The value can be
something that has to be calculated, or something that will be provided later, like user input.
The variable carName will have the value undefined after the execution of this statement:
Example
let carName;
Re-Declaring JavaScript Variables
If you re-declare a JavaScript variable declared with var, it will not lose its value.
The variable carName will still have the value "Volvo" after the execution of these
statements:
Example
var carName = "Volvo";
var carName;
Note
JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using operators
like = and +:
Example
let x = 5 + 2 + 3;
Example
let x = "John" + " " + "Doe";
Example
let x = "5" + 2 + 3;
Note
If you put a number in quotes, the rest of the numbers will be treated as strings, and
concatenated.
Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid variable
names:
Example
let $ = "Hello World";
let $$$ = 2;
let $myMoney = 5;
Using the dollar sign is not very common in JavaScript, but professional programmers often
use it as an alias for the main function in a JavaScript library.
In the JavaScript library jQuery, for instance, the main function $ is used to select HTML
elements. In jQuery $("p"); means "select all p elements".
Since JavaScript treats underscore as a letter, identifiers containing _ are valid variable
names:
Example
let _lastName = "Johnson";
let _x = 2;
let _100 = 5;
Using the underscore is not very common in JavaScript, but a convention among professional
programmers is to use it as an alias for "private (hidden)" variables.
-------------------
// Accessing a Property
Object.getOwnPropertyDescriptor(object, property)
// Accessing Properties
Object.getOwnPropertyDescriptors(object)
JavaScript Object.defineProperty()
Syntax:
Example
// Create an Object:
const person = {
firstName: "John",
lastName : "Doe",
language : "EN"
};
// Add a Property
Object.defineProperty(person, "year", {value:"2008"});
Example
// Create an Object:
const person = {
firstName: "John",
lastName : "Doe",
language : "EN"
};
// Change a Property
Object.defineProperty(person, "language", {value : "NO"});
Property Attributes
These attributes define how the property can be accessed (is it readable?, is it writable?)
In JavaScript, all attributes can be read, but only the value attribute can be changed (and only
if the property is writable).
( ECMAScript 5 has methods for both getting and setting all property attributes)
// Defining a getter
get: function() { return language }
// Defining a setter
set: function(value) { language = value }
ADVERTISEMENT
JavaScript getOwnPropertyNames()
Syntax
Object.getOwnPropertyNames(object)
Example
// Create an Object
const person = {
firstName: "John",
lastName : "Doe",
language : "EN"
};
Example
// Create an Object
const person = {
firstName: "John",
lastName : "Doe",
language : "EN"
};
JavaScript Object.keys()
Syntax
Object.keys(object)
Example
// Create an Object
const person = {
firstName: "John",
lastName : "Doe",
language : "EN"
};
If you define object properties without enumerable:false, the two methods will return the
same.
The Object.defineProperty() method can also be used to add Getters and Setters:
Example
//Create an object
const person = {firstName:"John", lastName:"Doe"};
// Define a getter
Object.defineProperty(person, "fullName", {
get: function () {return this.firstName + " " + this.lastName;}
});
A Counter Example
Example
// Define object
const obj = {counter:0};
// Define setters
Object.defineProperty(obj, "reset", {
get : function () {this.counter = 0;}
});
Object.defineProperty(obj, "increment", {
get : function () {this.counter++;}
});
Object.defineProperty(obj, "decrement", {
get : function () {this.counter--;}
});
Object.defineProperty(obj, "add", {
set : function (value) {this.counter += value;}
});
Object.defineProperty(obj, "subtract", {
set : function (i) {this.counter -= i;}
});
Prototype Properties
The delete keyword does not delete inherited properties, but if you delete a prototype
property, it will affect all objects inherited from the prototype.
The reference contains descriptions and examples of all Object Properties and Method
JAVASCRIPT Operators
Javascript operators are used to perform different types of mathematical and logical
computations.
Examples:
Assignment Examples
let x = 10;
Try it Yourself »
// Assign the value 5 to x
let x = 5;
// Assign the value 2 to y
let y = 2;
// Assign the value x + y to z:
let z = x + y;
Try it Yourself »
JavaScript Addition
Adding
let x = 5;
let y = 2;
let z = x + y;
Try it Yourself »
JavaScript Multiplication
Multiplying
let x = 5;
let y = 2;
let z = x * y;
Try it Yourself »
Types of JavaScript Operators
Arithmetic Operators
Assignment Operators
Comparison Operators
String Operators
Logical Operators
Bitwise Operators
Ternary Operators
Type Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
Note
ADVERTISEMENT
Assignment
let x = 10;
x += 5;
Try it Yourself »
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y
Note
Operator Description
== equal to
!= not equal
? ternary operator
Note
Example
let text1 = "A";
let text2 = "B";
let result = text1 < text2;
Try it Yourself »
Example
let text1 = "20";
let text2 = "5";
let result = text1 < text2;
Try it Yourself »
JavaScript String Addition
Example
let text1 = "John";
let text2 = "Doe";
let text3 = text1 + " " + text2;
Try it Yourself »
Example
let text1 = "What a very ";
text1 += "nice day";
Adding two numbers, will return the sum, but adding a number and a string will return a
string:
Example
let x = 5 + 5;
let y = "5" + 5;
let z = "Hello" + 5;
10
55
Hello5
Try it Yourself »
Note
Operator Description
|| logical or
! logical not
Note
Operator Description
Note
Any numeric operand in the operation is converted into a 32 bit number. The result is
converted back to a JavaScript number.
~ NOT ~5 ~0101 10
The examples above uses 4 bits unsigned examples. But JavaScript uses 32-bit signed
numbers.
Because of this, in JavaScript, ~ 5 will not return 10. It will return -6.
~00000000000000000000000000000101 will return 11111111111111111111111111111010
JavaScript Arrays
❮ PreviousNext ❯
An array is a special variable, which can hold more than one value:
However, what if you want to loop through the cars and find a specific one?
And what if you had not 3 cars, but 300?
An array can hold many values under a single name, and you can access the
values by referring to an index number.
Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
const array_name = [item1, item2, ...];
Learn more about const with arrays in the chapter: JS Array Const.
Example
const cars = ["Saab", "Volvo", "BMW"];
Try it Yourself »
Spaces and line breaks are not important. A declaration can span multiple
lines:
Example
const cars = [
"Saab",
"Volvo",
"BMW"
];
Try it Yourself »
You can also create an array, and then provide the elements:
Example
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
Try it Yourself »
Example
const cars = new Array("Saab", "Volvo", "BMW");
Try it Yourself »
For simplicity, readability and execution speed, use the array literal method.
ADVERTISEMENT
Try it Yourself »
cars[0] = "Opel";
Example
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
Try it Yourself »
Converting an Array to a String
The JavaScript method toString() converts an array to a string of (comma
separated) array values.
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
Result:
Banana,Orange,Apple,Mango
Try it Yourself »
Example
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
Try it Yourself »
Array:
const person = ["John", "Doe", 46];
Try it Yourself »
Object:
const person = {firstName:"John", lastName:"Doe", age:46};
Try it Yourself »
Because of this, you can have variables of different types in the same Array.
You can have objects in an Array. You can have functions in an Array. You can
have arrays in an Array:
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
Try it Yourself »
The length property is always one more than the highest array index.
Try it Yourself »
Try it Yourself »
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fLen = fruits.length;
let text = "<ul>";
for (let i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
Try it Yourself »
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
function myFunction(value) {
text += "<li>" + value + "</li>";
}
Try it Yourself »
Example
const fruits = ["Banana", "Orange", "Apple"];
fruits.push("Lemon"); // Adds a new element (Lemon) to fruits
Try it Yourself »
New element can also be added to an array using the length property:
Example
const fruits = ["Banana", "Orange", "Apple"];
fruits[fruits.length] = "Lemon"; // Adds "Lemon" to fruits
Try it Yourself »
WARNING !
Adding elements with high indexes can create undefined "holes" in an array:
Example
const fruits = ["Banana", "Orange", "Apple"];
fruits[6] = "Lemon"; // Creates undefined "holes" in fruits
Try it Yourself »
Associative Arrays
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
Example
const person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
person.length; // Will return 3
person[0]; // Will return "John"
Try it Yourself »
WARNING !!
If you use named indexes, JavaScript will redefine the array to an object.
After that, some array methods and properties will produce incorrect
results.
Example:
const person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
person.length; // Will return 0
person[0]; // Will return undefined
Try it Yourself »
The Difference Between Arrays
and Objects
In JavaScript, arrays use numbered indexes.
These two different statements both create a new empty array named points:
Try it Yourself »
The new keyword can produce some unexpected results:
Try it Yourself »
// Create an array with two elements:
const points = new Array(40, 100);
Try it Yourself »
// Create an array with one element ???
const points = new Array(40);
Try it Yourself »
A Common Error
const points = [40];
Try it Yourself »
// Create an array with 40 undefined elements:
const points = new Array(40);
Try it Yourself »
Try it Yourself »
Array.isArray(fruits);
Try it Yourself »
Solution 2:
The instanceof operator returns true if an object is created by a given
constructor:
Try it Yourself »
Example
const myObj = {
name: "John",
age: 30,
cars: [
{name:"Ford", models:["Fiesta", "Focus", "Mustang"]},
{name:"BMW", models:["320", "X3", "X5"]},
{name:"Fiat", models:["500", "Panda"]}
]
}
To access arrays inside arrays, use a for-in loop for each array:
Example
for (let i in myObj.cars) {
x += "<h1>" + myObj.cars[i].name + "</h1>";
for (let j in myObj.cars[i].models) {
x += myObj.cars[i].models[j];
}
}
-------------------
Search field
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let size = fruits.length;
Try it Yourself »
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
Result:
Banana,Orange,Apple,Mango
Try it Yourself »
Examples
Get the third element of fruits using at():
Try it Yourself »
Try it Yourself »
The at() method is supported in all modern browsers since March 2022:
This is not possible in JavaScript, because [] is used for accessing both arrays
and objects. obj[-1] refers to the value of key -1, not to the last property of
the object.
It behaves just like toString(), but in addition you can specify the separator:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
Result:
Try it Yourself »
ADVERTISEMENT
JavaScript Array pop()
The pop() method removes the last element from an array:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();
Try it Yourself »
The pop() method returns the value that was "popped out":
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.pop();
Try it Yourself »
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
Try it Yourself »
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.push("Kiwi");
Try it Yourself »
Shifting Elements
Shifting is equivalent to popping, but working on the first element instead of
the last.
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();
Try it Yourself »
The shift() method returns the value that was "shifted out":
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.shift();
Try it Yourself »
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");
Try it Yourself »
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");
Try it Yourself »
Changing Elements
Array elements are accessed using their index number:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[0] = "Kiwi";
Try it Yourself »
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Kiwi";
Try it Yourself »
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0];
Try it Yourself »
Try it Yourself »
Note
The concat() method does not change the existing arrays. It always returns a
new array.
Try it Yourself »
Try it Yourself »
Array copyWithin()
The copyWithin() method copies array elements to another position in an
array:
Examples
Copy to index 2, all elements from index 0:
Try it Yourself »
Try it Yourself »
Note
The copyWithin() method overwrites the existing values.
The copyWithin() method does not change the length of the array.
Flattening an Array
Flattening an array is the process of reducing the dimensionality of an array.
Example
const myArr = [[1,2],[3,4],[5,6]];
const newArr = myArr.flat();
Try it Yourself »
Browser Support
JavaScript Array flat() is supported in all modern browsers since January
2020:
The flatMap() method first maps all elements of an array and then creates a
new array by flattening the array.
Example
const myArr = [1, 2, 3, 4, 5, 6];
const newArr = myArr.flatMap(x => [x, x * 10]);
Try it Yourself »
Browser Support
JavaScript Array flatMap() is supported in all modern browsers since January
2020:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
Try it Yourself »
The first parameter (2) defines the position where new elements should
be added (spliced in).
The second parameter (0) defines how many elements should be removed.
The rest of the parameters ("Lemon" , "Kiwi") define the new elements to
be added.
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 2, "Lemon", "Kiwi");
Try it Yourself »
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1);
Try it Yourself »
The first parameter (0) defines the position where new elements should
be added (spliced in).
The second parameter (1) defines how many elements should be removed.
The rest of the parameters are omitted. No new elements will be added.
Try it Yourself »
Example
Slice out a part of an array starting from array element 1 ("Orange"):
Try it Yourself »
Note
The slice() method creates a new array.
The slice() method does not remove any elements from the source array.
Example
Slice out a part of an array starting from array element 3 ("Apple"):
Try it Yourself »
The slice() method can take two arguments like slice(1, 3).
The method then selects elements from the start argument, and up to (but
not including) the end argument.
Example
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1, 3);
Try it Yourself »
If the end argument is omitted, like in the first examples, the slice() method
slices out the rest of the array.
Example
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(2);
Try it Yourself »
Automatic toString()
JavaScript automatically converts an array to a comma separated string when
a primitive value is expected.
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
Try it Yourself »
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
Try it Yourself »
Note
All JavaScript objects have a toString() method.
Searching Arrays
Searching arrays are covered in the next chapter of this tutorial.
Sorting Arrays
Sorting arrays covers the methods used to sort arraysg.
Iterating Arrays
Iterating arrays covers methods that operate on all array elements.