0% found this document useful (0 votes)
22 views

JavaScript Tutorial 02

Uploaded by

sajeevmohan001
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

JavaScript Tutorial 02

Uploaded by

sajeevmohan001
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

JavaScript - For client side scripting (Tutorial 02)

JavaScript Data Types

1.Primitives

The latest ECMAScript standard defines eight data types: Seven data types that
are primitives:

1. Boolean. true and false.


2. null. A special keyword denoting a null value. (Because JavaScript is
case-sensitive, null is not the same as Null, NULL, or any other variant.)
3. undefined. A top-level property whose value is not defined.
4. Number. An integer or floating point number. For example: 42 or
3.14159.
5. BigInt. An integer with arbitrary precision. For example:
9007199254740992n.
6. String. A sequence of characters that represent a text value. For example:
"Howdy".
7. Symbol. A data type whose instances are unique and immutable.

let firstName = "John"; //strings


let age = 21; //number
let student = true; //booleans

console.log("Hello", firstName);
console.log("You are", age, "years old");
console.log("Enrolled:", student);

document.getElementById("p1").innerHTML = "Hello " + firstName;


document.getElementById("p2").innerHTML = "You are " + age + " years old";
document.getElementById("p3").innerHTML = "Enrolled: " + student;
COM 2303, ICT 2204

2. Non-primitives/ Special Data types

Arrays
Arrays can hold more than one variable and special types of object. Arrays consist of
square brackets and items that are separated by commas.

We use arrays whenever we want to create and store a list of multiple items in a single
variable. Arrays are especially useful when creating ordered collections where items in
the collection can be accessed by their numerical position in the list

It is a common practice to declare arrays with the const keyword.

Syntax:

const array_name = [item1, item2, ...];

const shopping = ['bread', 'milk', 'cheese', 'hummus', 'noodles'];


console.log(shopping);

Declaring a constant array does NOT make the elements unchangeable.

Declaring a variable as const only means that you cannot assign a new value to that
variable once a value has been assigned. you can still perform operations on the array
elements, such as adding new elements to the array, changing the value of an element,
or removing elements.
<p id="demo"></p> <p id="demo"></p>

<script> <script>
// Create an Array: // Create an Array:
cars = ["Saab", "Volvo", "BMW"]; const cars = ["Saab", "Volvo", "BMW"];
//Reassign array //Reassign array
cars = ["SUV", "Sport", "Muscle"]; cars = ["SUV", "Sport", "Muscle"];

// Display the Array: // Display the Array:


document.getElementById("demo").innerHTML document.getElementById("demo").innerHTML =
= cars; cars;
</script> </script>
TypeError: Assignment to constant variable

1
COM 2303, ICT 2204

JavaScript arrays can contain any and all types of data at the
same time!

In the above example, each item is a string, but in an array we can store various data
types — strings, numbers, objects, and even other arrays. We can also mix data types in
a single array — we do not have to limit ourselves to storing only numbers in one array,
and in another only strings. For example:

const shopping = ['bread', 'milk', 'cheese', 1, 2, 3, true ];


console.log(shopping);

Objects

An object is a collection of related data and/or functionality. These usually consist of


several variables and functions (which are called properties and methods when they are
inside objects)

Objects are used to represent a “thing” in your code. That could be a person, a car, a
building, a book, a character in a game — basically anything that is made up or can be
defined by a set of characteristics

const car = {type:"Fiat", model:"500", color:"white"};

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

<script>
// Create an object:
const car = {type:"Fiat", model:"500", color:"white"};

// Display some data from the object:


document.getElementById("demo").innerHTML = "The car type is " + car.type;
console.log(car);
</script>

2
COM 2303, ICT 2204

An object is made up of multiple members, each of which has a name, and a value. Each
name/value pair must be separated by a comma, and the name and value in each case
are separated by a colon

To access the object's properties and methods we use dot notation

Data type conversion

JavaScript is a dynamically typed language. This means you don't have to specify the
data type of a variable when you declare it. It also means that data types are
automatically converted as-needed during script execution.

So, for example, you could define a variable as follows:

let answer = 42;

And later, you could assign the same variable a string value, for example:

answer = "Thanks for all the fish!";

Because JavaScript is dynamically typed, this assignment does not cause an error
message.

3
COM 2303, ICT 2204

Using Constructors for Data Type Conversion

// type conversion = change the datatype of a value to another (strings, numbers,


booleans)

let age = window.prompt("How old are you?");

console.log(typeof age);
age = Number(age);
age += 1;

console.log("Happy Birthday! You are", age, "years old");

/*
let x;
let y;
let z;

x = Number("pizza");
y = String(3.14);
z = Boolean("pizza");

console.log(x, typeof x);


console.log(y, typeof y);
console.log(z, typeof z);
*

4
COM 2303, ICT 2204

Flow Control

Conditional Statements

A conditional statement is a set of commands that executes if a specified condition is


true. JavaScript supports two conditional statements: if...else and switch.

if...else statement

Use the if statement to execute a statement if a logical condition is true.


Use the optional else clause to execute a statement if the condition is false.

An if statement looks like this:

if (condition) {
statement1;
} else {
statement2;
}

If statement If.. else statement

5
COM 2303, ICT 2204

Here, the condition can be any expression that evaluates to true or false.
If condition evaluates to true, statement_1 is executed. Otherwise, statement_2 is
executed. statement_1 and statement_2 can be any statement, including further nested
if statements.

You can also compound the statements using else if to have multiple conditions tested
in sequence, as follows:

if (condition1) {
statement1;
} else if (condition2) {
statement2;
} else if (conditionN) {
statementN;
} else {
statementLast;
}

In the case of multiple conditions, only the first logical condition which evaluates to true
will be executed. To execute multiple statements, group them within a block statement
({ /* … */ }).

In general, it's good practice to always use block statements—especially when nesting if
statements:

<script>
const hour = new Date().getHours();
let greeting;

if (hour < 18) {


greeting = "Good day";
} else {
greeting = "Good evening";
}
console.log(greeting);

6
COM 2303, ICT 2204

switch statement

A switch statement allows a program to evaluate an expression and attempt to match


the expression's value to a case label. If a match is found, the program executes the
associated statement.

A switch statement looks like this:

switch (expression) {
case label1:
statements1;
break;
case label2:
statements2;
break;
// …
default:
statementsDefault;
}

JavaScript evaluates the above switch statement as follows:

● The program first looks for a case clause with a label matching the value of
expression and then transfers control to that clause, executing the associated
statements.
● If no matching label is found, the program looks for the optional default clause:
● If a default clause is found, the program transfers control to that clause,
executing the associated statements.
● If no default clause is found, the program resumes execution at the statement
following the end of switch.
(By convention, the default clause is written as the last clause, but it does not need to be
so.)

break statements

The optional break statement associated with each case clause ensures that the
program breaks out of switch once the matched statement is executed, and then
continues execution at the statement following switch. If break is omitted, the program

7
COM 2303, ICT 2204

continues execution inside the switch statement (and will evaluate the next case, and so
on).

eg:

<script>

let fruitType= window.prompt("Which fruit do you need?");

switch (fruitType) {
case "Oranges":
console.log("Oranges are $0.59 a pound.");
break;
case "Apples":
console.log("Apples are $0.32 a pound.");
break;
case "Bananas":
console.log("Bananas are $0.48 a pound.");
break;
case "Cherries":
console.log("Cherries are $3.00 a pound.");
break;
case "Mangoes":
console.log("Mangoes are $0.56 a pound.");
break;
case "Papayas":
console.log("Mangoes and papayas are $2.79 a pound.");
break;
default:
console.log(`Sorry, we are out of’,fruitType );
}
console.log("Is there anything else you'd like?");

</script>

You might also like