0% found this document useful (0 votes)
1 views55 pages

JavaScript Dialogue Boxes

This document provides an overview of JavaScript, covering key concepts such as objects, methods, events, data types, and variables. It explains the use of dialogue boxes, including alert, prompt, and confirm, as well as the various data types in JavaScript like strings, numbers, and booleans. Additionally, it discusses variable declaration methods and best practices for using JavaScript effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views55 pages

JavaScript Dialogue Boxes

This document provides an overview of JavaScript, covering key concepts such as objects, methods, events, data types, and variables. It explains the use of dialogue boxes, including alert, prompt, and confirm, as well as the various data types in JavaScript like strings, numbers, and booleans. Additionally, it discusses variable declaration methods and best practices for using JavaScript effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 55

UNIT 4

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

JavaScript Dialogue Boxes


 Last Updated : 07 Nov, 2022



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

<p>Line-Breaks in Dialogue box(Alert function)</p>


<button onclick="alert('Geeksfor\nGeeks')">
CLICK ME
</button>

Output:

---------------------------------------------------------------

JavaScript Data Types


JavaScript has 8 Datatypes

String
Number
Bigint
Boolean
Undefined
Null
Symbol
Object

The Object Datatype

The object data type can contain both built-in objects, and user defined objects:

Built-in object types can be:


objects, arrays, dates, maps, sets, intarrays, floatarrays, promises, and more.

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

A JavaScript variable can hold any type of data.

The Concept of Data Types

In programming, data types is an important concept.

To be able to operate on variables, it is important to know something about the type.

Without data types, a computer cannot safely solve this:

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?

JavaScript will treat the example above as:

let x = "16" + "Volvo";


Note

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 Types are Dynamic

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

A string (or a text string) is a series of characters like "John Doe".

Strings are written with quotes. You can use single or double quotes:

Example
// Using double quotes:
let carName1 = "Volvo XC60";

// Using single quotes:


let carName2 = '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";

// Single quotes inside double quotes:


let answer2 = "He is called 'Johnny'";

// Double quotes inside single quotes:


let answer3 = 'He is called "Johnny"';

You will learn more about strings later in this tutorial.

JavaScript Numbers

All JavaScript numbers are stored as decimal numbers (floating point).

Numbers can be written with, or without decimals:

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

Most programming languages have many number types:

Whole numbers (integers):


byte (8-bit), short (16-bit), int (32-bit), long (64-bit)

Real numbers (floating-point):


float (32-bit), double (64-bit).

Javascript numbers are always one type:


double (64-bit floating point).

You will learn more about numbers later in this tutorial.

JavaScript BigInt

All JavaScript numbers are stored in a 64-bit floating-point format.

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");

You will learn more about BigInt later in this tutorial.

JavaScript Booleans

Booleans can only have two values: true or false.

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.

You will learn more about booleans later in this tutorial.

JavaScript Arrays

JavaScript arrays are written with square brackets.

Array items are separated by commas.

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.

You will learn more about arrays later in this tutorial.

JavaScript Objects

JavaScript objects are written with curly braces {}.

Object properties are written as name:value pairs, separated by commas.

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 will learn more about objects later in this tutorial.


The typeof Operator

You can use the JavaScript typeof operator to find the type of a JavaScript variable.

The typeof operator returns the type of a variable or an expression:

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"

You will learn more about typeof later in this tutorial.

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

An empty value has nothing to do with undefined.

An empty string has both a legal value and a type.

Example
let car = ""; // The value is "", the typeof is "string"
-----------------
JAVASCRIPT VARIABLES
Variables are Containers for Storing Data

JavaScript Variables can be declared in 4 ways:

 Automatically
 Using var
 Using let
 Using const

In this first example, x, y, and z are undeclared variables.

They are automatically declared when first used:

Example
x = 5;
y = 6;
z = x + y;
Note

It is considered good programming practice to always declare variables before use.

From the examples you can guess:

 x stores the value 5


 y stores the value 6
 z stores the value 11

Example using var


var x = 5;
var y = 6;
var z = x + y;
Note

The var keyword was used in all JavaScript code from 1995 to 2015.

The let and const keywords were added to JavaScript in 2015.

The var keyword should only be used in code written for older browsers.

Example using let


let x = 5;
let y = 6;
let z = x + y;
Example using const
const x = 5;
const y = 6;
const z = x + y;
Mixed Example
const price1 = 5;
const price2 = 6;
let total = price1 + price2;

The two variables price1 and price2 are declared with the const keyword.

These are constant values and cannot be changed.

The variable total is declared with the let keyword.

The value total can be changed.

When to Use var, let, or const?

1. Always declare variables

2. Always use const if the value should not be changed

3. Always use const if the type should not be changed (Arrays and Objects)

4. Only use let if you can't use const

5. Only use var if you MUST support old browsers.

Just Like Algebra

Just like in algebra, variables hold values:

let x = 5;
let y = 6;

Just like in algebra, variables are used in expressions:

let z = x + y;

From the example above, you can guess that the total is calculated to be 11.
Note

Variables are containers for storing values.

ADVERTISEMENT

JavaScript Identifiers

All JavaScript variables must be identified with unique names.

These unique names are called 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:

 Names can contain letters, digits, underscores, and dollar signs.


 Names must begin with a letter.
 Names can also begin with $ and _ (but we will not use it in this tutorial).
 Names are case sensitive (y and Y are different variables).
 Reserved words (like JavaScript keywords) cannot be used as names.

Note

JavaScript identifiers are case-sensitive.

The Assignment Operator

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

In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to x.

(It calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5.)

Note

The "equal to" operator is written like == in JavaScript.


JavaScript Data Types

JavaScript variables can hold numbers like 100 and text values like "John Doe".

In programming, text values are called text strings.

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.

If you put a number in quotes, it will be treated as a text string.

Example
const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';

Declaring a JavaScript Variable

Creating a variable in JavaScript is called "declaring" a variable.

You declare a JavaScript variable with the var or the let keyword:

var carName;
or:
let carName;

After the declaration, the variable has no value (technically it is undefined).

To assign a value to the variable, use the equal sign:

carName = "Volvo";

You can also assign a value to the variable when you declare it:

let carName = "Volvo";

In the example below, we create a variable called carName and assign the value "Volvo" to it.

Then we "output" the value inside an HTML paragraph with id="demo":

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.

One Statement, Many Variables

You can declare many variables in one statement.

Start the statement with let and separate the variables by comma:

Example
let person = "John Doe", carName = "Volvo", price = 200;

A declaration can span multiple lines:

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.

A variable declared without a value will have the value undefined.

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

You cannot re-declare a variable declared with let or const.

This will not work:

let carName = "Volvo";


let carName;

JavaScript Arithmetic

As with algebra, you can do arithmetic with JavaScript variables, using operators
like = and +:

Example
let x = 5 + 2 + 3;

You can also add strings, but strings will be concatenated:

Example
let x = "John" + " " + "Doe";

Also try this:

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.

Now try this:


Example
let x = 2 + 3 + "5";
JavaScript Dollar Sign $

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".

JavaScript Underscore (_)

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.

-------------------

avaScript Object Properties

Property Management Methods


// Adding or changing an object property
Object.defineProperty(object, property, descriptor)
// Adding or changing object properties
Object.defineProperties(object, descriptors)

// Accessing a Property
Object.getOwnPropertyDescriptor(object, property)

// Accessing Properties
Object.getOwnPropertyDescriptors(object)

// Returns all properties as an array


Object.getOwnPropertyNames(object)

// Accessing the prototype


Object.getPrototypeOf(object)

JavaScript Object.defineProperty()

The Object.defineProperty() method can be used to:

 Adding a new property to an object


 Changing property values
 Changing property metadata
 Changing object getters and setters

Syntax:

Object.defineProperty(object, property, descriptor)

Adding a new Property

This example adds a new property to an object:

Example
// Create an Object:
const person = {
firstName: "John",
lastName : "Doe",
language : "EN"
};
// Add a Property
Object.defineProperty(person, "year", {value:"2008"});

Changing a Property Value

This example changes a property value:

Example
// Create an Object:
const person = {
firstName: "John",
lastName : "Doe",
language : "EN"
};

// Change a Property
Object.defineProperty(person, "language", {value : "NO"});

Property Attributes

All properties have a name. In addition they also have a value.

The value is one of the property's attributes.

Other attributes are: enumerable, configurable, and writable.

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)

Changing Meta Data

The following property meta data can be changed:

writable : true // Property value can be changed


enumerable : true // Property can be enumerated
configurable : true // Property can be reconfigured
writable : false // Property value can not be changed
enumerable : false // Property can be not enumerated
configurable : false // Property can be not reconfigured

Getters and setters can also be changed:

// Defining a getter
get: function() { return language }
// Defining a setter
set: function(value) { language = value }

This example makes language read-only:

Object.defineProperty(person, "language", {writable:false});

This example makes language not enumerable:

Object.defineProperty(person, "language", {enumerable:false});

ADVERTISEMENT

JavaScript getOwnPropertyNames()

The Object.getOwnPropertyNames() method can:

 List object properties

Syntax
Object.getOwnPropertyNames(object)

List all Object Properties

This example gets all properties of an object:

Example
// Create an Object
const person = {
firstName: "John",
lastName : "Doe",
language : "EN"
};

// Get all Properties


Object.getOwnPropertyNames(person);

Object.getOwnPropertyNames() will also list properties that is not enumerable:

Example
// Create an Object
const person = {
firstName: "John",
lastName : "Doe",
language : "EN"
};

// Set the language Property not enumerable


Object.defineProperty(person, "language", {enumerable:false});

// Get all Properties


Object.getOwnPropertyNames(person);

JavaScript Object.keys()

The Object.keys() method can:

 List enumerable object properties

Syntax
Object.keys(object)

List Enumerable Object Properties

This example uses Object.keys() insted of Object.getOwnPropertyNames():

Example
// Create an Object
const person = {
firstName: "John",
lastName : "Doe",
language : "EN"
};

// Change the "language" Property


Object.defineProperty(person, "language", {enumerable:false});

// Get all Enumerable Properties


Object.keys(person);
Note

The getOwnPropertyNames() method returns all properties.

The Object.keys() method returns all enumerable properties.

If you define object properties without enumerable:false, the two methods will return the
same.

Adding Getters and Setters

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;}
});

// Play with the counter:


obj.reset;
obj.add = 5;
obj.subtract = 1;
obj.increment;
obj.decrement;

Prototype Properties

JavaScript objects inherit the properties of their prototype.

The delete keyword does not delete inherited properties, but if you delete a prototype
property, it will affect all objects inherited from the prototype.

Complete Object Reference

For a complete reference, go to our:

Complete JavaScript Object Reference.

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:

The Assignment Operator = assigns values

The Addition Operator + adds values

The Multiplication Operator * multiplies values

The Comparison Operator > compares values


JavaScript Assignment

The Assignment Operator (=) assigns a value to a variable:

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

The Addition Operator (+) adds numbers:

Adding
let x = 5;
let y = 2;
let z = x + y;
Try it Yourself »
JavaScript Multiplication

The Multiplication Operator (*) multiplies numbers:

Multiplying
let x = 5;
let y = 2;
let z = x * y;
Try it Yourself »
Types of JavaScript Operators

There are different types of JavaScript operators:

 Arithmetic Operators
 Assignment Operators
 Comparison Operators
 String Operators
 Logical Operators
 Bitwise Operators
 Ternary Operators
 Type Operators

JavaScript Arithmetic Operators

Arithmetic Operators are used to perform arithmetic on numbers:

Arithmetic Operators Example


let a = 3;
let x = (100 + 50) * a;
Try it Yourself »

Operator Description

+ Addition

- Subtraction

* Multiplication

** Exponentiation (ES2016)

/ Division
% Modulus (Division Remainder)

++ Increment

-- Decrement

Note

Arithmetic operators are fully described in the JS Arithmetic chapter.

ADVERTISEMENT

JavaScript Assignment Operators

Assignment operators assign values to JavaScript variables.

The Addition Assignment Operator (+=) adds a value to a variable.

Assignment
let x = 10;
x += 5;
Try it Yourself »

Operator Example Same As

= 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

Assignment operators are fully described in the JS Assignment chapter.

JavaScript Comparison Operators

Operator Description

== equal to

=== equal value and equal type

!= not equal

!== not equal value or not equal type


> greater than

< less than

>= greater than or equal to

<= less than or equal to

? ternary operator

Note

Comparison operators are fully described in the JS Comparisons chapter.

JavaScript String Comparison

All the comparison operators above can also be used on strings:

Example
let text1 = "A";
let text2 = "B";
let result = text1 < text2;
Try it Yourself »

Note that strings are compared alphabetically:

Example
let text1 = "20";
let text2 = "5";
let result = text1 < text2;
Try it Yourself »
JavaScript String Addition

The + can also be used to add (concatenate) strings:

Example
let text1 = "John";
let text2 = "Doe";
let text3 = text1 + " " + text2;
Try it Yourself »

The += assignment operator can also be used to add (concatenate) strings:

Example
let text1 = "What a very ";
text1 += "nice day";

The result of text1 will be:

What a very nice day


Try it Yourself »
Note

When used on strings, the + operator is called the concatenation operator.

Adding Strings and Numbers

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;

The result of x, y, and z will be:

10
55
Hello5
Try it Yourself »
Note

If you add a number and a string, the result will be a string!

JavaScript Logical Operators

Operator Description

&& logical and

|| logical or

! logical not

Note

Logical operators are fully described in the JS Comparisons chapter.

JavaScript Type Operators

Operator Description

typeof Returns the type of a variable

instanceof Returns true if an object is an instance of an object type

Note

Type operators are fully described in the JS Type Conversion chapter.


JavaScript Bitwise Operators

Bit operators work on 32 bits numbers.

Any numeric operand in the operation is converted into a 32 bit number. The result is
converted back to a JavaScript number.

Operator Description Example Same as Re

& AND 5&1 0101 & 0001 00

| OR 5|1 0101 | 0001 01

~ NOT ~5 ~0101 10

^ XOR 5^1 0101 ^ 0001 01

<< left shift 5 << 1 0101 << 1 10

>> right shift 5 >> 1 0101 >> 1 00

>>> unsigned right shift 5 >>> 1 0101 >>> 1 00

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

Bitwise operators are fully described in the JS Bitwise chapter


-------------------------

JavaScript Arrays

❮ PreviousNext ❯

An array is a special variable, which can hold more than one value:

const cars = ["Saab", "Volvo", "BMW"];


Try it Yourself »

Why Use Arrays?


If you have a list of items (a list of car names, for example), storing the cars
in single variables could look like this:

let car1 = "Saab";


let car2 = "Volvo";
let car3 = "BMW";

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?

The solution is an array!

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, ...];

It is a common practice to declare arrays with the const keyword.

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 »

Using the JavaScript Keyword


new
The following example also creates an Array, and assigns values to it:

Example
const cars = new Array("Saab", "Volvo", "BMW");
Try it Yourself »

The two examples above do exactly the same.

There is no need to use new Array().

For simplicity, readability and execution speed, use the array literal method.

ADVERTISEMENT

Accessing Array Elements


You access an array element by referring to the index number:

const cars = ["Saab", "Volvo", "BMW"];


let car = cars[0];

Try it Yourself »

Note: Array indexes start with 0.

[0] is the first element. [1] is the second element.

Changing an Array Element


This statement changes the value of the first element in cars:

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 »

Access the Full Array


With JavaScript, the full array can be accessed by referring to the array
name:

Example
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;

Try it Yourself »

Arrays are Objects


Arrays are a special type of objects. The typeof operator in JavaScript returns
"object" for arrays.

But, JavaScript arrays are best described as arrays.

Arrays use numbers to access its "elements". In this


example, person[0] returns John:

Array:
const person = ["John", "Doe", 46];
Try it Yourself »

Objects use names to access its "members". In this


example, person.firstName returns John:

Object:
const person = {firstName:"John", lastName:"Doe", age:46};

Try it Yourself »

Array Elements Can Be Objects


JavaScript variables can be objects. Arrays are special kinds of objects.

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;

Array Properties and Methods


The real strength of JavaScript arrays are the built-in array properties and
methods:

cars.length // Returns the number of elements


cars.sort() // Sorts the array

Array methods are covered in the next chapters.

The length Property


The length property of an array returns the length of an array (the number of
array elements).
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.length;

Try it Yourself »

The length property is always one more than the highest array index.

Accessing the First Array


Element
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[0];

Try it Yourself »

Accessing the Last Array


Element
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[fruits.length - 1];

Try it Yourself »

Looping Array Elements


One way to loop through an array, is using a for loop:

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 »

You can also use the Array.forEach() function:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];

let text = "<ul>";


fruits.forEach(myFunction);
text += "</ul>";

function myFunction(value) {
text += "<li>" + value + "</li>";
}

Try it Yourself »

Adding Array Elements


The easiest way to add a new element to an array is using
the push() method:

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).

JavaScript does not support arrays with named indexes.

In JavaScript, arrays always use numbered indexes.

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.

In JavaScript, objects use named indexes.

Arrays are a special kind of objects, with numbered indexes.

When to Use Arrays. When to


use Objects.
 JavaScript does not support associative arrays.
 You should use objects when you want the element names to
be strings (text).
 You should use arrays when you want the element names to
be numbers.

JavaScript new Array()


JavaScript has a built-in array constructor new Array().

But you can safely use [] instead.

These two different statements both create a new empty array named points:

const points = new Array();


const points = [];

These two different statements both create a new array containing 6


numbers:

const points = new Array(40, 100, 1, 5, 25, 10);


const points = [40, 100, 1, 5, 25, 10];

Try it Yourself »
The new keyword can produce some unexpected results:

// Create an array with three elements:


const points = new Array(40, 100, 1);

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];

is not the same as:

const points = new Array(40);


// Create an array with one element:
const points = [40];

Try it Yourself »
// Create an array with 40 undefined elements:
const points = new Array(40);

Try it Yourself »

How to Recognize an Array


A common question is: How do I know if a variable is an array?

The problem is that the JavaScript operator typeof returns "object":

const fruits = ["Banana", "Orange", "Apple"];


let type = typeof fruits;

Try it Yourself »

The typeof operator returns object because a JavaScript array is an object.


Solution 1:
To solve this problem ECMAScript 5 (JavaScript 2009) defined a new
method Array.isArray():

Array.isArray(fruits);

Try it Yourself »

Solution 2:
The instanceof operator returns true if an object is created by a given
constructor:

const fruits = ["Banana", "Orange", "Apple"];

(fruits instanceof Array);

Try it Yourself »

Nested Arrays and Objects


Values in objects can be arrays, and values in arrays can be objects:

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

 JavaScript Array Methods


Basic Array Methods
Array length Array shift()
Array toString() Array unshift()
Array at() Array delete()
Array join() Array concat()
Array pop() Array copyWithin()
Array push() Array flat()
Array splice()
Array toSpliced()
Array slice()

JavaScript Array length


The length property returns the length (size) of an array:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let size = fruits.length;

Try it Yourself »

JavaScript Array toString()


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 »

JavaScript Array at()


ES2022 intoduced the array method at():

Examples
Get the third element of fruits using at():

const fruits = ["Banana", "Orange", "Apple", "Mango"];


let fruit = fruits.at(2);

Try it Yourself »

Get the third element of fruits using []:

const fruits = ["Banana", "Orange", "Apple", "Mango"];


let fruit = fruits[2];

Try it Yourself »

The at() method returns an indexed element from an array.

The at() method returns the same as [].

The at() method is supported in all modern browsers since March 2022:

Chrome 92 Edge 92 Firefox 90 Safari 15.4

Apr 2021 Jul 2021 Jul 2021 Mar 2022


Note
Many languages allow negative bracket indexing like [-1] to access elements
from the end of an object / array / string.

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.

The at() method was introduced in ES2022 to solve this problem.

JavaScript Array join()


The join() method also joins all array elements into a string.

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:

Banana * Orange * Apple * Mango

Try it Yourself »

Popping and Pushing


When you work with arrays, it is easy to remove elements and add new
elements.

This is what popping and pushing is:

Popping items out of an array, or pushing items into an array.

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 »

JavaScript Array push()


The push() method adds a new element to an array (at the end):

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");

Try it Yourself »

The push() method returns the new array length:

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.

JavaScript Array shift()


The shift() method removes the first array element and "shifts" all other
elements to a lower index.

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 »

JavaScript Array unshift()


The unshift() method adds a new element to an array (at the beginning),
and "unshifts" older elements:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");

Try it Yourself »

The unshift() method returns the new array length:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");

Try it Yourself »

Changing Elements
Array elements are accessed using their index number:

Array indexes start with 0:

[0] is the first array element


[1] is the second
[2] is the third ...

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[0] = "Kiwi";

Try it Yourself »

JavaScript Array length


The length property provides an easy way to append a new element to an
array:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Kiwi";

Try it Yourself »

JavaScript Array delete()


Warning !
Using delete() leaves undefined holes in the array.
Use pop() or shift() instead.

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0];

Try it Yourself »

Merging Arrays (Concatenating)


In programming languages, concatenation means joining strings end-to-end.

Concatenation "snow" and "ball" gives "snowball".

Concatenating arrays means joining arrays end-to-end.

JavaScript Array concat()


The concat() method creates a new array by merging (concatenating)
existing arrays:

Example (Merging Two Arrays)


const myGirls = ["Cecilie", "Lone"];
const myBoys = ["Emil", "Tobias", "Linus"];

const myChildren = myGirls.concat(myBoys);

Try it Yourself »

Note
The concat() method does not change the existing arrays. It always returns a
new array.

The concat() method can take any number of array arguments.

Example (Merging Three Arrays)


const arr1 = ["Cecilie", "Lone"];
const arr2 = ["Emil", "Tobias", "Linus"];
const arr3 = ["Robin", "Morgan"];
const myChildren = arr1.concat(arr2, arr3);

Try it Yourself »

The concat() method can also take strings as arguments:

Example (Merging an Array with Values)


const arr1 = ["Emil", "Tobias", "Linus"];
const myChildren = arr1.concat("Peter");

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:

const fruits = ["Banana", "Orange", "Apple", "Mango"];


fruits.copyWithin(2, 0);

Try it Yourself »

Copy to index 2, the elements from index 0 to 2:

const fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];


fruits.copyWithin(2, 0, 2);

Try it Yourself »

Note
The copyWithin() method overwrites the existing values.

The copyWithin() method does not add items to the array.

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.

Flattening is useful when you want to convert a multi-dimensional array into


a one-dimensional array.

JavaScript Array flat()


ES2019 Introduced the Array flat() method.

The flat() method creates a new array with sub-array elements


concatenated to a specified depth.

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:

Chrome 69 Edge 79 Firefox 62 Safari 12

Sep 2018 Jan 2020 Sep 2018 Sep 2018

JavaScript Array flatMap()


ES2019 added the Array flatMap() method to JavaScript.

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:

Chrome 69 Edge 79 Firefox 62 Safari 12

Sep 2018 Jan 2020 Sep 2018 Sep 2018

Splicing and Slicing Arrays


The splice() method adds new items to an array.

The slice() method slices out a piece of an array.

JavaScript Array splice()


The splice() method can be used to add new items to an array:

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.

The splice() method returns an array with the deleted items:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 2, "Lemon", "Kiwi");

Try it Yourself »

Using splice() to Remove


Elements
With clever parameter setting, you can use splice() to remove elements
without leaving "holes" in the array:

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.

JavaScript Array toSpliced()


ES2023 added the Array toSpliced() method as a safe way to splice an array
without altering the original array.

The difference between the new toSpliced() method and the


old splice() method is that the new method creates a new array, keeping the
original array unchanged, while the old method altered the original array.
Example
const months = ["Jan", "Feb", "Mar", "Apr"];
const spliced = months.toSpliced(0, 1);

Try it Yourself »

JavaScript Array slice()


The slice() method slices out a piece of an array into a new array:

Example
Slice out a part of an array starting from array element 1 ("Orange"):

const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];


const citrus = fruits.slice(1);

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"):

const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];


const citrus = fruits.slice(3);

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.

This is always the case when you try to output an array.

These two examples will produce the same result:

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.

You might also like