JS

 

JavaScript is the world's most popular programming language.JavaScript is the programming language of the Web.JavaScript is easy to learn. JavaScript is a high-level, versatile, and widely-used programming language primarily known for its role in web development. It is often referred to as the "language of the web" because it is a core technology for building interactive and dynamic web pages. JavaScript allows you to add functionality, interactivity, and behavior to websites, making them more user-friendly and engaging. Here are some key characteristics and uses of JavaScript:

1.    Scripting Language: JavaScript is a scripting language, which means it is interpreted by the browser or runtime environment (like Node.js) on the client-side. This allows for dynamic behavior on web pages.

2.    Client-Side Programming: JavaScript is primarily used on the client side (in web browsers) to manipulate the Document Object Model (DOM), handle user interactions, validate forms, and make asynchronous requests to web servers.

3.    Cross-Platform: JavaScript can run on various platforms, including web browsers, servers (using Node.js), and mobile app development (using frameworks like React Native or NativeScript).

 

 <html>

   <body>  

      <script>        

            document.write("Hello World!")       

      </script>     

   </body>

</html>

===========================================

<html>

<body>

<button type="button"

onclick="document.getElementById('demo').innerHTML = Date()">

Click me to display Date and Time.</button>

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

</html>   

<html>

<body>

<p id="demo">JavaScript can change HTML content.</p>

 

<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello JavaScript!"'>Click Me!</button>

 

</body>

</html>

 

 

<html>

<body><p>Creating a JavaScript Variable</p>

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

<script>

var c="Fiat";

document.getElementById("demo").innerHTML=c;

</script></body></html>

 

 

<html><body>

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

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

<script>

var x=5;

var y=6;

document.getElementById("demo").innerHTML=x+y;

document.getElementById("demo1").innerHTML=x*y;

</script>

</body></html>

===============================

 <html><body>

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

<script>

var c="Volvo XC60";

var d='Volvo XC60';

var a="it's alright";

var b="He is called 'johnny'";

var e='He is called "johnny"';

document.getElementById("demo").innerHTML=c +"<br>" +d +"<br>" +a + "<br>" +b + "<br>" +e;

</script></body></html>

===============

 Function

1.builtin functions

2.user defined functions

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

 

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

JavaScript Function Syntax

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().

 

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

 

The parentheses may include parameter names separated by commas:

(parameter1, parameter2, ...)

 

The code to be executed, by the function, is placed inside curly brackets: {}

 

function name(parameter1, parameter2, parameter3) {

  // code to be executed

}

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

 

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

 

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

=============================

 <html>

<body>

 

<h1>JavaScript Functions</h1>

 

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

 

<script>

let x = myFunction(4, 3);

document.getElementById("demo").innerHTML = x;

 

function myFunction(a, b) {

  return a * b;

}

</script>

 

</body>

</html>

===================================================================

<html>

<body>

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

<script>

document.getElementById("demo").innerHTML = 5 + 6;

</script></body></html>

Variables

Variables are Containers for Storing Data

JavaScript Variables can be declared in 4 ways:

 

Automatically

Using var

Using let

Using const

 

 <html>

<body>

<h1>JavaScript Variables</h1>

 

<p>In this example, x, y, and z are undeclared.</p>

<p>They are automatically declared when first used.</p>

 

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

 

<script>

x = 5;

y = 6;

z = x + y;

document.getElementById("demo").innerHTML =

"The value of z is: " + z;

</script>

 

</body>

</html>

 <html>

<body>

<h1>JavaScript Variables</h1>

 

<p>In this example, x, y, and z are variables.</p>

 

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

 

<script>

var x = 5;

var y = 6;

var z = x + y;

document.getElementById("demo").innerHTML =

"The value of z is: " + z;

</script>

 

</body>

</html>

<html>

<body>

<h1>JavaScript Variables</h1>

 

<p>In this example, x, y, and z are variables.</p>

 

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

<script>

let x = 5;

let y = 6;

let z = x + y;

document.getElementById("demo").innerHTML =

"The value of z is: " + z;

</script></body>

</html>

<html><body>

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

<script>

const x = 5;

const y = 6;

const z = x + y;

document.getElementById("demo").innerHTML =

"The value of z is: " + z;

</script></body>

</html>

 

<html>

<body>

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

<script>

let x = 5;

let y = 2;

let z = x * y;

document.getElementById("demo").innerHTML = z;

</script></body></html>

JavaScript has 8 Datatypes

1. String

2. Number

3. Bigint

4. Boolean

5. Undefined

6. Null

7. Symbol

8. Object

<html>

<body>

 

<h2>JavaScript</h2>

 

<p>When adding a number and a string, JavaScript will treat the number as a string.</p>

 

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

 

<script>

let x = 16 + "Volvo";

document.getElementById("demo").innerHTML = x;

</script>

 

</body>

</html>

JavaScript Arrays

JavaScript arrays are written with square brackets.

Array items are separated by commas.

 

<html>

<body>

<h2>JavaScript Arrays</h2>

<p>Array indexes are zero-based, which means the first item is [0].</p>

 

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

 

<script>

const cars = ["Jannath","anu","sera"];

 

document.getElementById("demo").innerHTML = cars[0];

</script></body></html>

<html>

<body>

 

<h1>JavaScript Comparison</h1>

<h2>The == Operator</h2>

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

<script>

let x = 5;

document.getElementById("demo").innerHTML = (x == 8);

</script>

 

</body>

</html>

<html>

<body>

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

 

<script>

let x = 6;

let y = 3;

 

document.getElementById("demo").innerHTML =

(x < 10 && y > 1) + "<br>" +

(x < 10 && y < 1);

</script>

 

</body>

</html>

<html>

<body>

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

 

<script>

let x = 6;

let y = 3;

 

document.getElementById("demo").innerHTML =

!(x === y) + "<br>" +

!(x > y);

</script>

 

</body>

</html>

<html>

<body>

 

 

<input id="age" value="18" />

 

<button onclick="myFunction()">Try it</button>

 

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

 

<script>

function myFunction() {

  let age = document.getElementById("age").value;

  let v = (age < 18) ? "Too young":"Old enough";

  document.getElementById("demo").innerHTML = v + " to vote.";

}

</script>

 

</body>

</html>

<html>

<body>

 

<h1>JavaScript Bitwise AND</h1>

<h2>The & Operator</h2>

 

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

 

<script>

document.getElementById("demo").innerHTML = 5 & 1;

</script>

 

</body>

</html>

<html>

<body>

 

<h2>The delete Operator</h2>

 

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

 

<script>

const person = {

  firstname:"Joy",

  lastname:"tom",

  age:50,

  eyecolor:"blue"

};

 

delete person.age;

 

document.getElementById("demo").innerHTML =

person.firstname + " is " + person.age + " years old.";

</script>

 

</body>

</html>

Operator precedence

Operator precedence describes the order in which operations are performed in an arithmetic expression.

Multiplication (*) and division (/) have higher precedence than addition (+) and subtraction (-).

<html>

<body>

<h2>Operator Precedence</h2>

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

 

<script>

document.getElementById("demo").innerHTML = 100 + 50 * 3;

</script>

 

</body>

</html>

Control Structures

If

if (condition) {

  //  block of code to be executed if the condition is true

}

<html>

<body>

 

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

 

<script>

if (new Date().getHours() < 18) {

  document.getElementById("demo").innerHTML = "Good day!";

}

</script>

 

</body>

</html>

If else

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

}

<html>

<body>

 

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

 

<script>

const hour = new Date().getHours();

let greeting;

 

if (hour < 18) {

  greeting = "Good day";

} else {

  greeting = "Good evening";

}

 

document.getElementById("demo").innerHTML = greeting;

</script></body></html>

 

else if              

          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

}

<html><body>

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

const time = new Date().getHours();

let greeting;

if (time < 10) {

  greeting = "Good morning";

} else if (time < 20) {

  greeting = "Good day";

} else {

  greeting = "Good evening";

}

document.getElementById("demo").innerHTML = greeting;

</script></body></html>

switch(expression) {

  case x:

    // code block

    break;

  case y:

    // code block

    break;

  default:

    // code block

}

<html><body>

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

 

<script>

let day;

switch (new Date().getDay()) {

  case 0:

    day = "Sunday";

    break;

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

}

document.getElementById("demo").innerHTML = "Today is " + day;

</script>/body></html>

 

Loop

for (expression 1; expression 2; expression 3) {

  // code block to be executed

}

<html>

<body>

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

 

<script>

let text = "";

 

for (let i = 0; i < 5; i++) {

  text += "The number is " + i + "<br>";

}

 

document.getElementById("demo").innerHTML = text;

</script>

 

</body>

</html>

<html>

<body>

<script> 

for (i=1; i<=10; i++) 

{ 

document.write(i + "<br/>") 

} 

</script> 

</body>

</html>

while (condition) 

{ 

    code to be executed 

}

<html>

<body>

<script> 

var i=10; 

while (i<=20) 

{ 

document.write(i + "<br/>"); 

i++; 

} 

</script> 

</body>

</html>

do{ 

    code to be executed 

}while (condition);

<html>

<body>

<script> 

var i=21; 

do{ 

document.write(i + "<br/>"); 

i++; 

}while (i<=25); 

</script> 

</body>

</html>

<html>

<head>

   

</head>

<body>

   

 

    <table border="1">

        <tbody>

            <!-- Outer loop for rows -->

            <script>

                for (var i = 1; i <= 5; i++) {

                    document.write("<tr>");

                   

                    // Nested loop for columns

                    for (var j = 1; j <= 5; j++) {

                        document.write("<td>Row " + i + ", Column " + j + "</td>");

                    }

                   

                    document.write("</tr>");

                }

            </script>

        </tbody>

    </table>

</body>

</html>

<html>

<head>

   

</head>

<body>

    <h1>Multiplication Table</h1>

    <table border="1">

        <tr>

            <th></th>

            <!-- Create column headers for the table -->

            <script>

                for (let i = 1; i <= 10; i++) {

                    document.write(`<th>${i}</th>`);

                }

            </script>

        </tr>

        <!-- Use nested for loops to create rows and fill in multiplication values -->

        <script>

            for (let i = 1; i <= 10; i++) {

                document.write("<tr>");

                document.write(`<th>${i}</th>`);

 

                for (let j = 1; j <= 10; j++) {

                    document.write(`<td>${i * j}</td>`);

                }

 

                document.write("</tr>");

            }

        </script>

    </table>

</body>

</html>

Break

The break statement "jumps out" of a loop.

<html>

<body>

 

<h2>JavaScript Loops</h2>

 

<p>A loop with a <b>break</b> statement.</p>

 

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

 

<script>

let text = "";

for (let i = 0; i < 10; i++) {

  if (i === 3) { break; }

  text += "The number is " + i + "<br>";

}

 

document.getElementById("demo").innerHTML = text;

</script>

 

</body>

</html>

Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

<html>

<body>

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

 

<script>

let text = "";

for (let i = 0; i < 10; i++) {

  if (i == 3) { continue; }

  text += "The number is " + i + "<br>";

}

document.getElementById("demo").innerHTML = text;

</script>

 

</body>

</html>

Function : A JavaScript function is a block of code designed to perform a particular task.A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().

 

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

 

The parentheses may include parameter names separated by commas:

(parameter1, parameter2, ...)

 

The code to be executed, by the function, is placed inside curly brackets: {}

 

function name(parameter1, parameter2, parameter3) {

  // code to be executed

}

<html><body>

 

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

 

<script>

let x = myFunction(4, 3);

document.getElementById("demo").innerHTML = x;

 

function myFunction(a, b) {

  return a * b;

}

</script>

 

</body>

</html>

Advantage of JavaScript function

There are mainly two advantages of JavaScript functions.

 

Code reusability: We can call a function several times so it save coding.

Less coding: It makes our program compact. We don’t need to write many lines of code each time to perform a common task.

<html><body>

<script>  

function msg(){ 

alert("hello! this is message"); 

} 

</script>

<form> 

<input type="button" onclick="msg()" value="call function"/>  

</form>  </body></html>

<html>

<body>

<script> 

function getcube(number){ 

alert(number*number*number); 

} 

</script> 

<form> 

<input type="button" value="click" onclick="getcube(4)"/> 

</form> 

</body>

</html>

<html>

<body>

<script> 

function getInfo(){ 

return "hello How r u?"; 

} 

</script> 

<script> 

document.write(getInfo()); 

</script> 

</body>

</html>

<html>

<body>

 

<script>

var pow=new Function("num1","num2","return Math.pow(num1,num2)");

document.writeln(pow(2,3));

</script>

 

</body>

</html>

<html>

<body>

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

 

<script>

function toCelsius(f) {

  return (5/9) * (f-32);

}

 

let value = toCelsius(77);

document.getElementById("demo").innerHTML = value;

</script>

 

</body>

</html>

<html>

<head>

    <title>Simple Function Example</title>

</head>

<body>

    <h1>Calculate the Sum of Two Numbers</h1>

 

    <input type="text" id="num1" placeholder="Enter a number">

    <input type="text" id="num2" placeholder="Enter another number">

    <button onclick="calculateSum()">Calculate</button>

 

    <p id="result"></p>

 

    <script>

        function calculateSum() {

            // Get the values entered by the user

            var num1 = parseFloat(document.getElementById("num1").value);

            var num2 = parseFloat(document.getElementById("num2").value);

 

            // Check if the input is valid

            if (!isNaN(num1) && !isNaN(num2)) {

                // Calculate the sum

                var sum = num1 + num2;

 

                // Display the result

                document.getElementById("result").innerHTML = "Sum: " + sum;

            } else {

                // Handle invalid input

                document.getElementById("result").innerHTML = "Please enter valid numbers.";

            }

        }

    </script>

</body>

</html>

<html>

<body>

    <h1 id="demo">Hello, World!</h1>

    <button onclick="changeText()">Click me</button>

 

    <script>

        function changeText() {

            // Get the element by its ID

            var element = document.getElementById("demo");

 

            // Change the text

            element.innerHTML = "Text has been changed!";

        }

    </script>

</body>

</html>

<html>

<head>

    <title>Function with Parameter</title>

</head>

<body>

    <h1>Function with Parameter Example</h1>

 

    <p>Click the button to display a message:</p>

 

    <button onclick="showMessage('Hello, World!')">Click Me</button>

 

    <p id="output"></p>

 

    <script>

        // JavaScript function with a parameter

        function showMessage(message) {

            // Display the message in a paragraph with id "output"

            document.getElementById("output").textContent = message;

        }

    </script>

</body>

</html>

<html>

<head>

    <title>Integer Parameter Function</title>

</head>

<body>

 

<h1>Integer Parameter Function Example</h1>

 

<p>Enter an integer:</p>

<input type="number" id="inputNumber">

<button onclick="doubleInteger()">Double</button>

 

<p>Result: <span id="result"></span></p>

 

<script>

function doubleInteger() {

    // Get the input value as a string

    var inputElement = document.getElementById("inputNumber");

    var inputValue = inputElement.value;

 

    // Parse the input string as an integer

    var number = parseInt(inputValue);

 

    // Check if the input is a valid integer

    if (!isNaN(number)) {

        // Double the integer

        var result = number * 2;

 

        // Display the result

        document.getElementById("result").textContent = result;

    } else {

        // Display an error message for invalid input

        document.getElementById("result").textContent = "Invalid input. Please enter an integer.";

    }

}

</script>

 

</body>

</html>

Popup Boxes

Alert Box

An alert box is often used if you want to make sure information comes through to the user.

Confirm Box

A confirm box is often used if you want the user to verify or accept something.

Prompt Box

A prompt box is often used if you want the user to input a value before entering a page.

<html>

<body>

<h2>JavaScript Alert For You</h2>

 

<button onclick="myFunction()">Try it</button>

 

<script>

function myFunction() {

  alert("I am an alert box from techzmatrix!");

}

</script></body></html>

<html>

 

<body>

 

 

 

<h2>JavaScript Confirm Box</h2>

 

 

 

 

 

<button onclick="myFunction()">Try it</button>

 

 

 

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

 

 

 

<script>

 

function myFunction() {

 

  var txt;

 

  if (confirm("Press a button!")) {

 

    txt = "You pressed OK!";

 

  } else {

 

    txt = "You pressed Cancel!";

 

  }

 

  document.getElementById("demo").innerHTML = txt;

 

}

 

</script>

 

 

 

</body>

 

</html>

<html>

 

<body>

 

 

 

<h2>JavaScript Prompt</h2>

 

 

 

<button onclick="myFunction()">Try it</button>

 

 

 

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

 

 

 

<script>

 

function myFunction() {

 

  var txt;

 

  var person = prompt("Please enter your name:", "VEDHA");

 

  if (person == null || person == "") {

 

    txt = "User cancelled the prompt.";

 

  } else {

 

    txt = "Hello " + person + "! How are you today?";

 

  }

 

  document.getElementById("demo").innerHTML = txt;

 

}

 

</script>

 

 

 

</body>

 

</html>

<html>

<body>

<font color="blue"><h1 align="center">Outer function() with single inner function()</h1></font>

<script>

function triangleHypotenuse(base,height)

{

function square(side){

return side*side;

}

return Math.sqrt(square(base)+square(height));

}

document.write("Hypotenuse of triangle is :"+triangleHypotenuse(3,4));

</script>

</body>

</html>

Rest Parameter in JavaScript :  -

The rest parameter is an improved way to handle function parameters, allowing us to more easily handle various inputs as parameters in a function. The rest parameter syntax allows us to represent an indefinite number of arguments as an array. The rest parameter (...) allows a function to treat an indefinite number of arguments as an array

 Rest parameter is an important feature provided by JavaScript.

 syntax

function functionname(...parameters)

{

statement;

}

 

 <html>

<body>

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

 

<script>

function findMax() {

  let max =0;

  for(let i = 0; i < arguments.length; i++) {

    if (arguments[i] > max) {

      max = arguments[i];

    }

  }

  return max;

}

document.getElementById("demo").innerHTML = findMax(40, 5, 6,30,55);

</script>

</body>

</html>

<html>

<head>

<script>

   function myFunc(name1, name2, ...namen)

   {

     document.write("First name: " +name1, "<br>");

     document.write("Second name: " +name2, "<br>");

     for(let i = 0; i < namen.length; i++)

     {

       document.write("Other name: " +namen[i], "<br>");

     }

    }

    myFunc("Jannath", "hana", "liaqa" );

</script>

</head>

<body>

</body>

</html>

 Anonymous Functions in JavaScript : -                                                                                                                                                                 In JavaScript, it is also possible to create anonymous functions. An anonymous function in JavaScript is a type of function that doesn’t have a name after the function keyword.The function above is actually an anonymous function (a function without a name).Functions stored in variables do not need function names. They are always invoked (called) using the variable name.

<html>

<head>

<script>

    var firstName = function(name)

    {

      document.write(name);

    };

    firstName("Jannath"); // calling anonymous function using variable name.

</script>

</head>

<body>

</body></html>

<html><head>

<script>

    var sum = new Function("x", "y", "return x + y");

    document.write(sum(20, 30));

</script></head></html>

Recursion

Recursion is defined as a process which calls itself directly or indirectly and the corresponding function is called a recursive function.

 

 

<html>

<head>

    <title>Recursive Function Example</title>

</head>

<body>

    <h1>Factorial Calculator</h1>

    <p>Enter a number to calculate its factorial:</p>

    <input type="number" id="numberInput">

    <button onclick="calculateFactorial()">Calculate Factorial</button>

    <p id="result"></p>

 

    <script>

        function calculateFactorial() {

            const numberInput = document.getElementById('numberInput').value;

            const resultElement = document.getElementById('result');

 

            if (numberInput === '') {

                resultElement.textContent = 'Please enter a number.';

                return;

            }

 

            const number = parseInt(numberInput);

 

            if (isNaN(number)) {

                resultElement.textContent = 'Invalid input. Please enter a valid number.';

                return;

            }

 

            if (number < 0) {

                resultElement.textContent = 'Factorial is not defined for negative numbers.';

                return;

            }

 

            const factorial = calculateRecursiveFactorial(number);

            resultElement.textContent = `Factorial of ${number} is ${factorial}.`;

        }

 

        function calculateRecursiveFactorial(n) {

            if (n === 0 || n === 1) {

                return 1;

            } else {

                return n * calculateRecursiveFactorial(n - 1);

            }

        }

    </script>

</body>

</html>               

 Arrow Function :

Arrow functions allow us to write shorter function syntax

<html>

<body>

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

<script>

let myFunction = (a, b) => a * b;

document.getElementById("demo").innerHTML = myFunction(4, 5);

</script>

 

</body>

</html>

 <html>

<body>

 

 

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

 

<script>

let hello = "";

 

hello = () => {

  return "Hello World!";

}

 

document.getElementById("demo").innerHTML = hello();

</script>

 

</body>

</html>

<html>

<body>

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

 

<script>

let hello = "";

 

hello = (val) => "Hello " + val;

 

document.getElementById("demo").innerHTML = hello("Trivandrum!");

</script>

</body></html>

 Objects :- Objects are variables too. But objects can contain many values.                                                                                                                <html>

<body>

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

 

<script>

 book = {type:"holy", name:"Bible", language:"English"};

 

document.getElementById("demo").innerHTML = "The book  is " + book.name;

</script>

 

</body>

</html>

<html>

<body>

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

<script>

const person = {firstName:"Jannath", lastName:"Kerala", age:30, eyeColor:"blue"};

 

document.getElementById("demo").innerHTML =

person.firstName + " is " + person.age + " years old.";

</script>

 

</body>

</html>

Types of objects in javascript:                                                                                                                                                                                      1.Built-in Objects

2.User Defind Objects

Built-in Objects

Object: The most fundamental object in JavaScript, used for creating custom objects.

Array: Used to store and manipulate arrays of data.

Function: Represents a JavaScript function.

Date: Used to work with dates and times.

Math: Provides mathematical functions and constants.

Array: an array is a data structure used to store a collection of values. Arrays can hold multiple values, and each value is associated with a numeric index. The elements in an array can be of any data type, including numbers, strings, objects, other arrays, and functions.

 

<html>

<body>

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

<script>

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

document.getElementById("demo").innerHTML = cars;

</script>

 

</body>

</html>

<html>

<body>

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

 

<script>

const cars = [];

cars[0]= "Alto";

cars[1]= "Volvo";

cars[2]= "BMW";

document.getElementById("demo").innerHTML = cars;

</script>

 

</body>

</html>

<html>

<body>

<h1>JavaScript Arrays</h1>

 

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

 

<script>

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

document.getElementById("demo").innerHTML = cars;

</script>

 

</body>

</html>

<html>

<body>

<h1>JavaScript Arrays</h1>

 

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

<p id="demo2"></p>

<p id="demo3"></p>

<p id="demo4"></p>

 

<script>

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

cars[0]="Suzuki";

document.getElementById("demo1").innerHTML = cars[0];

document.getElementById("demo2").innerHTML = cars;

document.getElementById("demo3").innerHTML = cars.length;

document.getElementById("demo4").innerHTML = cars[cars.length-1]

</script></body></html>

<html>

<body>

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

 

<script>

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

let fLen = fruits.length;

 

let text = "<ul>";

for (let i = 0; i < fLen; i++) {

  text += "<li>" + fruits[i] + "</li>";

}

text += "</ul>";

 

document.getElementById("demo").innerHTML = text;

</script>

 

</body>

</html>

<html>

<body>

<p>Call a function for each array element:</p>

 

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

 

<script>

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

 

let text = "<ul>";

fruits.forEach(myFunction);

text += "</ul>";

 

document.getElementById("demo").innerHTML = text;

 

function myFunction(value) {

  text += "<li>" + value + "</li>";

}

</script>

 

</body>

</html>

<html><body>

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

<script>

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

 

let text = "<ul>";

fruits.forEach(myFunction);

text += "</ul>";

 

document.getElementById("demo").innerHTML = text;

 

function myFunction(value) {

  text += "<li>" + value + "</li>";

}

</script></body></html>

 

Adding Array Elements

<html>

<body>

<p>The push method appends a new element to an array.</p>

 

<button onclick="myFunction()">Try it</button>

 

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

 

<script>

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

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

 

function myFunction() {

  fruits.push("Lemon");

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

}

</script>

 

</body>

</html>

<html>

<body>

<h1>JavaScript Arrays</h1>

 

<p>The length property provides an easy way to append new elements to an array without using the push() method.</p>

 

<button onclick="myFunction()">Try it</button>

 

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

 

<script>

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

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

 

function myFunction() {

  fruits[fruits.length] = "Lemon";

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

}

</script>

 

</body>

</html>

<html>

<body>

<h1>JavaScript Arrays</h1>

 

<p>Adding elements with high indexes can create undefined "holes" in an array.</p>

 

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

 

<script>

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

fruits[6] = "Lemon";

 

let fLen = fruits.length;

let text = "";

for (i = 0; i < fLen; i++) {

  text += fruits[i] + "<br>";

}

 

document.getElementById("demo").innerHTML = text;

</script>

 

</body>

</html>

The Difference Between Arrays and Objects

In JavaScript, arrays use numbered indexes.  

In JavaScript, objects use named indexes.

 

Array Methods

Join

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

 

<html>

<body>

<h1>JavaScript Arrays</h1>

<h2>The join() Method</h2>

 

<p>The join() method joins array elements into a string.</p>

<p>It this example we have used " * " as a separator between the elements:</p>

 

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

 

<script>

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

document.getElementById("demo").innerHTML = fruits.join(" * ");

</script>

 

</body>

</html>

Pop

The pop() method removes the last element from an array:

<html>

<body>

<h1>JavaScript Arrays</h1>

<h2>The pop() Method</h2>

 

<p>The pop() method removes the last element from an array.</p>

 

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

<p id="demo2"></p>

 

<script>

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

document.getElementById("demo1").innerHTML = fruits;

fruits.pop();

document.getElementById("demo2").innerHTML = fruits;

</script>

 

</body>

</html>

Push

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

<html>

<body>

<p>The push() method appends a new element to an array:</p>

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

<p id="demo2"></p>

 

<script>

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

document.getElementById("demo1").innerHTML = fruits;

fruits.push("Kiwi");

document.getElementById("demo2").innerHTML = fruits;

</script>

 

</body>

</html>

<html>

<body>

<h1>JavaScript Arrays</h1>

 

<p>Adding elements with high indexes can create undefined "holes" in an array.</p>

 

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

 

<script>

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

fruits[6] = "Lemon";

 

let fLen = fruits.length;

let text = "";

for (i = 0; i < fLen; i++) {

  text += fruits[i] + "<br>";

}

 

document.getElementById("demo").innerHTML = text;

</script>

 

</body>

</html>

The Difference Between Arrays and Objects

In JavaScript, arrays use numbered indexes. 

In JavaScript, objects use named indexes.

Array Methods

Join

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

<html>

<body>

<h1>JavaScript Arrays</h1>

<h2>The join() Method</h2>

 

<p>The join() method joins array elements into a string.</p>

<p>It this example we have used " * " as a separator between the elements:</p>

 

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

 

<script>

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

document.getElementById("demo").innerHTML = fruits.join(" * ");

</script>

 

</body>

</html>

Pop

The pop() method removes the last element from an array:

<html>

<body>

<h1>JavaScript Arrays</h1>

<h2>The pop() Method</h2>

 

<p>The pop() method removes the last element from an array.</p>

 

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

<p id="demo2"></p>

 

<script>

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

document.getElementById("demo1").innerHTML = fruits;

fruits.pop();

document.getElementById("demo2").innerHTML = fruits;

</script>

 

</body>

</html>

<html>

<body>

<h1>JavaScript Arrays</h1>

<h2>The shift() Method</h2>

 

<p>The shift() method removes the first element of an array (and "shifts" the other elements to the left):</p>

 

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

<p id="demo2"></p>

 

<script>

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

document.getElementById("demo1").innerHTML = fruits;

fruits.shift();

document.getElementById("demo2").innerHTML = fruits;

</script>

 

</body>

</html>

<html>

<body>

<h1>JavaScript Arrays</h1>

<h2>The shift() Method</h2>

 

<p>The shift() method removes the first element of an array (and "shifts" the other elements to the left):</p>

 

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

<p id="demo2"></p>

 

<script>

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

document.getElementById("demo1").innerHTML = fruits;

fruits.shift();

document.getElementById("demo2").innerHTML = fruits;

</script>

 

</body>

</html>

<html>

<body>

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

 

<script>

const myGirls = ["Jannath", "Ammu"];

const myBoys = ["anu", "Tomy", "Appu"];

const myChildren = myGirls.concat(myBoys);

 

document.getElementById("demo").innerHTML = myChildren;

</script>

 

</body>

</html>

<html>

<body>

 

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

 

<script>

const myArray = ["anu", "Tomy", "Lena"];

const myChildren = myArray.concat("Joy");

document.getElementById("demo").innerHTML = myChildren;

</script>

 

</body>

</html>

The flat() method creates a new array with sub-array elements concatenated to a specified depth.

<html>

<head>

    <title>Flat Method Example</title>

</head>

<body>

    <h1>Flatten an Array Using JavaScript</h1>

    <p>Original nested array:</p>

    <pre id="originalArray"></pre>

    <p>Flattened array:</p>

    <pre id="flattenedArray"></pre>

 

    <script>

        // Define the nested array

        const nestedArray = [1, 2, [3, 4, [5, 6]], 7, [8]];

 

        // Flatten the array using the flat() method

        const flatArray = nestedArray.flat();

 

        // Display the original and flattened arrays in the HTML document

        document.getElementById("originalArray").textContent = JSON.stringify(nestedArray, null, 2);

        document.getElementById("flattenedArray").textContent = JSON.stringify(flatArray, null, 2);

    </script>

</body>

</html>

Sort -The sort() method in JavaScript is used to sort the elements of an array in place and returns the sorted array.

<html>

<body>

 

<h2>JavaScript Arrays</h2>

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

 

<script>

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

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

</script>

 

</body>

</html>

slice-Array.slice() returns selected array elements as a new array:

<html>

<body>

<h2>JavaScript Array Methods</h2>

<h2>slice()</h2>

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

<script>

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

const citrus = fruits.slice(1, 3);

document.getElementById("demo").innerHTML = citrus;

</script></body></html>

<html><body><h2>JavaScript Array Methods</h2>

<h2>slice()</h2>

 

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

 

<script>

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

const myBest = fruits.slice(-3, -1);

 

document.getElementById("demo").innerHTML = myBest;

</script>

 

</body>

</html>

Fill-fills specified elements in an array with a value.

<html>

<body>

 

<h1>JavaScript Arrays</h1>

<h2>The fill() Method</h2>

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

 

<script>

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

document.getElementById("demo").innerHTML = fruits.fill("Kiwi");

</script>

</body>

</html>

<html><body>

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

 

<script>

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

document.getElementById("demo").innerHTML = fruits.fill("Kiwi",2,4);

</script></body>

</html>

splice-The Array.splice() method adds array elements

<html><body>

<p>The Array.splice() method adds array elements:</p>

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

<script>

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

fruits.splice(1,0, "Kiwi","grapes");

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

</script></body></html>

 Map() -The Array.map() method creates a new array from the results of calling a function for every element.

 <html><body>

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

<script>

const numbers = [4, 9, 16, 25];

document.getElementById("demo").innerHTML = numbers.map(Math.sqrt);

</script></body></html>

 

 

 The find() Method

find() returns the value of the first element in an array that passes a test (provided by a function)

<html><body>

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

<script>

const ages = [3, 10, 18, 20];

document.getElementById("demo").innerHTML = ages.find(checkAge);

function checkAge(age) {

  return age > 18;

}

</script></body></html>

The forEach() Method

forEach() calls a function for each element in an array

 

<html><body>

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

<script>

let text = "";

const fruits = ["apple", "orange", "cherry"];

fruits.forEach(myFunction);

document.getElementById("demo").innerHTML = text;

function myFunction(item, index) {

  text += index + ": " + item + "<br>";

}

</script></body></html>

The filter() method creates a new array filled with elements that pass a test provided by a function.

The filter() method does not execute the function for empty elements.

The filter() method does not change the original array.

<html><body>

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

<script>

const ages = [32, 33, 16, 40];

document.getElementById("demo").innerHTML = ages.filter(checkAdult);

function checkAdult(age) {

  return age >= 18;

}

</script></body></html>

 

 The findIndex() method executes a function for each array element.

The findIndex() method returns the index (position) of the first element that passes a test.

The findIndex() method returns -1 if no match is found.

The findIndex() method does not execute the function for empty array elements.

The findIndex() method does not change the original array.

 

<html><body>

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

<script>

const ages = [3, 10, 18, 20];

 

document.getElementById("demo").innerHTML = ages.findIndex(checkAge);

function checkAge(age) {

  return age > 18;

}

</script></body></html>

The some() method checks if any array elements pass a test (provided as a callback function).

The some() method executes the callback function once for each array element.

The some() method returns true (and stops) if the function returns true for one of the array elements.

The some() method returns false if the function returns false for all of the array elements.

The some() method does not execute the function for empty array elements.

The some() method does not change the original array.

 

 <html><body>

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

<script>

const ages = [3, 10, 18, 20];

document.getElementById("demo").innerHTML = ages.some(checkAdult);

function checkAdult(age) {

  return age > 18;

}

</script></body></html>

every() returns true if all elements in an array pass a test (provided as a function).

<html>

<body>

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

 

<script>

const ages = [32, 33, 16, 40];

document.getElementById("demo").innerHTML = ages.every(checkAge);

 

function checkAge(age) {

  return age > 18;

}

</script>

 

</body>

</html>

String

String length

<html><body>

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

<script>

let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

document.getElementById("demo").innerHTML = text.length;

</script></body>

</html>

 

 

String slice

slice() extracts a part of a string and returns the extracted part in a new string.

 

<html>

<body>

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

 

<script>

let text = "Apple, Banana, Kiwi";

let part = text.slice(7,13);

document.getElementById("demo").innerHTML = part;

</script>

 

</body>

</html>

substring-The substring() method extract a part of a string and returns the extracted parts in a new string

 <html>

<body>

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

 

<script>

let str = "hello world";

document.getElementById("demo").innerHTML = str.substring(0,5);

</script>

 

</body>

</html>

 The replace() method replaces a specified value with another value in a string

 <html>

<body>

<button onclick="myFunction()">Try it</button>

 

<p id="demo">Please visit Trivandrum!</p>

 

<script>

function myFunction() {

  let text = document.getElementById("demo").innerHTML;

  document.getElementById("demo").innerHTML =

  text.replace("Trivandrum","Dubai");

}

</script>

 

</body>

</html>

ReplaceAll

<html>

<body>

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

 

<script>

let text = "I love cats. Cats are very easy to love. Cats are very popular."

text = text.replaceAll("Cats","Dogs");

text = text.replaceAll("cats","dogs");

 

document.getElementById("demo").innerHTML = text;

</script>

 

</body>

</html>

toUpperCase

<html>

<body>

<button onclick="myFunction()">Try it</button>

 

<p id="demo">Hello World!</p>

 

<script>

function myFunction() {

  let text = document.getElementById("demo").innerHTML;

  document.getElementById("demo").innerHTML =

  text.toUpperCase();

}

</script>

 

</body>

</html>

toLowerCase

<html>

<body>

<button onclick="myFunction()">Try it</button>

<p id="demo">HELLO WORLD!</p>

<script>

function myFunction() {

  let text = document.getElementById("demo").innerHTML;

  document.getElementById("demo").innerHTML =

  text.toLowerCase();

}

</script>

</body>

</html>

Concat

<html><body>

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

<script>

let text1 = "Hello";

let text2 = "World!";

let text3 = text1.concat(" ",text2);

document.getElementById("demo").innerHTML = text3;

</script></body></html>

 

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

<html>

<body>

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

 

<script>

let text1 = "     Hello World!     ";

let text2 = text1.trim();

document.getElementById("demo").innerHTML =

"Length text1 = " + text1.length + "<br>Length text2 = " + text2.length;

</script></body>

</html>

charAt()-The charAt() method returns the character at a specified index (position) in a string

 

<html>

<body>

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

<script>

var text = "HELLO WORLD";

document.getElementById("demo").innerHTML = text.charAt(0);

</script>

 

</body>

</html>

split()

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

<html>

<body>

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

 

<script>

let text = "How are you doing today?";

const myArray = text.split(" ");

 

document.getElementById("demo").innerHTML = myArray;

</script>

 

</body>

</html>

Math Object

The JavaScript Math object allows you to perform mathematical tasks on numbers.

<html>

<body>

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

 

<script>

document.getElementById("demo").innerHTML = Math.PI;

</script>

 

</body>

</html>

<html>

<body>

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

 

<script>

document.getElementById("demo").innerHTML = Math.round(4.3);

</script>

 

</body>

</html>

<html>

<body>

<p>Math.ceil() rounds a number <strong>up</strong> to its nearest integer:</p>

 

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

 

<script>

document.getElementById("demo").innerHTML = Math.ceil(4.1);

</script>

 

</body>

</html>

<html>

<body>

 

<h2>JavaScript Math.floor()</h2>

 

<p>Math.floor(x) returns the value of x rounded <strong>down</strong> to its nearest integer:</p>

 

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

 

<script>

document.getElementById("demo").innerHTML = Math.floor(4.7);

</script>

 

</body>

</html>

<html>

<body>

 

<h2>JavaScript Math.trunc()</h2>

 

<p>Math.trunc(x) returns the integer part of x:</p>

 

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

 

<script>

document.getElementById("demo").innerHTML = Math.trunc(4.733);

</script>

 

</body>

</html>

<html>

<body>

 

<h2>JavaScript Math.pow()</h2>

 

<p>Math.pow(x,y) returns the value of x to the power of y:</p>

 

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

 

<script>

document.getElementById("demo").innerHTML = Math.pow(8,3);

</script>

 

</body>

</html>

<html>

<body>

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

 

<script>

document.getElementById("demo").innerHTML = Math.abs(-4.7);

</script>

 

</body>

</html>

<html>

<body>

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

 

<script>

document.getElementById("demo").innerHTML =

Math.min(0, 150, 30, 20, -8,200);

</script>

 

</body>

</html>

<html>

<body>

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

 

<script>

document.getElementById("demo").innerHTML =

Math.max(0, 150, 30, 20, -8, -200);

</script>

 

</body>

</html>

 

No comments:

Post a Comment

Techzmatrix