Monday, June 26, 2023

JavaScript Data

 

JavaScript Date Objects

JavaScript Date Objects let us work with dates:

Mon Jun 26 2023 11:26:10 GMT-0700 (Pacific Daylight Time)

Examples

<!DOCTYPE html>

<html>

<body>


<h1>JavaScript Dates</h1>

<h2>Using new Date()</h2>

<p>new Date() without arguments, creates a date object with the current date and time:</p>


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


<script>

const d = new Date();

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

</script>


</body>

</html>

Creating Date Objects

Date objects are created with the new Date() constructor.

There are 9 ways to create a new date object:

new Date()
new Date(date string)

new Date(year,month)
new Date(year,month,day)
new Date(year,month,day,hours)
new Date(year,month,day,hours,minutes)
new Date(year,month,day,hours,minutes,seconds)
new Date(year,month,day,hours,minutes,seconds,ms)

new Date(milliseconds)


JavaScript white Loop

 

The While Loop

The while loop loops through a block of code as long as a specified condition is true.

Syntax

while (condition) {
  // code block to be executed
}

Example

In the following example, the code in the loop will run, over and over again, as long as a variable (i) is less than 10:

Example

while (i < 10) {
  text += "The number is " + i;
  i++;
}

The Do While Loop

The do while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

Syntax

do {
  // code block to be executed
}
while (condition);

Example

do {
  text += "The number is " + i;
  i++;
}
while (i < 10);

JavaScript For of Loop

 

JavaScript For Of

The For Of Loop

The JavaScript for of statement loops through the values of an iterable object.

It lets you loop over iterable data structures such as Arrays, Strings, Maps, NodeLists, and more:

Syntax

for (variable of iterable) {
  // code block to be executed
}

variable - For every iteration the value of the next property is assigned to the variable. Variable can be declared with constlet, or var.

iterable - An object that has iterable properties.


Looping over an Array


Example

const cars = ["BMW""Volvo""Mini"];

let text = "";
for (let x of cars) {
  text += x;
}

Looping over a String

let language = "JavaScript";

let text = "";
for (let x of language) {
text += x;
}


JavaScript For in Loop

 

The For In Loop

The JavaScript for in statement loops through the properties of an Object:

for (key in object) {
  // code block to be executed
}

Example

const person = {fname:"John", lname:"Doe", age:25};

let text = "";
for (let x in person) {
  text += person[x];
}

Example Explained

  • The for in loop iterates over a person object
  • Each iteration returns a key (x)
  • The key is used to access the value of the key
  • The value of the key is person[x]                 

    For In Over Arrays

    The JavaScript for in statement can also loop over the properties of an Array:
     for (variable in array) {
      code
    }

    Example


  • const numbers = [45491625];

    for (let x in numbers) {
      txt += numbers[x];
    }
  • let txt = "";

Sunday, June 25, 2023

JavaScript For Loop

 

JavaScript Loops

Loops are handy, if you want to run the same code over and over again, each time with a different value.

Often this is the case when working with arrays:

Example

<!DOCTYPE html>

<html>

<body>


<h2>JavaScript For Loop</h2>


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


<script>

const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];


let text = "";

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

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

}


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

</script>


</body>

</html>


Wednesday, June 21, 2023

JavaScript Switch Statement

 

The JavaScript Switch Statement

Use the switch statement to select one of many code blocks to be executed.

Syntax

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

This is how it works:

  • The switch expression is evaluated once.
  • The value of the expression is compared with the values of each case.
  • If there is a match, the associated block of code is executed.
  • If there is no match, the default code block is executed.     

    Example

     The getDay() method returns the weekday as a number between 0 and 6.

    (Sunday=0, Monday=1, Tuesday=2 ..)

    This example uses the weekday number to calculate the weekday name:        <!DOCTYPE html>

    <html>

    <body>


    <h2>JavaScript switch</h2>


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

JavaScript if....Else

 

JavaScript if, else, and else if

Conditional Statements

Very often when you write code, you want to perform different actions for different decisions.

You can use conditional statements in your code to do this.

In JavaScript we have the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false






  • Use switch to specify many alternative blocks of code to be executed    

    The if Statement

    Use the if statement to specify a block of JavaScript code to be executed if a condition is true.

    Example  

    <html>

    <body>


    <h2>JavaScript if</h2>


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


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


    <script>

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

      document.getElementById("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.

  • Example  

  • <!DOCTYPE html>
    <html>
    <body>

    <h2>JavaScript if .. else</h2>

    <p>A time-based greeting:</p>

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




Sunday, June 18, 2023

JavaScript Booleans

 

Boolean Values

Very often, in programming, you will need a data type that can only have one of two values, like

  • YES / NO
  • ON / OFF
  • TRUE / FALSE

For this, JavaScript has a Boolean data type. It can only take the values true or false.

The Boolean() Function

You can use the Boolean() function to find out if an expression (or a variable) is true:

JavaScript Booleans

Display the value of Boolean(10 > 9):

true

Example

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Booleans</h1>
<p>Display the value of Boolean(10 > 9):</p>

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

<script>
document.getElementById("demo").innerHTML = Boolean(10 > 9);
</script>

</body>
</html>

Comparisons and Conditions

The chapter JS Comparisons gives a full overview of comparison operators.

The chapter JS Conditions gives a full overview of conditional statements.

Here are some examples:

OperatorDescriptionExample
==equal toif (day == "Monday")
>greater thanif (salary > 9000)
<less thanif (age < 18)


Saturday, June 17, 2023

JavaScript Random

Math.random()

JavaScript Math.random()

Math.random() returns a random number between 0 (included) and 1 (excluded):

0.5602783686247255

EXAMPLE

<!DOCTYPE html>

<html>

<body>


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


<p>Math.random() returns a random number between 0 (included) and 1 (excluded):</p>


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


<script>

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

</script>


</body>

</html>


JavaScript Random Integers

Math.random() used with Math.floor() can be used to return random integers.

JavaScript Math

Math.floor(Math.random() * 10) returns a random integer between 0 and 9 (both included):

7

EXAMPLE

<!DOCTYPE html>

<html>

<body>


<h2>JavaScript Math</h2>


<p>Math.floor(Math.random() * 10) returns a random integer between 0 and 9 (both 

included):</p>


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


<script>

document.getElementById("demo").innerHTML =

Math.floor(Math.random() * 10);

</script>


</body>

</html>


Thursday, June 15, 2023

JavaScript Arrays Sort/Reverse

 

JavaScript Arrays

The sort() Method

The sort() method sorts an array alphabetically:

Banana,Orange,Apple,Mango

Apple,Banana,Mango,Orange


:::Code:::

<!DOCTYPE html>

<html>

<body>

<h1>JavaScript Arrays</h1>

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


<p>The sort() method sorts an array alphabetically:</p>


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

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


<script>

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

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


fruits.sort();

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

</script>


</body>

</html>

JavaScript Arrays

Sort in Reverse

The reverse() method reverses the elements in an array.

By combining sort() and reverse() you can sort an array in descending order:

Banana,Orange,Apple,Mango

Orange,Mango,Banana,Apple

:::Code:::

<!DOCTYPE html>

<html>

<body>

<h1>JavaScript Arrays</h1>

<h2>Sort in 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>


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

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


<script>

// Create and display an array:

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

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


// First sort the array

fruits.sort();


// Then reverse it:

fruits.reverse();


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

</script>


</body>

</html>


Tuesday, June 13, 2023

JavaScript Arrays

 

JavaScript Arrays

Why Use Arrays?

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

let car1 = "Saab";
let car2 = "Volvo";
let car3 = "BMW";

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name, and you can access the values by referring to an index number.

Creating an Array

Using an array literal is the easiest way to create a JavaScript Array.

Syntax:

const array_name = [item1item2, ...];   <!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>

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

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

</body>
</html>

Tuesday, June 6, 2023

JavaScript Events

 

JavaScript Events

HTML Events

An HTML event can be something the browser does, or something a user does.

Here are some examples of HTML events:

  • An HTML web page has finished loading
  • An HTML input field was changed
  • An HTML button was clicked

Often, when events happen, you may want to do something.

JavaScript lets you execute code when events are detected.

HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

With single quotes:

<element event='some JavaScript'>

With double quotes:

<element event="some JavaScript">

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

Example

<!DOCTYPE html>
<html>
<body>

<button onclick="document.getElementById('demo').innerHTML=Date()">The time is?</button>

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

</body>
</html>

Example

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML Events</h2>
<button onclick="this.innerHTML=Date()">The time is?</button>

</body>
</html>

Example

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML Events</h2>
<p>Click the button to display the date.</p>

<button onclick="displayDate()">The time is?</button>

<script>
function displayDate() {
  document.getElementById("demo").innerHTML = Date();
}
</script>

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

</body>
</html> 

JavaScript Animated

  JavaScript Animated <!DOCTYPE html> <html> <style> #myContainer {   width: 400px;   height: 400px;   position: relative;...