Download as pdf or txt
Download as pdf or txt
You are on page 1of 153

JAVASCRIPT

Source: https://www.w3schools.com
Introduction
JavaScript Can Change HTML Content

One of many JavaScript HTML methods is getElementById().

The example below "finds" an HTML element (with id="demo"), and changes the element content
(innerHTML) to "Hello JavaScript":
JS Can Change HTML Attribute

In this example JavaScript changes the value of the src (source) attribute of an <img> tag:
JS Can Change HTML Style (CSS)
Changing the style of an HTML element, is a variant of changing an HTML attribute:
JS Can Hide HTML Element
Hiding HTML elements can be done by changing the display style:
JS Can Show HTML Element

Showing hidden HTML elements can also be done by changing the display style:
JS Output

JavaScript Display Possibilities

JavaScript can "display" data in different ways:


• Writing into an HTML element, using innerHTML.
• Writing into the HTML output using document.write().
• Writing into an alert box, using window.alert().
• Writing into the browser console, using console.log().
Using InnerHTML

To access an HTML element, JavaScript can use the document.getElementById(id) method.

The id attribute defines the HTML element. The innerHTML property defines the HTML content:
Using document.write()
For testing purposes, it is convenient to use document.write():
Using window.alert()
You can use an alert box to display data:
Using window.alert()

You can skip the window keyword.


In JavaScript, the window object is the global scope object. This means that variables,
properties, and methods by default belong to the window object. This also means that
specifying the window keyword is optional:
JS Print

JavaScript does not have any print object or print methods.


You cannot access output devices from JavaScript.
The only exception is that you can call the window.print() method in the browser to print the
content of the current window.
JS Print

JavaScript does not have any print object or print methods.


You cannot access output devices from JavaScript.
The only exception is that you can call the window.print() method in the browser to print the
content of the current window.
JS Print
JS Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.

This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":
JS Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.

This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":
JS Semicolons;
Semicolons separate JavaScript statements.

Add a semicolon at the end of each executable statement:

When separated by semicolons, multiple statements on one line are allowed:


JS White Space

JavaScript ignores multiple spaces. You can add white space to your script to
make it more readable.

The following lines are equivalent:

let person = "Hege";


let person="Hege";

A good practice is to put spaces around operators ( = + - * / ):

let x = y + z;
JS Line Length and Line Breaks

For best readability, programmers often like to avoid code lines longer than 80 characters.

If a JavaScript statement does not fit on one line, the best place to break it is after an
operator:
JS CodeBlocks
JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.

The purpose of code blocks is to define statements to be executed together.

One place you will find statements grouped together in blocks, is in JavaScript functions:
JS Keywords

JavaScript statements often start with a keyword to identify the JavaScript action to be

performed.

Our Reserved Words Reference lists all JavaScript keywords.


JS Keywords
Here is a list of some of the keywords you will learn about in this tutorial:
Keyword Description

var Declares a variable

let Declares a block variable

const Declares a block constant

if Marks a block of statements to be executed


on a condition

switch Marks a block of statements to be executed


in different cases
for Marks a block of statements to be executed
in a loop

function Declares a function

return Exits a function

try Implements error handling to a block of


statements
JS Syntax

JavaScript syntax is the set of rules, how JavaScript programs are


constructed:

// How to create variables:


var x;
let y;

// How to use variables:


x = 5;
y = 6;
let z = x + y;
JS Values

The JavaScript syntax defines two types of values:


•Fixed values
•Variable values

Fixed values are called Literals.


Variable values are called Variables.
JS Literals

The two most important syntax rules for fixed values are:

1. Numbers are written with or without decimals:


JS Variables
In a programming language, variables are used to store data values.
JavaScript uses the keywords var, let and const to declare variables.
An equal sign is used to assign values to variables.
In this example, x is defined as a variable. Then, x is assigned (given) the value 6:
JS Operators
JavaScript uses arithmetic operators ( + - * / ) to compute values:
JS Expression
An expression is a combination of values, variables, and operators, which computes to a value.

The computation is called an evaluation.

For example, 5 * 10 evaluates to 50:


JS Expression
An expression is a combination of values, variables, and operators, which computes to a value.

The computation is called an evaluation.

For example, 5 * 10 evaluates to 50:


JS Expression

Expressions can also contain variable values:


JS Expression

The values can be of various types, such as numbers and strings.

For example, "John" + " " + "Doe", evaluates to "John Doe":


JS Keywords

JavaScript keywords are used to identify actions to be performed.


The let keyword tells the browser to create variables:
JS Keywords
JavaScript keywords are used to identify actions to be performed.
The let keyword tells the browser to create variables:
The var keyword also tells the browser to create variables
JS Comments
Not all JavaScript statements are "executed".
Code after double slashes // or between /* and */ is treated as a comment.
Comments are ignored, and will not be executed:
JS Identifiers / Names

Identifiers are JavaScript names.


Identifiers are used to name variables and keywords, and functions.
The rules for legal names are the same in most programming languages.

A JavaScript name must begin with:


•A letter (A-Z or a-z)
•A dollar sign ($)
•Or an underscore (_)

Subsequent characters may be letters, digits, underscores, or dollar signs.


JS Case Sensitive
All JavaScript identifiers are case sensitive.
The variables lastName and lastname, are two different variables:
JS and Camel Case
Historically, programmers have used different ways of joining multiple words into one
variable name:
Hyphens:
first-name, last-name, master-card, inter-city.

Underscore:

first_name, last_name, master_card, inter_city.

Upper Camel Case (Pascal Case):

FirstName, LastName, MasterCard, InterCity.

Lower Camel Case:

JavaScript programmers tend to use camel case that starts with a lowercase letter:

firstName, lastName, masterCard, interCity.


JS Single-Comments

JavaScript comments can be used to explain JavaScript code, and to make it more readable.

JavaScript comments can also be used to prevent execution, when testing alternative code.

Single Line Comments


Single line comments start with //.

Any text between // and the end of the line will be ignored by JavaScript (will not be executed).

This example uses a single-line comment before each code line:


JS Multi-Line Comments

Multi-line comments start with /* and end with */.


Any text between /* and */ will be ignored by JavaScript.
This example uses a multi-line comment (a comment block) to explain the code:
JS Variables
4 Ways to Declare a JavaScript Variable:
•Using var
•Using let
•Using const
•Using nothing

What are Variables?


Variables are containers for storing data (storing data values).
In this example, x, y, and z, are variables, declared with the var keyword:
JS Variables

When to Use JavaScript var?


Always declare JavaScript variables with var,let, orconst.

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

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

If you want your code to run in older browsers, you must use var.
JS 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.
JS Dollar Sign $

Since JavaScript treats a dollar sign as a letter, identifiers containing $


are valid variable names:
JS Dollar Sign $
Since JavaScript treats a dollar sign as a letter, identifiers containing $
are valid variable names:

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


JS Underscore ( _ )
Since JavaScript treats underscore as a letter, identifiers
containing _ are valid variable names:

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.
JS Let

The let keyword was introduced in ES6 (2015).


Variables defined with let cannot be Redeclared.
Variables defined with let must be Declared before use.
Variables defined with let have Block Scope.

Cannot be Redeclared

Variables defined with let cannot be redeclared.


You cannot accidentally redeclare a variable.
With let you can not do this:

let x = "John Doe";


let x = 0;
// SyntaxError: 'x' has already been
declared
Block Scope
Before ES6 (2015), JavaScript had only Global Scope and Function Scope.
ES6 introduced two important new JavaScript keywords: let and const.
These two keywords provide Block Scope in JavaScript.
Variables declared inside a { } block cannot be accessed from outside the block:

Example
{
let x = 2;
}
// x can NOT be used here

Variables declared with the var keyword can NOT have block scope.
Variables declared inside a { } block can be accessed from outside the block.

Example
{
var x = 2;
}
// x CAN be used here
Redeclaring Variables
Redeclaring a variable using the var keyword can impose problems.
Redeclaring a variable inside a block will also redeclare the variable outside the
block:
Example
var x = 10;
// Here x is 10
{
var x = 2;
// Here x is 2
}
// Here x is 2

Redeclaring a variable using the let keyword can solve this problem.
Redeclaring a variable inside a block will not redeclare the variable outside the block:
Example
let x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
Browser Support
The let keyword is not fully supported in Internet Explorer 11 or earlier.
The following table defines the first browser versions with full support for the let keyword:
Redeclaring
Redeclaring a JavaScript variable with var is allowed anywhere in a program:
var x = 2;
// Now x is 2
var x = 3;
// Now x is 3

With let, redeclaring a variable in the same block is NOT allowed:


Example
var x = 2; // Allowed
let x = 3; // Not allowed
{
let x = 2; // Allowed
let x = 3; // Not allowed
}
{
let x = 2; // Allowed
var x = 3; // Not allowed
}
Let Hoising

Variables defined with var are hoisted to the top and can be initialized at any time.

Meaning: You can use the variable before it is declared:


Data Types

JavaScript variables can hold different data types: numbers,


strings, objects and more:

let length = 16; // Number


let lastName = "Johnson"; // String
let x = {firstName:"John", lastName:"Doe"}; // Object
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";

JavaScript evaluates expressions from left to right. Different sequences can produce
different results:
JS Types is Dynamic
JavaScript has dynamic types. This means that the same variable can be used to hold different
data types:
JS String
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:

You can use quotes inside a


string, as long as they don't
match the quotes
surrounding the string:
JS Numbers
JavaScript has only one type of numbers.
Numbers can be written with, or without decimals:
JS Numbers

Extra large or extra small numbers can be written with scientific (exponential) notation:
JS Booleans
Booleans can only have two values: true or false.

Booleans are often used in conditional testing.


JS 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):
JS Objects
JavaScript objects are written with curly braces {}.
Object properties are written as name:value pairs, separated by commas.

The object (person) in the example above has 4 properties: firstName, lastName, age, and eyeColor.
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:
Undefined
In JavaScript, a variable without a value, has the value undefined. The type is
also undefined.
Undefined
In JavaScript, a variable without a value, has the value undefined. The type is
also undefined.

Any variable can be emptied, by setting


the value to undefined. The type will also
be undefined.
Empty Values
An empty value has nothing to do with undefined.
An empty string has both a legal value and a type.
JS Objects
Real Life Objects, Properties, and Methods
In real life, a car is an object.

A car has properties like weight and color, and methods like start and stop:

All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different
times.
JS Objects
You have already learned that JavaScript variables are containers for data values.

This code assigns a simple value (Fiat) to a variable named car:

Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:

const car = {type:"Fiat", model:"500", color:"white"};

The values are written as name:value pairs (name and value separated by a colon).
Object Definition
You define (and create) a JavaScript object with an object literal:

Spaces and line breaks are not important. An object definition can span multiple lines:
Object Properties
The name:values pairs in JavaScript objects are called properties:

Spaces and line breaks are not important. An object definition can span multiple lines:
Access Object Properties
You can access object properties in two ways:

objectName.propertyName

objectName["propertyName"]
Object Methods
Objects can also have methods.
Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.

Property Property Value

firstName John

lastName Doe

age 50

eyeColor blue

fullName function() {return this.firstName + " " + this.lastName;}


Object Methods
Example
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

In the example above, this refers to the person object.


I.E. this.firstName means the firstName property of this.
I.E. this.firstName means the firstName property of person.
JS Function

A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it).

function myFunction(p1, p2) {


return p1 * p2; // The function returns the product of p1 and p2
}
JS Function Syntax
A JavaScript function is defined with the function keyword, followed by a name, followed
by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}

function name(parameter1, parameter2, parameter3) {


// code to be executed
}

Function parameters are listed inside the parentheses () in the function definition.

Function arguments are the values received by the function when it is invoked.

Inside the function, the arguments (the parameters) behave as local variables.
Function Invocation

The code inside the function will execute when "something" invokes (calls)
the function :

• When an event occurs (when a user clicks a button)


• When it is invoked (called) from JavaScript code
• Automatically (self invoked)
Function Return
When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will "return" to execute the code
after the invoking statement.

Functions often compute a return value. The return value is "returned" back to the "caller":

Example
Calculate the product of two numbers, and return the result:
let x = myFunction(4, 3); // Function is called, return value will end up in x

function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}

The result in x will be:


12
Why Function?

You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce
different results.

Example
Convert Fahrenheit to Celsius:

function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius(77);
The ( ) Operator Invokes the Function
Using the example above, toCelsius refers to the function object, and toCelsius() refers to
the function result.
Accessing a function without () will return the function object instead of the function result.
Function used as Variables

Functions can be used the same way as you use variables, in all types of formulas,
assignments, and calculations.

Example
Instead of using a variable to store the return value of a function:

let x = toCelsius(77);
let text = "The temperature is " + x + " Celsius";

You can use the function directly, as a variable value:

let text = "The temperature is " + toCelsius(77) + " Celsius";


Function used as Variables

Functions can be used the same way as you use variables, in all types of formulas,
assignments, and calculations.

Example
Instead of using a variable to store the return value of a function:

let x = toCelsius(77);
let text = "The temperature is " + x + " Celsius";

You can use the function directly, as a variable value:

let text = "The temperature is " + toCelsius(77) + " Celsius";


JS Events

HTML events are "things" that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can "react" on


these events.
JS EVENTS

HTML Events

An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events:
• An HTML web page has finished loading
• An HTML input field was changed
• An HTML button was clicked
Often, when events happen, you may want to do something.
JavaScript lets you execute code when events are detected.
HTML allows event handler attributes, with JavaScript code, to be added to
HTML elements.
JS EVENTS
With single quotes:

<element event='some JavaScript'>

With double quotes:

<element event="some JavaScript“>

In the following example, an onclick attribute (with code), is added to a <button> element:
Common HTML Events

Event Description

onchange An HTML element has been changed

onclick The user clicks an HTML element

onmouseover The user moves the mouse over an HTML


element

onmouseout The user moves the mouse away from an HTML


element

onkeydown The user pushes a keyboard key

onload The browser has finished loading the page


JS Event Handlers
Event handlers can be used to handle and verify user input, user actions,
and browser actions:

•Things that should be done every time a page loads


•Things that should be done when the page is closed
•Action that should be performed when a user clicks a button
•Content that should be verified when a user inputs data
•And more ...

Many different methods can be used to let JavaScript work with events:

•HTML event attributes can execute JavaScript code directly


•HTML event attributes can call JavaScript functions
•You can assign your own event handler functions to HTML
elements
•You can prevent events from being sent or being handled
•And more ...
JS String

JavaScript strings are for storing and manipulating text.

A JavaScript string is zero or more characters written inside quotes.

You can use single or double quotes:

let carName1 = "Volvo XC60"; // Double quotes


let carName2 = 'Volvo XC60'; // Single quotes

You can use quotes inside a string, as long as they don't match the quotes surrounding
the string:

let answer1 = "It's alright";


let answer2 = "He is called 'Johnny'";
let answer3 = 'He is called "Johnny"';
JS String Length

To find the length of a string, use the built-in length property:


Escape Character
Because strings must be written within quotes, JavaScript will misunderstand this string:

let text = "We are the so-called "Vikings" from the north.";

The string will be chopped to "We are the so-called ".


The solution to avoid this problem, is to use the backslash escape character.
The backslash (\) escape character turns special characters into string characters:

Code Result Description

\' ' Single quote

\" " Double quote

\\ \ Backslash
Escape Character

The sequence \" inserts a double quote in a string:

let text = "We are the so-called \"Vikings\" from the north.";

The sequence \' inserts a single quote in a string:

let text= 'It\'s alright.';

The sequence \\ inserts a backslash in a string:

let text = "The character \\ is called backslash.";


Escape Character

Six other escape sequences are valid in JavaScript:

Code Result

\b Backspace

\f Form Feed

\n New Line

\r Carriage Return

\t Horizontal Tabulator

\v Vertical Tabulator
Breaking Long Code Lines
For best readability, programmers often like to avoid code lines longer than 80 characters.
If a JavaScript statement does not fit on one line, the best place to break it is after an
operator:

You can also break up a code line within a text string with a single backslash:

document.getElementById("demo").innerHTML = "Hello \
Dolly!";
JS String as Object
Normally, JavaScript strings are primitive values, created from literals:

let x = "John";

But strings can also be defined as objects with the keyword new:

let y = new String("John");


JS String as Object

When using the == operator, x and y are equal:

When using the === operator, x and y are not equal:


let x = "John";
let y = new String("John");
JS String Methods

String methods help you to work with strings.

String Methods and Properties

Primitive values, like "John Doe", cannot have properties or methods (because they are not
objects).

But with JavaScript, methods and properties are also available to primitive values, because
JavaScript treats primitive values as objects when executing methods and properties.
JS String Length

The length property returns the length of a string:


Extracting String Parts

There are 3 methods for extracting a part of a string:

• slice(start, end)

• substring(start, end)

• substr(start, length)
JS String slice()

slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the start position, and the end position (end not included).
JS String slice()

slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the start position, and the end position (end not included).
JS String slice()

If a parameter is negative, the position is counted from the end of the string.
This example slices out a portion of a string from position -12 to position -6:

Example
let str = "Apple, Banana, Kiwi";
let part = str.slice(-12, -6);
JS String substring()

substring() is similar to slice().


The difference is that start and end values less than 0 are treated as 0 in substring().

Example
let str = "Apple, Banana, Kiwi";
let part = str.substring(7, 13);

If you omit the second parameter, substring() will slice out the rest of the string.
JS String substr()
substr() is similar to slice().

The difference is that the second parameter specifies the length of the extracted part.

Example
let str = "Apple, Banana, Kiwi";
let part = str.substr(7, 6);

If you omit the second parameter, substr() will slice out the rest of the string.

Example
let str = "Apple, Banana, Kiwi";
let part = str.substr(7);
Replacing String Content
The replace() method replaces a specified value with another value in a string:

Example
let text = "Please visit Microsoft!";
let newText =
text.replace("Microsoft", "W3Schools");

Note
• The replace() method does not change the string it is called on.
• The replace() method returns a new string.
• The replace() method replaces only the first match
• If you want to replace all matches, use a regular expression with the /g flag set. See
examples below.

By default, the replace() method replaces only the first match:

By default, the replace() method is case sensitive. Writing MICROSOFT (with upper-case) will not work:
Replacing String Content

By default, the replace() method replaces only the first match:


By default, the replace() method is case sensitive. Writing MICROSOFT (with upper-case)
will not work:

To replace case insensitive, use a regular expression with an /i flag (insensitive):

Example
let text = "Please visit Microsoft!";
let newText =
text.replace(/MICROSOFT/i, "W3Schools");

Note: Regular expressions are written without quotes.

To replace all matches, use a regular expression with a /g flag (global match):

Example
let text = "Please visit Microsoft and
Microsoft!";
let newText =
text.replace(/Microsoft/g, "W3Schools");
JS String toUpperCase()
JS String toLowerCase()
JS String trim()

The trim() method removes whitespace from both sides of a string:


JS String trimStart()
ECMAScript 2019 added the String method trimStart() to JavaScript.
The trimStart() method works like trim(), but removes whitespace only from the start of a
string.
JS String trimStart()
ECMAScript 2019 added the String method trimStart() to JavaScript.
The trimStart() method works like trim(), but removes whitespace only from the start of a
string.
JS String trimEnd()
ECMAScript 2019 added the String method trimEnd() to JavaScript.
The trimEnd() method works like trim(), but removes whitespace only from the end of a
string.
Extracting String Characters

There are 3 methods for extracting string characters:

• charAt(position)

• charCodeAt(position)

• Property access [ ]
JS String charArt()

The charAt() method returns the character at a specified index (position) in a string:
JS String charCodeAt()

The charCodeAt() method returns the unicode of the character at a specified index in
a string:
The method returns a UTF-16 code (an integer between 0 and 65535).
Property Access

ECMAScript 5 (2009) allows property access [ ] on strings:


JS String split()

A string can be converted to an array with the split() method:


JS Arrays

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.

Spaces and line breaks are not important. A declaration can span multiple lines:
Using the JS keyword new

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

const cars = new Array("Saab", "Volvo", "BMW");


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

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


let car = cars[0];

Note: Array indexes start with 0.


[0] is the first element. [1] is the second element.
Changing an Array Elements

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

cars[0] = "Opel";
Access the Full Array

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

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


document.getElementById("demo").innerHTML =
cars;
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 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
The Length Property

The length property of an array returns the length of an array (the number of array elements).
Accessing the First Array
Accessing the Last Array
Looping Array Elements

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


Looping Array Elements

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


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

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

The easiest way to add a new element to an array is using the push() method:
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.
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.
JS 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];

The new keyword can produce some unexpected results:


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;
How To Recognize an Array

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

Solution 2:
The instanceof operator returns true if an object is created by a given
constructor:
JS Array Method
Converting Arrays to Strings

The JavaScript method toString() converts an array to a string of (comma separated)


array values.

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


document.getElementById("demo").innerHTML = fruits.toString();

Result:
Banana,Orange,Apple,Mango

The join() method also joins all array elements into a string.
It behaves just like toString(), but in addition you can specify the separator:

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


document.getElementById("demo").innerHTML = fruits.join(" * ");
Result:
Banana * Orange * Apple * Mango
JS Array Method
Converting Arrays to Strings

The JavaScript method toString() converts an array to a string of (comma separated)


array values.

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


document.getElementById("demo").innerHTML = fruits.toString();

Result:
Banana,Orange,Apple,Mango

The join() method also joins all array elements into a string.
It behaves just like toString(), but in addition you can specify the separator:

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


document.getElementById("demo").innerHTML = fruits.join(" * ");
Result:
Banana * Orange * Apple * Mango
JS Array pop()
The pop() method removes the last element from an array:
JS Array push()
The push() method adds a new element to an array (at the end):
JS Array shift()

The shift() method removes the first array element and "shifts" all
other elements to a lower index.
JS Array unshift()
The unshift() method adds a new element to an array (at the beginning), and
"unshifts" older elements:
JS Array length
The length property provides an easy way to append a new element to an array:
JS Array delete()
JS Array delete()
Merging ( Concatenating ) Arrays

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

The concat() method does


not change the existing
arrays. It always returns a
new array.
Merging ( Concatenating ) Arrays
The concat() method can take any number of array arguments:
JS Array splice()
The splice() method can be used to add new items to an array:

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:
Using splice() to Remove Elements
With clever parameter setting, you can use splice() to remove elements without leaving
"holes" in the array:

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
JS Array slice()
The slice() method slices out a piece of an array into a new array.

This example slices out a part of an array starting from array element 1 ("Orange"):
Automatic to String()
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:
Source:
https://www.w3schools.com/css/default.asp
Thank you!

You might also like