JavaScript Data Types and Syntax Guide
JavaScript Data Types and Syntax Guide
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
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
[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 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
•
After the first character, identifiers can contain letters, digits ,$ , 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).
<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>
Boolean/logical
Works On Numbers (bitwise)
expressions
Checks true/false
Operation Compares each bit
conditions
Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an instance of an object type
<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
• <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
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.
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
while(i<10);
The For Loop
</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
• 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.
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
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
• [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
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
• [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
</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
var fruits =
["Banana", "Orange", "Apple", "Mango"];
[Link]("demo").innerHTML =
fruits;
JavaScript Sorting Arrays
<!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"];
</body>
</html>
Reversing an Array
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>