Javascript
Javascript
// Strings:
let color = "Yellow";
let lastName = "Johnson";
// Booleans
let x = true;
let y = false;
// Object:
const person = {firstName:"John", lastName:"Doe"};
// Array object:
const cars = ["Saab", "Volvo", "BMW"];
// Date object:
const date = new Date("2022-03-25");
One of many JavaScript HTML methods is getElementById().
Simple program:
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button"
onclick='[Link]("demo").innerHTML = "Hello
JavaScript!"'>Click Me!</button>
// Passing arguments
welcome("Rohan");
Return Value:
function welcome() {
// Return statement
return "Welcome to GfG";
}
[Link](welcome());
Function Expression:
let welcome = function () {
return "Welcome to GfG";
}
[Link](gfg);
Types Of Functions in JavaScript:
1. Named function:
function add(a, b) {
return a + b;
}
[Link](add(5, 4));
[Link] function:
let add = function (a, b) {
return a + b;
}
[Link](add(5, 4));
[Link] Functions:
function msg(firstName) {
function hey() {
[Link]("Hey " + firstName);
}
return hey();
}
msg("Ravi");
[Link] invoked function expression:
let msg = (function() {
return "Welcome to GfG" ;
})();
[Link](msg);
JavaScript Function Call:
The call() method is a predefined JavaScript method. It can be used to invoke
(call) a method with an owner object as an argument (parameter).
Example:
function product(a, b) {
return a * b;
}
// Calling product() function
let result = [Link](this, 20, 5);
[Link](result);
Example:
let employee = {
details: function (designation, experience) {
return [Link]
+""
+ [Link]
+ designation
+ experience;
}
}
// Objects declaration
let emp1 = {
name: "A",
id: "123",
}
let emp2 = {
name: "B",
id: "456",
}
let x = [Link](emp2, " Manager ", "4 years");
[Link](x);
Different ways of writing functions in JavaScript:
1. Function Declaration:
A Function Declaration is the traditional way to define a function. It starts with
the function keyword, followed by the function name and any parameters the
function needs.
Example:
// Function declaration
function add(a, b) {
[Link](a + b);
}
// Calling a function
add(2, 3);
2. Function Expression:
Function Expression is another way to define a function. Here, the function is
defined inside a variable, and the function’s value (its returned value) is stored
in that variable.
// Function Expression
const add = function (a, b) {
[Link](a + b);
}
// Calling function
add(2, 3);
3. Arrow Functions:
Arrow Functions were introduced in ES6 (a newer version of JavaScript). They
provide a shorter syntax for writing functions. Instead of using the function
keyword, you use an arrow (=>).
let add = (a, b) => a + b;
[Link](add(3, 2));
Different Function States in JavaScript
the difference between
[Link] Person( ) { },
[Link] person = Person ( )
[Link] person = new Person ( ).
Example:
// Function declaration
function person() { }
let person = person()
// Printing the return value
// of the person() function
[Link](person)
function person1(name) {
return name;
}
let person1 = person1("Aayush")
// Printing the value of person1
[Link](person1)
function constructor in Javascript:
// Creating the function
function Person(name, age) {
[Link] = name;
[Link] = age;
}
// Calling the function
let person = new Person("Vikah", 22);
[Link]([Link]);
[Link]([Link]);
Example:
<body>
<h3> LOGIN </h3>
<formform ="Login_form" onsubmit="submit_form()">
<h4> USERNAME</h4>
<input type="text" placeholder="Enter your email id"/>
<h4> PASSWORD</h4>
<input type="password" placeholder="Enter your password"/></br></br>
<input type="submit" value="Login"/>
<input type="button" value="SignUp" onClick="create()"/>
</form>
<script type="text/javascript">
function submit_form(){
alert("Login successfully");
}
function create(){
[Link]="[Link]";
}
</script>
JavaScript Statements
JavaScript statements are programming instructions that a computer
executes. A computer program is essentially a list of these
“instructions” designed to perform tasks. In a programming language,
such instructions are called statements.
Types of Statements:
1. Variable Declarations (var, let, const):
Example:
let name = "Mohan"; // Declaration with 'let'
const age = 25; // Declaration with 'const' (constant value)
var isActive = true; // Declaration with 'var' (older version)
2. Assignment Statement:
An assignment statement is used to assign a value to a variable.
Example:
let number = 10; // Assigning a number
let message = "Hello, World!"; // Assigning a string
3. Expression Statements:
An expression in JavaScript is any valid unit of code that resolves to a
value.
Example:
x = y + 10; // Expression statement
[Link](x); // Expression statement using a function call.
4. Control Flow Statements:
Control flow statements are used to control the order in which
statements are executed in a program. Examples include if, else,
switch, while, and for loops.
Example:
let number = 10;
if (number > 5) {
[Link]("Number is greater than 5");
}
5. Function Declarations:
A function declaration is a statement that defines a function in
JavaScript. Functions are reusable blocks of code designed to perform
specific tasks.
Example:
function greet(name) {
return "Hello, " + name;
}
[Link](greet("Alisha"));
6. Return Statement:
The return statement is used to exit a function and optionally pass a
value back to the calling code.
Example:
function add(x, y) {
return x + y;
}
let result = add(5, 3); // result will be 8
7. Throw Statement:
The throw statement is used to create custom errors in JavaScript. It is
often used in conjunction with try…catch to handle errors.
Example:
function checkAge(age) {
if (age < 18) {
throw new Error("Age must be 18 or older");
}}
9. Break and Continue Statements:
The break and continue statements are used within loops. break exits
the loop, while continue skips to the next iteration.
Example:
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Exits the loop when i equals 5
}
[Link](i);
}
JavaScript if-else:
JavaScript if-else statement executes a block of code based on a
condition. If the condition evaluates to true, the code inside the “if”
block executes; otherwise, the code inside the “else” block, if present,
executes.
JavaScript if-statement
if(condition)
{
}
JavaScript if-else statement
if (condition){
//statement
}
Else{
//statement
}
Example:
// JavaScript program to illustrate If-else statement
let i = 10;
if (i < 15)
[Link]("i is less than 15");
else
[Link]("I am Not in if");
JavaScript nested-if statement:
JavaScript allows us to nest if statements within if statements. i.e, we
can place an if statement inside another if statement. A nested if is an
if statement that is the target of another if or else.
Syntax:
if(condition1){
if(condition2){}}
Example:
// JavaScript program to illustrate nested-if statement
let i = 10;
if (i == 10) { // First if statement
if (i < 15) {
[Link]("i is smaller than 15");
// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
[Link]("i is smaller than 12 too");
else
[Link]("i is greater than 15");
}
}
JavaScript if-else-if ladder statement
Syntax:
if (condition){
//statement
}
Else if(condition2){
//statement
}
Else{}
Example:
// JavaScript program to illustrate nested-if statement
let i = 20;
if (i == 10)
[Link]("i is 10");
else if (i == 15)
[Link]("i is 15");
else if (i == 20)
[Link]("i is 20");
else
[Link]("i is not present");
Example:
<h1>JavaScript Statements</h1>
<h2>The if...else Statements</h2>
<p>Please input a number between 1 and 10:</p>
<input id="numb" type="text">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
var x, text;
// Get the value of input field with id="numb"
x = [Link]("numb").value;
<script>
function myFunction() {
var text;
var favDrink = prompt("What's your favorite cocktail drink?",
"Daiquiri");
switch(favDrink) {
case "Martini":
text = "Excellent choice. Martini is good for your soul.";
break;
case "Daiquiri":
text = "Daiquiri is my favorite too!";
break;
case "Cosmopolitan":
text = "Really? Are you sure the Cosmopolitan is your favorite?";
break;
default:
text = "I have never heard of that one..";
}
[Link]("demo").innerHTML = text;
}
</script>
JavaScript Break Statement:
JavaScript break statement is used to terminate the execution of the
loop or the switch statement when the condition is true.
JavaScript Continue Statemen:t
The continue statement in JavaScript is used to break the iteration of
the loop and follow with the next iteration.
Continue vs Break:
The major difference between the continue and break statement is that
the break statement breaks out of the loop completely while continue
is used to break one statement and iterate to the next statement.
JavaScript Return Statement:
The return statement in JavaScript is used to end the execution of a
function and return a value to the caller. It is used to control function
behaviour and optimise code execution.
try...catch...finally:
The try statement defines the code block to run (to try).
The catch statement defines a code block to handle any error.
The finally statement defines a code block to run regardless of the
result.
The throw statement defines a custom error.
Both catch and finally are optional, but you must use one of them.
Syntax:
try {
tryCode- Code block to run
}
catch(err){
catchCode- Code block to handle errors
}
finally {
finallyCode - Code block to be executed regardless of the try result
}
Example:
<p id="demo"></p>
<script>
try {
adddlert("Welcome guest!");
}
catch(err) {
[Link]("demo").innerHTML = [Link];
}
</script>
Throw:
The throw statement allows you to create a custom error.
The throw statement throws (generates) an error.
The technical term for this is:
The throw statement throws an exception.
Syntax:
throw expression;
Example:
try {
if(x == "") throw "is Empty";
if(isNaN(x)) throw "not a number";
if(x > 10) throw "too high";
if(x < 5) throw "too low";
}
catch(err) {
[Link] = "Input " + err;
JavaScript Loops
Loops in JavaScript are used to reduce repetitive tasks by repeatedly
executing a block of code as long as a specified condition is true. This
makes code more concise and efficient.
The different types of loops available in javascript:
1. JavaScript for Loop:
for loop is a control flow statement that allows code to be executed
repeatedly based on a condition. It consists of three parts:
initialization, condition, and increment/decrement.
Syntax:
for (initialization; condition; increment/decrement) {
// Code to execute
}
Example:
for (let i = 1; i <= 3; i++) {
[Link]("Count:", i);
}
2. JavaScript while Loop:
It is an entry condition looping structure.
The while loop executes a block of code as long as a specified
condition is true. In JavaScript, this loop evaluates the condition
before each iteration and continues running as long as the condition
remains true.
Syntax:
while(condition){
}
Example:
let i = 0;
while (i < 3) {
[Link]("Number:", i);
i++;
}
3. JavaScript do-while Loop:
A Do-While loop is another type of loop in JavaScript that is similar
to the while loop, but with one key difference: the do-while loop
guarantees that the block of code inside the loop will be executed at
least once, regardless of whether the condition is
initially true or false .
Entry Controlled loops: In this type of loop, the test condition is
tested before entering the loop body. For Loop and While
Loops are entry-controlled loops.
Exit Controlled Loops: In this type of loop the test condition is
tested or evaluated at the end of the loop body. Therefore, the
loop body will execute at least once, irrespective of whether the
test condition is true or false. the do-while loop is exit controlled
loop.
It is an exit condition looping structure.
Syntax:
do{
code to be executed
}
while();
Example 1:
let i = 0;
do {
[Link]("Iteration:", i);
i++;
} while (i < 3);
Example:
let test = 1;
do {
[Link](test);
} while(test<1)
while(test<1){
[Link](test);
}
JavaScript For In Loop
The JavaScript for…in loop iterates over the properties of an object.
It allows you to access each key or property name of an object.
Syntax
for (key in object) { // Code}
Example:
const car = {
make: "Toyota",
model: "Corolla",
year: 2020
};
for (let key in car) {
[Link](`${key}: ${car[key]}`);
}
JavaScript for…of Loop
The JavaScript for…of loop is a modern, iteration statement.
Works for iterable objects such as arrays, strings, maps, sets, and
more.
It is better choice for traversing items of iterables compared to
traditional for and for in loops, especially when we have break
or continue statements. If we just want to perform an operation
on all items, we prefer forEach()
1. Iterating Over an Array using for…of
Example:
const a = [ 1, 2, 3, 4, 5 ];
for (const item of a) {
[Link](item);
}
2. Iterating Over a String using for…of
Example:
const str = "Hello";
Example:
const m = new Map([
["name", "Akash"],
["age", 25],
["city", "Noida"]
]);
Example:
let person = {
name: "Akash",
age: 25,
city: "Noida"
};
// Add Properties
[Link] = "John";
[Link] = "Doe";
[Link] = 50;
[Link] = "blue";
Accessing Object Properties:
You can access object properties in two ways:
[Link].
[Link]["propertyName"].
JavaScript Object Methods:
Object methods are actions that can be performed on objects.
A method is a function definition stored as a property value.
Example:
[Link] = function() {
return ([Link] + " " + [Link]).toUpperCase();
};
Basic Operations on JavaScript Objects:
1. Accessing Object Properties:
You can access an object’s properties using either dot notation or bracket
notation
Example:
let obj = { name: "Sourav", age: 23 };
// Using Dot Notation
[Link]([Link]);
// Using Bracket Notation
[Link](obj["age"]);
2. Modifying Object Properties:
Properties in an object can be modified by reassigning their values.
Example:
let obj = { name: "Sourav", age: 22 };
[Link](obj);
[Link] = 23;
[Link](obj);
3. Adding Properties to an Object:
You can dynamically add new properties to an object using dot or bracket
notation.
Example:
let obj = { model: "Tesla" };
[Link] = "Red";
[Link](obj);
[Link] Properties from an Object
The delete operator removes properties from an object.
Example:
let obj = { model: "Tesla", color: "Red" };
delete [Link];
[Link](obj);
JavaScript Arrays
In JavaScript, an array is an ordered list of values. Each value is called an
element, and each element has a numeric position in the array, known as its
index. Arrays in JavaScript are zero-indexed, meaning the first element is at
index 0, the second at index 1, and so on.
1. Create Array using Literal:
// Creating an Empty Array
let a = [];
[Link](a);
// Creating an Array and Initializing with Values
let b = [10, 20, 30];
[Link](b);
2. Create using new Keyword (Constructor):
The “Array Constructor” refers to a method of creating arrays by invoking the
Array constructor function.
Example:
// Creating and Initializing an array with values
let a = new Array(10, 20, 30);
[Link](a);
Basic Operations on JavaScript Arrays:
1. Accessing Elements of an Array:
Any element in the array can be accessed using the index number. The index in
the arrays starts with 0.
Example:
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
[Link](delete [Link]);
[Link](emp);
5. JavaScript Array concat() Method:
The concat() method is used to concatenate two or more arrays and it gives the
merged array.
Example:
let a1 = [11, 12, 13];
let a2 = [14, 15, 16];
let a3 = [17, 18, 19];
let newArr = [Link](a2, a3);
[Link](newArr);
6. JavaScript Array flat() Method:
The flat() method is used to flatten the array i.e. it merges all the given array
and reduces all the nesting present in it.
Example:
const a1 = [['1', '2'], ['3', '4', '5',['6'], '7']];
const a2 = [Link](Infinity);
[Link](a2);
The code defines a multilevel (nested) array ‘a1’ and uses the
flat(Infinity) method to flatten it completely into a single-level array.
7. JavaScript [Link]() Method:
The push() method is used to add an element at the end of an Array. As arrays in
JavaScript are mutable objects, we can easily add or remove elements from the
Array.
Example:
let a = [10, 20, 30, 40, 50];
[Link](60);
[Link](70, 80, 90);
[Link](a);
8. JavaScript [Link]() Method:
The unshift() method is used to add elements to the front of an Array.
Example:
let a = [20, 30, 40];
[Link](10, 20);
[Link](a);
9. JavaScript [Link]() Method:
The pop() method is used to remove elements from the end of an array.
Example:
let a = [20, 30, 40, 50];
[Link]();
[Link](a);
10. JavaScript [Link]() Method:
The shift() method is used to remove elements from the beginning of an array.
Example:
let a = [20, 30, 40, 50];
[Link]();
[Link](a);
11. JavaScript [Link]() Method
The splice() method is used to Insert and Remove elements in between the
Array.
Example:
let a = [20, 30, 40, 50];
[Link](1, 3);
[Link](1, 0, 3, 4, 5);
[Link](a);
The first [Link](1, 3) removes 3 elements (30, 40, 50) starting at index 1.
The array becomes [20].
The second [Link](1, 0, 3, 4, 5) inserts 3, 4, and 5 at index 1 without
removing anything. The array becomes [20, 3, 4, 5].
12. JavaScript [Link]() Method:
The slice() method returns a new array containing a portion of the original array,
based on the start and end index provided as arguments.
Example:
const a = [1, 2, 3, 4, 5];
const res = [Link](1, 4);
[Link](res);
[Link](a)
13. JavaScript Array some() Method:
The some() method checks whether at least one of the elements of the array
satisfies the condition checked by the argument function.
Example:
const a = [1, 2, 3, 4, 5];
let res = [Link]((val) => val > 4);
[Link](res);
In this example
The some() method checks if at least one element in the array satisfies
the provided condition.
(val) => val > 4: The condition checks if any element in the array is
greater than 4.
The method stops as soon as it finds the first matching element, making it
efficient for large arrays.
14. JavaScript Array map() Method:
The map() method creates an array by calling a specific function on each
element present in the parent array. It is a non-mutating method.
Example:
function geeks() {
return [Link]([Link]);
}
[Link](sub);
In this example
The output will be an array of the same length as a, but each element will
be the result of applying [Link]([Link]).
The filter() method in JavaScript creates a new array with all elements that pass
the test implemented by the provided function. It does not modify the original
array.
Example:
let a1 = [1, 2, 3, 4, 5]
In this example
The filter() method is used to create a new array (a2) that contains all
elements of the original array that satisfy the condition (num > 1).
The filter() method does not modify the original array. It returns a new
array, leaving the original one unchanged.
The reduce() method is used to reduce the array to a single value and executes a
provided function for each value of the array (from left to right) and the return
value of the function is stored in an accumulator.
Example:
}
[Link](sub);
In this example
The reduce() method iterates over the array ‘a’ and applies the geeks
function, which subtracts each element (num) from the running total (tot).
For the array [88, 50, 25, 10], the calculation proceeds as: 88 – 50 – 25 –
10.
Example:
[Link]();
[Link](a);
In this example
The reverse() method reverses the order of elements in the array arr in
place, modifying the original array.
The values() method returns a new Array Iterator object that contains the values
for each index in the array.
[Link](value);
}
In this example:
The values() method returns an iterator object that allows iterating over
the values of the ‘a’ array.
The for…of loop is used to iterate over the iterator and log each fruit
(“Apple”, “Banana”, “Cherry”) to the console.
Example:
// Input array contain some elements.
let array = [10, 20, 30, 40, 50];
// Function (return element > 10).
let found = [Link](function (element) {
return element > 20;
});
// Printing desired values.
[Link](found);
Array fill() Method:
The Array fill() method is used to fill the array with a given static value. The
value can be used to fill the entire array or it can be used to fill a part of the
array.
Example:
// JavaScript code for fill() function
let arr = [1, 23, 46, 58];
// Here value = 87, start index = 1 and
// and last index = 3
[Link](87, 1, 3);
[Link](arr);
Array forEach() Method:
The Array forEach() method calls the provided function once for each element
of the array. The provided function may perform any kind of operation on the
elements of the given array.
Example:
// Original array
const items = [1, 29, 47];
const copy = [];
[Link](function (item) {
[Link](item * item);
});
[Link](copy);
Array sort() Method:
The Array sort() method is used to sort the array. An array can be of any type
i.e. string, numbers, characters, etc.
Example:
// Original array
let numbers = [88, 50, 25, 10];
// Performing sort method
let sub = [Link](geeks);
function geeks(a, b) {
return a - b;
}
[Link](sub);
Array concat() Method:
The Array concat() method is used to merge two or more arrays together. This
function does not alter the original arrays passed as arguments.
Example:
// JavaScript code for concat() function
let num1 = [11, 12, 13],
num2 = [14, 15, 16],
num3 = [17, 18, 19];
[Link]([Link](num2, num3));
Array includes() Method:
The Array includes() method is used to know whether a particular element is
present in the array or not and accordingly, it returns true or false i.e, if the
element is present, then it returns true otherwise false
// Taking input as an array A
// having some elements.
let A = [1, 2, 3, 4, 5];
// Include() function is called to
// test whether the searching element
// is present in given array or not.
let a = [Link](2);
// Printing result of function.
[Link](a);
Array reverse() Method:
The Array reverse() method is used for in-place reversal of the array. The first
element of the array becomes the last element and vice versa.
Example:
//Original Array
let arr = [34, 234, 567, 4];
[Link]("Original array: " + arr);
//Reversed array
let new_arr = [Link]();
// Display the result
[Link]("Newly reversed array: " + new_arr);
Important Array Methods of JavaScript
JavaScript arrays are powerful tools for managing collections of data.
They come with a wide range of built-in methods that allow developers to
manipulate, transform, and interact with array elements.
[Link] indexOf() Method
The indexOf() method is used to find the index of a particular element in
an array.
Example:
let a = ["Hello", "GFG", "JS"];
[Link]([Link]('GFG'));
[Link] includes() Method:
The includes() method is used to check whether the array contains the specified
element or not.
Example:
let a = ["Hello", "GFG", "JS"];
[Link]([Link]("GFG"));
[Link]([Link]("React"));
Output
true
false
[Link] concat() Method:
The concat() method is used to concat or basically join two different arrays from
end to end.
Example:
let a1 = ["Hello","GFG", "Js"];
let a2 = ["React"];
let new = [Link](a2);
[Link](a1);
[Link](a2);
[Link](new);
// The concat() method merges a1 and a2 into a new array without modifying the
original arrays.//
[Link] forEach() Method:
The forEach() works as a loop over an array where for every element the function
just runs once only.
Example:
let a = ["Hello", "GFG", "JS"];
[Link](function (element) {
[Link](element)
});
Output
Hello
GeeksforGeeks
JavaScript
//The forEach() method iterates over each element in the array a and executes the
provided function for each element.//
[Link] sort() Method:
The sort() method sorts the elements of an array in alphabetical order in
ascending order.
Example:
let a = ["Hello", "GFG", "JS"];
[Link](a);
[Link]();
[Link](a);
Output
[ 'Hello', 'GeeksforGeeks', 'JavaScript' ]
[ 'GeeksforGeeks', 'Hello', 'JavaScript' ]
[Link] map() method:
The map() method iterates over an array, transforms the array according to user-
specified conditions and returns a new array.
Example:
let a1 = [1, 2, 3, 4, 5];
[Link](a1);
let a2 = [Link](function (elem) {
return elem * 5;
});
[Link](a2);
Output
[ 1, 2, 3, 4, 5 ]
[ 5, 10, 15, 20, 25 ]
7. JavaScript reduce() Method:
The reduce() method uses a reducer function that reduces the results into a single
output.
Example:
let a1 = [1, 2, 3, 4, 5];
[Link](a1);
let sum = [Link](
function (acc, elem) {
return acc + elem;
});
[Link](sum);
Output
[ 1, 2, 3, 4, 5 ]
15
8. JavaScript filter() Method:
The filter() method is used to filter out the contents, as per the user-specified
condition, in the form of a new array.
Example:
let a1 = [1, 2, 3, 4, 5];
[Link](a1);
let a2 = [Link](function (elem) {
return elem % 2 === 0;
});
[Link](a2);
Output
[ 1, 2, 3, 4, 5 ]
[ 2, 4 ]
9. JavaScript find() & findIndex() Method
The find() method finds out the first value which passes the user-specified
conditions and findIndex() method finds out the first index value which passes
the user-specified conditions.
Example:
let a = [1, 2, 3, 4, 5];
let find = [Link](function (elem) {
return elem > 4
});
[Link](find);
let val = [Link](function (elem) {
return elem >= 4
});
[Link](val);
Output
5
3
[Link] slice() & splice() Method:
The slice() selects the specified number of elements without affecting the original
array elements whereas splice() removes the selected elements from the original
array itself.
Example:
let a = [1, 2, 3, 4, 5];
let slice = [Link](0, 2);
[Link]("Slice Array: " + slice);
[Link]("Original Array: " + a);
let splice = [Link](0, 2);
[Link]("Slice Array: " + splice);
[Link]("Original Array: " + a);
Output
Slice Array: 1,2
Original Array: 1,2,3,4,5
Slice Array: 1,2
Original Array: 3,4,5
[Link] some() and every() Method:
The some() method checks the user-specified conditions on some elements of an
array (i.e. it checks for a few elements only), whereas every() method checks the
user-specified conditions on every element of an array then returns the results in
true or false.
Example:
let a = [1, 2, 3, 4, 5];
let n1 = [Link](
function (elem) {
return elem > 0
});
let n2 = [Link](
function (elem) {
return elem < 0
});
[Link](n1);
[Link](n2);
Output
true
false
13. Javascript forEach() method:
The forEach() method in JavaScript is used to execute a provided function once
for each element in an array.
let n = [1, 2, 3, 4, 5];
[Link](function(elem, index) {
[Link](elem);
});
Output
1
2
3
4
5
14. JavaScript Array reverse() Method:
The reverse() method is used to reverse the order of the elements in an array.
let a = [1, 2, 3, 4, 5];
[Link]();
[Link](a);
Output
[ 5, 4, 3, 2, 1 ]
Output
JAVASCRIPT
javascript
7. String Search in JavaScript:
Find the first index of a substring within a string using indexOf() method.
let s1 = 'def abc abc';
let i = [Link]('abc');
[Link](i);
Output
4
8. String Replace in JavaScript:
Replace occurrences of a substring with another using replace() method.
let s1 = 'Learn HTML at GfG';
let s2 = [Link]('HTML', 'JavaScript');
[Link](s2);
Output
Learn JavaScript at GfG
9. Trimming Whitespace from String:
Remove leading and trailing whitespaces using trim() method.
let s1 = ' Learn JavaScript ';
let s2 = [Link]();
[Link](s2);
Output
Learn JavaScript
10. Access Characters from String
Access individual characters in a string using bracket notation and charAt()
method.
let s1 = 'Learn JavaScript';
let s2 = s1[6];
[Link](s2);
s2 = [Link](6);
[Link](s2);
Output
J
J
11. String Comparison in JavaScript
There are some inbuilt methods that can be used to compare strings such as the
equality operator and another like localeCompare() method.
let str1 = "John";
let str2 = new String("John");
[Link](str1 == str2);
[Link]([Link](str2));
Output
true
0
12. Passing JavaScript String as Objects
We can create a JavaScript string using the new keyword.
const str = new String("GeeksforGeeks");
[Link](str);
Output
[String: 'GeeksforGeeks']
JavaScript Numbers
JavaScript numbers are primitive data types and, unlike other programming
languages, you don’t need to declare different numeric types like int, float, etc.
JavaScript numbers are always stored in double-precision 64-bit binary format
IEEE 754. This format stores numbers in 64 bits:
0-51 bits store the value (fraction)
52-62 bits store the exponent
63rd bit stores the sign
Numeric Types in JavaScript:
In JavaScript, numbers play an important role, and understanding their behavior
is essential for effective programming. Let’s explore the various aspects of
numeric types in JavaScript.
Number Literals:
The types of number literals You can use decimal, binary, octal, and
hexadecimal.
1. Decimal Numbers:
JavaScript Numbers does not have different types of numbers(ex: int, float,
long, short) which other programming languages do. It has only one type of
number and it can hold both with or without decimal values.
Example:
let a=33;
let b=3.3;
[Link](a);
[Link](b);
Output
33
3.3
2. Octal Number:
If the number starts with 0 and the following number is smaller than 8. It will be
parsed as an Octal Number.
let x = 0562;
[Link](x);
Output
370
3. Binary Numbers:
They start with 0b or 0B followed by 0’s and 1’s.
let x = 0b11;
let y = 0B0111;
[Link](x);
[Link](y);
Output
3
7
4. Hexadecimal Numbers:
They start with 0x or 0X followed by any digit belonging
(0123456789ABCDEF) .
let x = 0xfff;
[Link](x);
Output
4095
Number Coercion in JavaScript
In JavaScript, coercion refers to the automatic or implicit conversion of
values from one data type to another.
1. Undefined to NaN:
When you perform an operation involving undefined, JavaScript
returns NaN (Not-a-Number).
const result = undefined + 10;
[Link](result); // NaN
Output
NaN
2. Null to 0:
The value null is coerced to 0 when used in arithmetic operations.
const total = null + 5;
[Link](total); // 5
Output
5
3. Boolean to Number:
Boolean values (true and false) are converted to
numbers: 1 for true and 0 for false.
const num1 = true + 10;
const num2 = false + 10;
[Link](num1);
[Link](num2);
Output
11
10
4. String to Number
When performing arithmetic operations, JavaScript converts strings to numbers.
If the string cannot be parsed as a valid number, it returns NaN.
const str1 = '42';
const str2 = 'hello';
const numFromString1 = Number(str1);
const numFromString2 = Number(str2);
[Link](numFromString1);
[Link](numFromString2);
Output
42
NaN
5. BigInts and Symbols
Attempting to coerce Symbol values to numbers results in a TypeError.
const symbolValue = Symbol('mySymbol');
Example program:
Palindrome:
function palindromeCheck(num) {
let numStr = [Link]();
let result = [Link]('').reverse().join('');
return numStr === result;
}
[Link](palindromeCheck(121)); // true
[Link](palindromeCheck(123)); // false
Output
true
false
Check a Number is Prime or Not
let n = 17;
let isPrime = true;
if (n <= 1) {
isPrime = false;
} else {
for (let i = 2; i < n; i++) {
if (n % i === 0) {
isPrime = false;
break;
}
}
}
[Link](isPrime ? `${n} is a prime number.` : `${n} is not a prime
number.`);