[Go to site: main page, start]

0% found this document useful (0 votes)
10 views87 pages

JavaScript Data Types and Syntax Guide

Uploaded by

subbavedika604
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views87 pages

JavaScript Data Types and Syntax Guide

Uploaded by

subbavedika604
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

JavaScript Data-types

variable, operators,
loops and arrays
Datatype
• JavaScript data types determine the nature of data stored in variables,
affecting how values are processed and interacted with in the code. Each
data type has specific properties and behavior that impact how data is
stored, accessed, and manipulated.
• JavaScript data types are categorized into Primitive and Non-Primitive
types
Primitive Data Type

Primitive Data Type


Primitive data types in JavaScript represent simple, immutable values stored
directly in memory, ensuring efficiency in both memory usage and
performance.
1. Number
The Number data type in JavaScript includes both integers and floating-point
numbers. 2. String
A String in JavaScript is a series of characters that are surrounded by quotes.
There are three types of quotes in JavaScript, which are.
let s1 = "Hello There";
[Link](s1);
let s2 = 'Single quotes work fine';
[Link](s2);
let s3 = `can embed ${s1}`;
[Link](s3);
Note: There's no difference between 'single' and "double" quotes in
JavaScript
3. Boolean
The boolean type has only two values i.e. true and false.
4. Null
The special null value does not belong to any of the default data
types. It forms a separate type of its own which contains only the
null value.
5. Undefined
A variable that has been declared but not initialized with a value is
automatically assigned the undefined value. It means the variable
exists, but it has no value assigned to it.
6. Symbol
•Symbol is a primitive data type.
•It represents a unique and immutable value.
•Mainly used as object keys (to avoid conflicts).

7. BigInt
•BigInt is a primitive data type that can represent very large integers.
•Normal Number in JavaScript is safe only up to 2^53 - 1
(9007199254740991).
•BigInt can go beyond that limit.
Non-Primitive Data Types
The data types that are derived from primitive data types
are known as non-primitive data types. It is also known as
derived data types or reference data types.
1. Object
JavaScript objects are key-value pairs used to store data,
created with {} or the new keyword. They are fundamental
as nearly everything in JavaScript is an object. Collection of
key value pair
2. Arrays
An Array is a special kind of object used to store an
ordered collection of values, which can be of any data
type.
3. Function
A function in JavaScript is a block of reusable code
designed to perform a specific task when called.
4. Date Object
The Date object in JavaScript is used to work with dates
and times, allowing for date creation, manipulation, and
formatting.
5. Regular Expression
A RegExp (Regular Expression) in JavaScript is an object
used to define search patterns for matching text in strings.
JavaScript Statements

• statement is an instruction that the browser


can execute.
• Every statement usually ends with a semicolon (;)
•JavaScript statements are composed of:
• Values, Operators, Expressions, Keywords, and Comments.
• This statement tells the browser to write "Hello World!"
inside an HTML element with id="demo":

[Link]("demo").innerHTML =
"Hello World!";
Semicolons;
In JavaScript, a semicolon ( ; ) is used to end a statement.
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>JavaScript statements are separated by semicolons.</p>

<p id="demo1"></p>

<script>
var a, b, c;
a = 5;
b = 6;
c = a + b;
[Link]("demo1").innerHTML = c;
</script>

</body>
</html>
• When separated by semicolons, multiple statements on one line are allowed:
• a = 5; b = 6; c = a + b;
JavaScript Keywords

Keyword Description
JavaScript keywords break Terminates a switch or a loop
are reserved words. continue Jumps out of a loop and starts at the top
Reserved words
cannot be used as debugger Stops the execution of JavaScript, and calls (if available) the debugging
function
names for variables.
do ... while Executes a block of statements, and repeats the block, while a condition is true

for Marks a block of statements to be executed, as long as a condition is true

function Declares a function


if ... else Marks a block of statements to be executed, depending on a condition

return Exits a function


switch Marks a block of statements to be executed, depending on different cases

try ... catch Implements error handling to a block of statements

var Declares a variable


JavaScript Syntax

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


constructed:
Literals.: Numbers are
var x, y, z; // Declare Variables written with or without
decimals:
x = 5; y = 6; // Assign Values <p id="demo"></p>
z = x + y; // Compute Values <script>
[Link]
JavaScript Values Id("demo").innerHTML =
The JavaScript syntax defines two types of10.50;
values:
• Fixed values </script>

• Variable values Strings are text, written


within double or single quotes:
Fixed values are called Literals.:
Variable values are called Variables.
JavaScript Variables
• A variable is a named container that stores data.
You declare variables using var, let, or const.
• JavaScript uses the var keyword to declare variables.
The values can be of various types,
<p id="demo"></p>
such as numbers and strings.
<script> For example, “hello" + " " + “world",
evaluates to “hello world"
var x;
x = 6;
[Link]("demo").innerHTML = x;
</script>
JavaScript Operators
JavaScript uses arithmetic operators ( + - * / ) to compute values:3
+61 -40
JavaScript Comments

• Not all JavaScript statements are "executed".


• Single –line : // This is a comment
Double line:/* This is a multi-line comment */
Comments are ignored, and will not be executed:
var x = 5; // I will be executed
// var x = 6; It will NOT be executed
JavaScript is Case Sensitive:
var lastname, lastName;
lastName = »ABC";
lastname = «XYZ";
JavaScript 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.
Note: Hyphens are not allowed in JavaScript. They are reserved for
subtractions.
• Underscore:
first_name, last_name, master_card, inter_city.
•Upper Camel Case (Pascal Case):
•Each word starts with a capital letter.
•No spaces or underscores are used.
•The first word also starts with a capital letter.
FirstName, LastName, MasterCard, InterCity.
• Lower Camel Case:
JavaScript programmers tend to use camel case that starts with a lowercase
letter:
firstName, lastName, masterCard, interCity.
JavaScript Identifiers

• An identifier is the name you give to a variable, function, class, or object.


It’s basically the label used to identify values.
• 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 _
• Names are case sensitive (y and Y are different variables)
• Reserved words (like JavaScript keywords) cannot be used as names
Re-Declaring JavaScript Variables

• If you re-declare a JavaScript variable, 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; //re-declaration
JavaScript Dollar Sign $
• Remember that JavaScript identifiers (names) must begin with:
• A letter (A-Z or a-z)
• A dollar sign ($)
• Or an underscore (_)


After the first character, identifiers can contain letters, digits ,$ , or _.

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


are valid variable names:
<p id="demo"></p>
<script>
var $ = 2;
var $myMoney = 5;
[Link]("demo").innerHTML = $ + $myMoney;
</script>
JavaScript Operators
Operat Description
or
var x = 5;
+ Addition var z = x ** 2; // 25
- Subtraction
* Multiplication x ** y produces the
same result as
** Exponentiation [Link](x,y):
/ Division
Operator Precedence
% Modulus (Division Operator precedence describes the
Remainder) order in which operations are
++ Increment performed in an arithmetic
-- Decrement expression.
Example
var x = 100 + 50 * 3;
JavaScript Arithmetic

• JavaScript provides arithmetic operators to perform


mathematical calculations.
• Example var x = "5" + 2 + 3;
<p id="demo"></p> OUTPUT? 523

<script> var x = 2 + 3 + "5";


OUTPUT? 55
var x = 5 + 2 + 3;
[Link]("demo").innerHTML = x;
</script>
• You can also add strings, but strings will be
concatenated:
Example
• var x = "John" + " " + "Doe";
JavaScript Assignment Operators

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
JavaScript String Operators

• The + operator can also be used to add (concatenate)


strings.
var txt1 = ”ABC";
var txt2 = ”XYZ";
var txt3 = txt1 + " " + txt2;
JavaScript Comparison Operators
Operat Description
or

== 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
Operator Name Comparison Type Example Output
Compares only values. If
== Equality Operator (loose types are different, 5 == "5" true
equality) JavaScript tries to convert
(type coercion).

Strict Equality Operator Compares both value and


=== (strict equality) type. No type conversion is 5 === "5" false
done.

[Link](5 == "5"); // true (only value checked, "5" is converted to number 5)


[Link](5 === "5"); // false (type mismatch: number vs string)

[Link](true == 1); // true (true is converted to 1)


[Link](true === 1); // false (boolean vs number)
Comparison
Operator Name Example Output
Type
Compares
only values. If
Inequality
types differ,
Operator
!= JavaScript 5 != "5" false
(loose
converts
inequality)
them before
comparing.
Compares
both value
Strict
and type. No
!== Inequality 5 !== "5" true
type
Operator
conversion is
done.
Comparison
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>

<h2>JavaScript Comparison</h2>
<h2>JavaScript Comparison</h2>
<p>Assign 5 to x, and display the value
<p>Assign 5 to x, and display the value of the comparison (x == of the comparison (x === 5):</p>
8):</p>
<p id="demo"></p>

<p id="demo"></p> <script>


var x =5;
<script> [Link]("demo").in
nerHTML = (x === 5);
var x = 5; </script>
[Link]("demo").innerHTML = (x == 8);
</script> </body>
</html>
</body>
</html>
JavaScript Logical Operators

Operator Name Description Example Result


Returns true if
both (5 > 2 && 10 >
&& Logical AND true
conditions are 5)
true
Returns true if
at least one (5 > 10 || 10 >
|| Logical OR true
condition is 5)
true
Reverses the
result (true →
! Logical NOT !(5 > 2) false
false, false →
true)
JavaScript Bitwise Operators

• Bit operators work on 32 bits numbers.


Operato Description Example Same as Result Decimal
r
& AND 5&1 0101 & 0001 1
0001
| OR 5|1 0101 | 0001 0101 5

~ NOT ~5 ~0101 1010 10


^ XOR 5^1 0101 ^ 0001 0100 4

<< Zero fill left shift 5 << 1 0101 << 1 1010 10


>> Signed right shift 5 >> 1 0101 >> 1 0010 2
>>> Zero fill right shift 5 >>> 1 0101 >>> 1 0010 2
Feature & (Bitwise AND) && (Logical AND)

Boolean/logical
Works On Numbers (bitwise)
expressions

Checks true/false
Operation Compares each bit
conditions

Boolean or one of the


Return Type Number
operands

Example 5&3→1 true && false → false


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

The typeof Operator typeof(a)


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:
typeof "" // Returns "string"
Undefined:
typeof "John" // Returns "string"
<script>
typeof "John Doe" // Returns "string“
var car;
typeof 0 // Returns "number“
[Link]("demo").inn
typeof 3.14 // Returns "number"
erHTML =
car + "<br>" + typeof car;
</script>
JavaScript if else and else if

• Use if to specify a block of code to be executed, if a specified condition is true


• Use else to specify a block of code to be executed, if the same condition is false
• Use else if to specify a new condition to test, if the first condition is false
• Use switch to specify many alternative blocks of code to be executed
The if Statement:
Syntax JavaScript if
if (condition) {
// block of code to be executed if the condition is true Display "Good day!" if the hour
}
<!DOCTYPE html>
is less than 18:00:
<html> Good day!
<body>
<h1>JavaScript if</h1>

<p>Display "Good day!" if the hour is less than 18:00:</p>


<p id="demo">Good Evening!</p>

<script>
if (new Date().getHours() < 18) {
[Link]("demo").innerHTML = "Good day!";
}
</script>

</body>
</html>
The else Statement

• Use the else statement to specify a block of code to be executed if the condition is false.
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example:
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
The else if Statement:
Syntax
• if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
• <!DOCTYPE html>
•Morning check:
• <html>
• <body> If the hour is less
• <p id="demo"></p> than 12 → “Good
Morning!”
• <script> •Afternoon check:
• let hour = new Date().getHours(); If the hour is 12–17
→ “Good
• if (hour < 12) {

Afternoon!”
[Link]("demo").innerHTML = "Good Morning!";

•Else fallback:
} else if (hour < 18) {
• [Link]("demo").innerHTML = "Good Afternoon!";If the hour is 18 or
• } else { later → “Good
• [Link]("demo").innerHTML = "Good Evening!"; Evening!”
• }
• </script>

• </body>
• </html>
JavaScript Switch Statement

• Use the switch statement to select one of many code blocks


to be executed.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
• <!DOCTYPE html>
• <html>
• <body>
• <h1>JavaScript Control Flow</h1>
• <h2>The switch Statement</h2>

• <p id="demo"></p>

• <script>
• let day; JavaScript Control Flow
• switch (new Date().getDay()) {
• case 0: The switch Statement


day = "Sunday";
break;
Today is Thursday
• case 1:
• day = "Monday";
• break;
• case 2:
• day = "Tuesday";
• break;
• case 3:
• day = "Wednesday";
• break;
• case 4:
• day = "Thursday";
• break;
• case 5:
• day = "Friday";
• break;
• case 6:
• day = "Saturday";
• }
• [Link]("demo").innerHTML = "Today is " + day;
• </script>

• </body>
• </html>
Feature / Aspect if if…else else if (ladder) switch

Execute code only if a Execute one block if Compare a single


Purpose condition is true. condition is true, otherwise Test multiple conditions
sequentially. expression against multiple
another. fixed values.

Condition Type Any boolean expression. Any boolean expression. Multiple boolean Strict equality (===) with
expressions. constant values.

Syntax Simplicity Very simple. Simple for two outcomes. Becomes lengthy with many Cleaner
when
than many else if
checking one
conditions. variable.

Range / Complex Logic Excellent (supports <, >, Excellent Excellent Not suited—only exact
&&, etc.) matches.

Need for break No No No Yes, to avoid fall-through


between cases.

Default / Fallback Not built-in (add your own Built-in else branch. End with final else for default case handles
else). fallback. unmatched values.

Performance Fast; negligible difference Same as if. Slightly slower with many Slight edge when many
for small sets. conditions. discrete values are checked.

Typical Use Single true/false check. Two possible outcomes. Multiple, possibly range- Menu selections, day-of-
based checks. week, enumerations, etc.

Example if (x > 10) { ... } if (x>10){...} else {...} if (x>90){...} else if (x>75) switch(day){case 1: ...
{...} break;}
JavaScript For Loop
 Loops can execute a block of code a number of times.
 for (expr1; expr2; expr) {
// code block to be executed
}
 Example:
<!DOCTYPE html> JavaScript For Loop
<html>
<body>
BMW
Volvo
<h2>JavaScript For Loop</h2>
Saab
<p id="demo"></p> Ford
Fiat
<script>
var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"]; // Array of car names Audi
var text = ""; //Empty string to hold output
var i; //Loop counter
// For loop: runs from i = 0 up to i < [Link]
for (i = 0; i < [Link]; i++) {
text += cars[i] + "<br>"; // text=text+cars[i];
// Add each car name plus an HTML line break

}
[Link]("demo").innerHTML = text; // Display the combined string inside the <p id="demo"> element
</script>

</body>
</html>
Different Kinds of Loops

• JavaScript supports different kinds of loops:


• for - loops through a block of code a number of times
• for/in - loops through the properties of an object
• for/of - loop can be used to get the values from the
array
• while - loops through a block of code while a
specified condition is true
• do/while - also loops through a block of code while a
specified condition is true
i=10;
While(i>10)
i--;
Aspect while loop do…while loop
Checked before each Checked after the first
Condition Check
iteration. iteration.
May execute 0 times if Executes at least once
Minimum Executions
condition is false. regardless of condition.
Syntax while (condition) { … } do { … } while (condition);
When you need to run When code must run
Use Case code only if the condition once before the first
is initially true. condition check.
Example (condition false No output if condition is Runs body once, then
at start) false. stops if condition is false.

Var i=1; var i=1;


While(i<10){ do{
[Link](i+”<br>”); [Link](i+”<br>”);
i++;
} i++;}

while(i<10);
The For Loop

• The for loop has the following syntax:


for (statement 1; statement 2; statement 3) {
// code block to be executed
}
The number is 0
The number is 1
<script> The number is 2
var text = ""; //Create an empty string to build the output The number is 3
var i; //Loop counter The number is 4
for (i = 0; i < 5; i++) { \\ For loop: runs while i is less than 5
text += "The number is " + i + "<br>"; // Add a line of text for each iteration
}
[Link]("demo").innerHTML = text;
\\Place the final string inside the element with id="demo"
</script>
The For/In Loop
• The JavaScript for/in statement loops through the properties of an object:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript for...in Loop (Object)</h2>
<p id="demo"></p>
<script>
// Create an object with three properties
let person = { firstName: "John", lastName: "Doe", age: 25};
let text = ""; // Prepare an empty string to store the output
JavaScript for...in Loop
// Use for...in loop to iterate over all keys (property names) of the (Object)
object
for (let key in person) { firstName : John
// Append each key and its value to the text string, adding a linelastName
break : Doe
text += key + " : " + person[key] + "<br>"; age : 25
}
// Display the final string inside the <p> element with id="demo"
[Link]("demo").innerHTML = text;
</script>

</body>
</html>
The For/Of Loop
syntax:
for (variable of iterable) {
// code block to be executed
}
Looping over an Array:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript for...of Loop (Array)</h2>
<p id="demo"></p>
JavaScript for...of Loop
<script> (Array)
// Create an array of car names
BMW
let cars = ["BMW", "Volvo", "Audi"];
// Empty string to collect the output Volvo
let text = ""; Audi
// The for...of loop iterates over the VALUES of the array
for (let car of cars) {
// 'car' holds each element's value directly (e.g., "BMW", then "Volvo", then "Audi")
text += car + "<br>"; // Add the value and a line break to the text string
}
// Display the final string inside the <p> element with id="demo"
[Link]("demo").innerHTML = text;
</script>

</body>
</html>
Example Output
with cars =
Loop Type Iterates Over Best For
["BMW","Volvo","
Audi"]
Index (counter Arrays (with 0 : BMW, 1 : Volvo,
for
variable) indexes) 2 : Audi
0 : BMW, 1 : Volvo,
2 : Audi (for
Keys / Indexes /
for...in Objects & Arrays array)name : John,
Properties
age : 25 (for
object)
Arrays, Strings,
for...of Values (of iterable) BMW, Volvo, Audi
Sets, Maps
• For Loop
• 3
Let num =[3,5,1,2,4]
5
• For(let i=0;i<[Link];i++){ 1
2
• [Link](num[i]); 3
• }

For Each
• [Link](element)=> {
• [Link](element*element)
• })

• For….of
• For(let i of num) {
3
• [Link](i) 5
} 1
2
3
JavaScript Data Types

• JavaScript variables can hold many data types: numbers,


strings, objects and more:
• var length = 16; // Number
var lastName = "Johnson"; // String
var x = {firstName:"John", lastName:"Doe"}; // Object
JavaScript Types are Dynamic
JavaScript has dynamic types. This means that the same variable
var x; // Now x is undefined
can be used to hold different data types:
x = 5; // Now x is a Number
JavaScript Strings: x = "John"; // Now x is a String
Strings are written with quotes. You can use single or double
quotes:
JavaScript Numbers:E xtra large or extra small numbers
can be written with scientific (exponential) notation: var y =
123e5; // 12300000
var z = 123e-5; // 0.00123
Primitive Data
A primitive data value is a single simple data value with no additional properties and methods.
The typeof operator can return one of these primitive types:

• string
• number
• boolean
• Undefined
Complex Data:
The typeof operator can return one of two complex types:
• function
• object
The typeof operator returns "object" for objects, arrays, and null.
The typeof operator does not return "object" for functions.

typeof {name:'John', age:34} // Returns "object"


typeof [1,2,3,4] // Returns "object" (not "array", see note below)
typeof null // Returns "object"
typeof function myFunc(){} // Returns "function"
NOTE: The typeof operator returns "object" for arrays because in JavaScript arrays are objects.
var y = 5;
var z = 6;
JavaScript Booleans: (x == y) // Returns true
(x == z) // Returns false

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):
var cars = ["Saab", "Volvo", "BMW"];
JavaScript Objects

• JavaScript objects are written with curly braces {}.


• Object properties are written as name:value pairs,
separated by commas.
var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
JavaScript Display Output

Method Where It Shows Example


Directly in the web page
[Link]() [Link]("Hello");
(replaces content)
[Link](
Inside a specific HTML
[Link] "demo").innerHTML =
element
"Hello";
alert() Popup dialog box alert("Hello");
Browser’s developer
[Link]() [Link]("Hello");
console
Opens the browser print
[Link]() [Link]();
dialog
Array
• An Array is an object type designed for storing data collections.
• Key characteristics of JavaScript arrays are:
• Elements: An array is a list of values, known as elements.
• Ordered: Array elements are ordered based on their index.
• Zero indexed: The first element is at index 0, the second at index 1, and so on.
• Dynamic size: Arrays can grow or shrink as elements are added or removed.
• Heterogeneous: Arrays can store elements of different data types (numbers, strings, objects
and other arrays).
Example: let arr = [42, "Hello", true, {name: “Riya"}, [1, 2, 3], null];
[Link](arr);

an array is a special variable that can hold multiple values at a time under a single name. Each
value in an array is called an element, and each element has an index (position), starting from 0.

Declaring Arrays
1. Using Array Literal (most common)
let fruits = ["Apple", "Banana", "Mango"];
2. Using new Array()
let numbers = new Array(10, 20, 30, 40);
Why use array
• We use arrays in JavaScript because they •Efficient Looping
make it easier to store, organize, and process We can use loops to process all
multiple values under a single variable name. values quickly:
• Store Multiple Values in One Variable
for (let i = 0; i < [Link];
Instead of creating many variables:
i++) { [Link](students[i]); }
• let student1 = "Aman"; •Built-in Methods for Operations
• let student2 = "Riya";
Arrays provide helpful methods:
• let student3 = "Karan"; •push() → add element
•Store Multiple Values in One Variable
•pop() → remove last element
Instead of creating many variables:
let student1 = "Aman"; let student2 =
•slice() → copy part of array
"Riya"; let student3 = "Karan"; •sort() → arrange values
•Better Organization
We can use an array: Arrays keep related data together in
let students = ["Aman", "Riya", "Karan"]; one structure, which makes programs
•Easy Access Using Index
easier to read and maintain.
Each value can be accessed using its index:
[Link](students[0]); // Aman
[Link](students[2]); // Karan
Creating Array
• Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
var array_name = [item1, item2, ...];
Example:
<!DOCTYPE html>
<html> OUTPUT
<body>
<h1>JavaScript Arrays</h1> JavaScript Arrays
Saab,Volvo,BMW
<p id="demo"></p>

<script>
const cars = ["Saab", "Volvo", "BMW"];
[Link]("demo").innerHTML = cars;
</script>

</body>
</html>
Example: Access the Elements of an Array
<!DOCTYPE html>
<html>
<body>
<h2>Accessing Elements in JavaScript Array</h2>
<p id="demo"></p>

<script>
// Declare an array
let fruits = ["Apple", "Banana", "Mango", "Orange"]; OUTPUT
First Fruit: Apple
// Access elements by index
let firstFruit = fruits[0]; // Apple (index 0) Second Fruit: Banana
let secondFruit = fruits[1]; // Banana (index 1) Last Fruit: Orange
let lastFruit = fruits[[Link] - 1]; // Orange (last element)

// Display results
let text = "First Fruit: " + firstFruit + "<br>";
text += "Second Fruit: " + secondFruit + "<br>";
text += "Last Fruit: " + lastFruit;

[Link]("demo").innerHTML = text;
</script>
</body>
</html>
Using the JavaScript Keyword new OUTPUT:
The following example also creates an Array, and assigns values to it:
Saab,Volvo,BMW
var cars = new Array("Saab", "Volvo", "BMW");
Changing an Array Element:
var cars = [“BMW", "Volvo", “Saab"];
OUTPUT:
cars[1] = "Opel";
BMW,Opel,Saab
[Link]("demo").innerHTML = cars;
• Access the Full Array
• const cars = ["Saab", "Volvo", "BMW"]; OUTPUT:
[Link]("demo").innerHTML = cars; Saab,Volvo,BMW
• Arrays are Objects
• const person = {firstName:"John", lastName:"Doe", age:46};
• [Link]("demo").innerHTML = [Link];
• Array Elements Can Be Objects

• myArray[0] = [Link];
myArray[1] = myFunction;
myArray[2] = myCars;
Array Properties and Methods

The length Property


The length property of an array returns the length of an array (the number of array elements).
Accessing the First Array Element:
vegi = [“potatao", “ onion", “tomato" ]; var fruits = ["Banana", "Orange", "Apple", "Mango"];
var first = vegi[0]; [Link]; // the length of fruits is 4
[Link](first);

Accessing the Last Array Element:

var vegi = [“potatao", “ onion", “tomato" ];


var last = vegi[[Link]-1];
Array elements are accesses using
numeric indexes
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>JavaScript array elements are accesses using numeric indexes
(starting from 0).</p>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"]; OUTPUT:
Mango
var last = fruits[[Link]-1];
[Link]("demo").innerHTML = last;
</script>
</body>
</html>
Looping Array Elements
• The safest way to loop through an array, is using a for loop
<!DOCTYPE html>
<html>
<body>
<h2>Fruit List</h2>
<script>
// Declare variables
var fruits, text, fLen, i;
// Initialize the fruits array
fruits = ["Banana", "Orange", "Apple", "Mango"];
// Find total number of fruits
fLen = [Link];
// Start the ordered list HTML
1. Banana
text = "<ol>";
// Loop through each fruit and add as a list item 2. Orange
for (i = 0; i < fLen; i++) { 3. Apple
text += "<li>" + fruits[i] + "</li>"; 4. Mango
}
// Close the ordered list
text += "</ol>";
// Write the list directly to the document
[Link](text);
</script>
</body>
</html>
You can also use
the [Link]() function:
Syntax:
[Link](function(currentValue, index, array) {
// code to execute for each element
});
var fruits, text;
fruits = ["Banana", "Orange", "Apple", "Mango"];
// Start unordered list Output:
text = "<ul>"; Fruit List
•Banana
// Loop through each element in the array
•Orange
[Link](myFunction);
•Apple
// Close unordered list •Mango
text += "</ul>";
// Function to add each fruit as a list item
function myFunction(value) {
text += "<li>" + value + "</li>";
}

Note :[Link]() is not supported in Internet Explorer 8 or earlier.


Example

• let fruits = ["Banana", "Orange", "Apple",


"Mango"];

• [Link](function(fruit) {
• [Link](fruit);
• });
Adding Array Elements
The push() method:
<!DOCTYPE html>
<html> New element can also be added to an array using the
<body> length property:
<h2>JavaScript Arrays</h2>
<p>The push method appends a new element to an array.</p>
<!-- Button that calls the addFruit() function when clicked -->
<button it</button>
<!-- Paragraph to display the array -->
<p id="demo"></p>
<script>
// Create an array of fruit names
var fruits = ["Banana", "Orange", "Apple", "Mango"];
// Show the initial array on the page
[Link]("demo").innerHTML = fruits;
// Function to add a new fruit to the array
function addFruit() {
// Add "Lemon" to the end of the fruits array
[Link]("Lemon");
// Update the paragraph to show the updated array
[Link]("demo").innerHTML = fruits;
}
</script>
</body>
</html>
Associative Arrays
• Many programming languages support arrays with named indexes.
• Arrays with named indexes are called associative arrays (or hashes).
• JavaScript does not support associative arrays
• In JavaScript, arrays always use numbered indexes.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p> JavaScript Arrays
<script>
// Create an empty array named person
John 3
var person = [];
// Assign values to specific indexes
person[0] = "John"; // First element
person[1] = "Doe"; // Second element
person[2] = 46; // Third element (a number)
// Display the first element and the total length of the array
// person[0] is "John"
// [Link] returns 3 because there are 3 elements (0,1,2)
[Link]("demo").innerHTML =
person[0] + " " + [Link];
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>
<p>If you use a named index when accessing an array, JavaScript will redefine the array to
a standard object, and some array methods and properties will produce undefined or
incorrect results.</p>
<p id="demo"></p>
JavaScript Arrays
<script> If you use a named index when
var person = []; accessing an array, JavaScript will
person["firstName"] = "John"; redefine the array to a standard
person["lastName"] = "Doe"; object, and some array methods
person["age"] = 46; and properties will produce
[Link]("demo").innerHTML = undefined or incorrect results.
person[0] + " " + [Link];
</script>
undefined 0
</body>
</html>
JavaScript Array Methods

• Converting Arrays to Strings


• Popping and Pushing
• Shifting Elements
• Changing Elements
• Deleting Elements
• Splicing an Array
• Slicing an Array
• Automatic toString()
• Sorting Arrays
Converting Arrays to Strings

The JavaScript method toString() converts an array to a string of (comma separated) array values.
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"]; Banana ,Orange ,Apple ,Man
[Link]("demo").innerHTML = [Link](); go
</script>
The join() method also joins all array elements into a
string. It behaves just like toString(), but in addition you
can specify the separator:
<p id="demo"></p> Banana * Orange * Apple * Mango
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]("demo").innerHTML =
[Link](" * ");
</script>
Feature / Aspect toString() join(separator)
Converts the array to
Converts the array to
Purpose a string with a custom
a string.
separator.
Comma , (fixed, Comma , if no
Default Separator cannot be changed). separator is specified.
✅ Pass any string (e.g.,
Custom Separator ❌ Not supported.
" - ", `"
Syntax [Link]() [Link](separator)
Return Type String String
[1,2,3].toString() → [1,2,3].join(" - ") → "1
Example
"1,2,3" - 2 - 3"
JavaScript Array Methods

• Converting Arrays to Strings


• Popping and Pushing
• Shifting Elements
• Changing Elements
• Deleting Elements
• Splicing an Array
• Slicing an Array
• Automatic toString()
• Sorting Arrays
Popping and Pushing

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


<p id="demo1"></p> Banana,Orange,Apple,Mango
<p id="demo2"></p>
<script> Banana,Orange,Apple
var fruits = ["Banana", "Orange", "Apple", "Mango"];
// show the full array
[Link]("demo1").innerHTML = fruits;
[Link](); // Remove the last element
//Show the array again after removal
[Link]("demo2").innerHTML = fruits;
</script>
The pop() method returns the value that was "popped out":
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = [Link](); // the value of x is "Mango“
Pushing

The push() method adds a new element to an


array (at the end):
var fruits = ["Banana", "Orange", "Apple",
"Mango"];
[Link]("Kiwi"); // Adds a new element
("Kiwi") to fruits
[Link]("demo2").innerHTML =
fruits;

The push() method returns the new array length:


var fruits = ["Banana", "Orange", "Apple",
"Mango"];
JavaScript Array Methods

• Converting Arrays to Strings


• Popping and Pushing
• Shifting Elements
• Changing Elements
• Deleting Elements
• Splicing an Array
• Slicing an Array
• Automatic toString()
• Sorting Arrays
Shifting Elements
• Shift ()
•Purpose: Removes the first element of the array.
•Returns: The element that was removed.
•Effect: All remaining elements move one position to the left (lower index).
• let fruits = ["Banana", "Orange", "Apple", "Mango"];
• let removed = [Link]();

• [Link](removed); // "Banana"
• [Link](fruits); // ["Orange", "Apple", "Mango"]
unshift()
•Purpose: Adds one or more elements to the beginning of the array.
•Returns: The new length of the array.
• let fruits = ["Banana", "Orange", "Apple", "Mango"];
• let newLength = [Link]("Lemon");

• [Link](newLength); // 5
• [Link](fruits); // ["Lemon", "Banana", "Orange", "Apple", "Mango"]
shift() method returns the
element that was shifted out.
<!DOCTYPE html>
<html> Banana,Orange,Apple,Mango
<body> Banana
<h2>JavaScript Array Methods</h2> Orange,Apple,Mango
<h2>shift()</h2>
<p>The shift() method returns the element that was shifted
out.</p> The unshift() method returns th
<p id="demo1"></p> array length.
<p id="demo2"></p> var fruits =
<p id="demo3"></p> ["Banana", "Orange", "Apple", "
<script> ];
[Link]("Lemon"); // Ret
var fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]("demo1").innerHTML = fruits;
[Link]("demo2").innerHTML = [Link]();
[Link]("demo3").innerHTML = fruits;
</script>
</body>
JavaScript Array Methods

• Converting Arrays to Strings


• Popping and Pushing
• Shifting Elements
• Changing Elements
• Deleting Elements
• Splicing an Array
• Slicing an Array
• Automatic toString()
• Sorting Arrays
Changing Elements
Array elements are accessed using their index number:
<p id="demo1"></p>
<p id="demo2"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]("demo1").innerHTML = fruits; Banana,Orange,Apple,Mango
fruits[0] = "Kiwi";
[Link]("demo2").innerHTML = fruits; Kiwi,Orange,Apple,Mango
</script>
The length property provides an easy way to append a new element to an array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[[Link]] = "Kiwi"; // Appends "Kiwi" to fruits
JavaScript Array Methods

• Converting Arrays to Strings


• Popping and Pushing
• Shifting Elements
• Changing Elements
• Deleting Elements
• Splicing an Array
• Slicing an Array
• Automatic toString()
• Sorting Arrays
Deleting Elements

Since JavaScript arrays are objects, elements can


•Before delete
be deleted by using the JavaScriptfruits
operator
= ["Banana", "Orange",
delete: "Apple", "Mango"]
fruits[0] → "Banana"
var fruits = ["Banana", "Orange", "Apple", "Mango"];
•After delete fruits[0]
•The element at index 0 is
// Show the first element
removed, but the slot remains.
[Link]("demo1").innerHTML =•The array now looks like:
"The first fruit is: " + fruits[0]; [empty, "Orange", "Apple",
"Mango"].
// Delete the first element •[Link] is still 4.
delete fruits[0]; •Accessing fruits[0]
•Returns undefined because the
// Show the first element again
value is missing.
[Link]("demo2").innerHTML =
"The first fruit is: " + fruits[0];
JavaScript Array Methods

• Converting Arrays to Strings


• Popping and Pushing
• Shifting Elements
• Changing Elements
• Deleting Elements
• Splicing an Array
• Slicing an Array
• Automatic toString()
• Sorting Arrays
Splicing an Array

splice() can add, remove, or replace elements in place and always


returns an array of the elements that were removed
OUTPUT:
Syntax: [Link](startIndex, deleteCount, item1, item2, ...)
["Banana", "Orange",
The splice() method can be used to add new items to an"Lemon", array: "Kiwi",
var fruits = ["Banana", "Orange", "Apple", "Mango"]; "Apple", "Mango"]
[Link](2, 0, "Lemon", "Kiwi");
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 ["Banana",
deleted items:"Orange", "Lemon",
).
"Kiwi"]
var fruits = ["Banana", "Orange", "Apple", "Mango"];
removed → ["Apple", "Mango"]
[Link](2, 2, "Lemon", "Kiwi"); (array of deleted items
Splicing an Array : Example
<!DOCTYPE html>
<html> JavaScript Array Methods
<body> splice()
<h2>JavaScript Array Methods</h2> The splice() method adds new elements to
<h2>splice()</h2> an array.
<p>The splice() method adds new elements to an array.</p> Try it
Original Array:
<button it</button>
Banana,Orange,Apple,Mango
<p id="demo1"></p> New Array:
<p id="demo2"></p> Banana,Orange,Lemon,Kiwi,Apple,Mango
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]("demo1").innerHTML = "Original Array:<br>" + fruits;
function myFunction() {
[Link](2, 0, "Lemon", "Kiwi");
[Link]("demo2").innerHTML = "New Array:<br>" + fruits;
}
</script>

</body>
The splice() method returns
an array with the deleted
<!DOCTYPE html>
<html>
items:
<body>
<h2>JavaScript Array Methods</h2>
<h2>splice()</h2>
<p>The splice() method adds new elements to an array, and returns an array with the deleted elements (if any).</p>
<button it</button>
<p id="demo1"></p> JavaScript Array Methods
<p id="demo2"></p> splice()
<p id="demo3"></p> The splice() method adds new elements
<script> to an array, and returns an array with
var fruits = ["Banana", "Orange", "Apple", "Mango"]; the deleted elements (if any).
[Link]("demo1").innerHTML = "Original Array:<br> " + fruits; Try it
function myFunction() { Original Array:
var removed = [Link](2, 2, "Lemon", "Kiwi"); Banana,Orange,Apple,Man
[Link]("demo2").innerHTML = "New Array:<br>" + fruits; New Array:
[Link]("demo3").innerHTML = "Removed Items:<br> " + removed; Banana,Orange,Lemon,Kiwi
} Removed Items:
</script> Apple,Mango
</body>
</html>
Using splice() to Remove Elements
With clever parameter setting, you can use splice() to remove elements without leaving
"holes" in the array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link](0, 1); // Removes the first element of fruits
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.
Merging (Concatenating) Arrays:
The concat() method creates a new array by merging (concatenating) existing
arrays:
var myGirls = ["Cecilie", "Lone"];
var myBoys = ["Emil", "Tobias", "Linus"];
var myChildren = [Link](myBoys); // Concatenates
(joins)OUTPUT:
myGirls["Cecilie", "Lone", "Emil", "Tobias", "Linus"]
and myBoys
The concat() method can take any number of array arguments:
var arr1 = ["Cecilie", "Lone"];
var arr2 = ["Emil", "Tobias", "Linus"]; Cecilie,Lone,Emil,Tobias,Linus,Robin,Mor
gan
var arr3 = ["Robin", "Morgan"];
var myChildren = [Link](arr2, arr3); // Concatenates arr1 with arr2 and
arr3
The concat() method can also take strings as arguments:
var arr1 = ["Emil", "Tobias", "Linus"];
var myChildren = [Link]("Peter"); Emil,Tobias,Linus,Peter
JavaScript Array Methods

• Converting Arrays to Strings


• Popping and Pushing
• Shifting Elements
• Changing Elements
• Deleting Elements
• Splicing an Array
• Slicing an Array
• Automatic toString()
• Sorting Arrays
Slicing an Array
• 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"):
Banana,Orange,Lemon,Apple,Mango
<p id="demo"></p> Banana
<script>
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = [Link](0);
[Link]("demo").innerHTML = fruits + "<br><br>" + citrus;
</script>
<p id="demo"></p>
This example slices out a part of an array starting from array element 3 ("Apple"):
Banana,Orange,Lemon,Apple,Man
<script>
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; Apple,Mango
var citrus = [Link](3);
[Link]("demo").innerHTML = fruits + "<br><br>" + citrus;
</script>
• 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.
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = [Link](1, 3);
If the end argument is omitted, like in the first examples, the slice() method slices out
the rest of the array.
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Lemon", "Apple", Banana,Orange,Lemon,Apple,Mango
"Mango"];
var citrus = [Link](2); Lemon,Apple,Mango
[Link]("demo").innerHTML = fruits +
"<br><br>" + citrus;
</script>
JavaScript Array Methods

• Converting Arrays to Strings


• Popping and Pushing
• Shifting Elements
• Changing Elements
• Deleting Elements
• Splicing an Array
• Slicing an Array
• Automatic toString()
• Sorting Arrays
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:
var fruits = ["Banana", "Orange", "Apple", "Mango"]; Banana,Orange,Apple,Mango
[Link]("demo").innerHTML = [Link]();

var fruits =
["Banana", "Orange", "Apple", "Mango"];
[Link]("demo").innerHTML =
fruits;
JavaScript Sorting Arrays

The sort() method sorts an array alphabetically:

<!DOCTYPE html>
<html>
<head>
<title>Sort Fruits Example</title>
</head>
<body>
<h2>Fruit Array Sorting</h2>
<p id="demo"></p>
<!-- Button to sort fruits -->
<button Fruits Alphabetically</button>
<script>
// Array of fruits
var fruits = ["Banana", "Orange", "Apple", "Mango"];

// Display original array


[Link]("demo").innerHTML = "Original Array: " + fruits;

// Function to sort the array


function myFunction() {
[Link](); // Sort alphabetically
[Link]("demo").innerHTML = "Sorted Array: " + fruits;
}
</script>

</body>
</html>
Reversing an Array

• The reverse() method reverses the elements in


an array.
You can use it to sort an array in Orange,Mango,Banana,Apple
descending
order:

var fruits =
["Banana", "Orange", "Apple", "Mango"];
[Link](); // First sort the elements of fruits
[Link](); // Then reverse the order of the
elements
Sort()
By combining sort() and reverse() you can sort an
<!DOCTYPE html> array in descending order.
<html> Try it
<body> Banana,Orange,Apple,Mango
Orange,Mango,Banana,Apple
<h2>JavaScript Array Sort Reverse</h2>
<p>The reverse() method reverses the elements in an array.</p>
<p>By combining sort() and reverse() you can sort an array in descending order.</p>
<button it</button>
<p id="demo"></p>
<script>
// Create and display an array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]("demo").innerHTML = fruits;
function myFunction() {
[Link](); // First sort the array
[Link](); // Then reverse it:
[Link]("demo").innerHTML = fruits;
} </script>
</body>
</html>
Numeric Sort
// sort in ascending
<button it</button>
<p id="demo"></p>
<script>
var points = [40, 100, 1, 5, 25, 10];
[Link]("demo").innerHTML = points;
function myFunction() {
[Link](function(a, b){return a - b});
[Link]("demo").innerHTML = points;
} </script>
// sort in descending
<button it</button>

<p id="demo"></p>

<script>
var points = [40, 100, 1, 5, 25, 10];
[Link]("demo").innerHTML = points;

function myFunction() {
[Link](function(a, b){return b - a});
[Link]("demo").innerHTML = points;
}
</script>

You might also like