Java Script

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 21

What are data types?

Data type mentions the type of value assigned to a variable.


In JavaScript, the type is not defined during variable declaration. Instead, it is
determined at run-time based on the value it is initialized with.
Hence, JavaScript language is a loosely typed or dynamically typed language.
Types of data types
JavaScript defines the following data types:

Next, let us understand each data type in detail.


Primitive data type – Number

The data is said to be primitive if it contains an individual value.

Let us explore each of the primitive data types individually.

Number

To store a variable that holds a numeric value, the primitive data type number is used. In
almost all the programming languages a number data type gets classified as shown below:

Example:

1. const pi = 3.14; // its value is 3.14


2. const smallestNaturalNumber = 0; // its value is 0

In JavaScript, any other value that does not belong to the above-mentioned types is not
considered as a legal number. Such values are represented as NaN (Not-a-Number).

Example:

1. let result = 0/0; // its value is NaN


2. let result = "Ten" * 5; //its value is NaN
Primitive data type – String
String
When a variable is used to store textual value, a primitive data type string is used. Thus, the
string represents textual values. String values are written in quotes, either single or double.
Example:

1. let personName= “Rexha”; //OR

2. let personName = ‘Rexha’; // both will have its value as Rexha

You can use quotes inside a string but that shouldn't match the quotes surrounding the string.
Strings containing single quotes must be enclosed within double quotes and vice versa.
Example:

1. let ownership= "Rexha's"; //OR

2. let ownership = 'Rexha"s';

 This will be interpreted as Rexha's and Rexha"s respectively. Thus, use opposite quotes
inside and outside of JavaScript single and double quotes.
 But if you use the same quotes inside a string and to enclose the string:
Example:

1. let ownership= "Rexha"s"; //OR

2. let ownership = 'Rexha's';

It is a syntax error.
 Thus, remember, strings containing single quotes must be enlosed within double quotes
and strings containing double quotes must be enclosed within single quotes.
 To access any character within the string, it is important to be aware of its position in the
string.
 The first character exists at index 0, next at index 1, and so on.

Lietrals

Literals can span multiple lines and interpolate expressions to include their results.

Example:

1. let firstName="Kevin";
2. let lastName="Patrick";
3. console.log("Name: "+firstName+" "+lastName+"\
n Email:"+firstName+"_"+lastName+"@abc.com");
4. /*
5. OUTPUT:
6. Name: Kevin Patrick
7. Email:[email protected]
8. */e, '+' is used for concatenation of identifiers and static content, and '\n' for a new line.

Primitive data type – Boolean


 When a variable is used to store a logical value that can always be true or false then,
primitive data type Boolean is used. Thus, Boolean is a data type which represents only
two values: true and false.
 Values such as 100, -5, “Cat”, 10<20, 1, 10*20+30, etc. evaluates to true whereas 0,
“”, NaN, undefined, null, etc. evaluates to false.
Undefined
When the variable is used to store "no value", primitive data type undefined is used.
Any variable that has not been assigned a value has the value undefined and such variable is
of type undefined. The undefined value represents "no value".

Example 1:

1. let custName; //here value and the data type are undefined

The JavaScript variable can be made empty by assigning the value undefined.

null

The null value represents "no object".

Null data type is required as JavaScript variable intended to be assigned with the object at a
later point in the program can be assigned null during the declaration.
Example 1:

1. let item = null;


2. // variable item is intended to be assigned with object later. Hence null is

assigned during variable declaration.

If required, the JavaScript variable can also be checked if it is pointing to a valid object or null.

BigInt
 BigInt is a special numeric type that provides support for integers of random length.
 A BigInt is generated by appending n to the end of an integer literal or by calling the
function BigInt that generates BigInt from strings, numbers, etc.
Example:

1. const bigintvar = 67423478234689887894747472389477823647n;


2.
3. OR
4.
5. const bigintvar = BigInt("67423478234689887894747472389477823647");
6.
7. const bigintFromNumber = BigInt(10); // same as 10n
Objects
 Objects in JavaScript are a collection of properties and are represented in the form of
[key-value pairs].
 The 'key' of a property is a string or a symbol and should be a legal identifier.
 The 'value' of a property can be any JavaScript value like Number, String, Boolean, or
another object.
 JavaScript provides the number of built-in objects as a part of the language and user-
defined JavaScript objects can be created using object literals.
Syntax:

1. {
2. key1 : value1,
3. key2 : value2,
4. key3 :

value3 5. };

Example:

1. let mySmartPhone = {
2. name: "iPhone",
3. brand: "Apple",
4. platform:
"iOS", 5. price:
50000
6. };

Array
The Array is a special data structure that is used to store an ordered collection, which cannot
be achieved using the objects.
There are two ways of creating an array:

1. let dummyArr = new Array();


2. //OR

3. let dummyArr = [];

Either array can be declared as empty and can be assigned with value later, or can have the
value assigned during the declaration.
Example:

1. digits =[1,2,3,"four"];

A single array can hold multiple values of different data types.

Working With Operators


 Operators in a programming language are the symbols used to perform operations on
the values.
 Operands: Represents the data.
 Operator: Performs certain operations on the operands.

1. let sum = 5 + 10;

 The statement formed using the operator and the operands are called Expression.
 In the above example, 5+10 is an expression.
 The values are termed as operands.
 The symbol ‘+’ is the operator which indicates which operation needs to be performed.
Types of Operators
Operators are categorized into unary, binary, and ternary based on the number of operands on
which they operate in an expression.
JavaScript supports the following types of operators:

Arithmetic Operators

Arithmetic operators are used for performing arithmetic operations

let sum = 5 + 3; // sum=8


let difference = 5 – 3; // difference=2
let product = 5 * 3; // product=15
let division = 5/3; // division=1
let mod = 5%3; // mod=2
let value = 5;
value++; // increment by 1,
value=6 let value = 10;
value--; // decrement by 1, value=9
Arithmetic Operators - String Type Operands

Arithmetic operator '+' when used with string type results in the concatenation.
1. let firstName = "James";
2. let lastName = "Roche";

3. let name = firstName + " " + lastName; // name = James Roche

Arithmetic operator ‘+’ when used with a string value and a numeric value, it results in a new
string value.

1. let strValue="James";
2. let numValue=10;

3. let newStrValue= strValue + " " + numValue; // newStrValue= James 10

Assignment Operators
Assignment operators are used for assigning values to the variables.

1. let 30 // num=30
2. let 10 // num=num+10 => num=40
3. let 10 // num=num-10 => num=20
4. let 30 // num=num*30 => num=900
5. let 10 // num=num/10 => num=3
6. let 10 // num=num%10 => num=0
Relational or Comparison Operators
 Relational operators are used for comparing values and the result of comparison is
always either true or false.
 Relational operators shown below do implicit data type conversion of one of the
operands before comparison.

1. 10 10 //false
2. 10 10 //true
3. 10 10 //false
4. 10 10 //true
5. 10 10 //true
6. 10 10 //false

Relational operators shown below compares both the values and the value types without any
implicit type conversion.
 Strict equality (===) and strict inequality (!==) operators consider only values of the
same type to be equal.
 Hence, strict equality and strict inequality operators are highly recommended to
determine whether two given values are equal or not.
Logical Operators
Logical operators allow a program to make a decision based on multiple conditions. Each
operand is considered a condition that can be evaluated to true or false.

1. 10 20 //true
2. 10 5 20 20 //false
3. 10 5 20 20 //true
typeof Operator
 "typeof" is an operator in JavaScript.
 JavaScript is a loosely typed language i.e., the type of variable is decided at runtime
based on the data assigned to it. This is also called dynamic data binding.
 As programmers, if required, the typeof operator can be used to find the data type of a
JavaScript variable.
The following are the ways in which it can be used and the corresponding results that it returns.

1. typeof "JavaScript World" //string


2. typeof 10.5 // number
3. typeof 10 > 20 //boolean
4. typeof undefined //undefined
5. typeof null //Object
6. typeof {itemPrice : 500} //Object
Working with Statements and
Expressions Statements
Statements are instructions in JavaScript that have to be executed by a web browser.
JavaScript code is made up of a sequence of statements and is executed in the same order as
they are written.
A Variable declaration is the simplest example of a JavaScript statement.
Syntax:

1. var firstName = "Newton" ;

 Other types of JavaScript statements include conditions/decision making, loops, etc.


 White (blank) spaces in statements are ignored.
 It is optional to end each JavaScript statement with a semicolon. But it is highly
recommended to use it as it avoids possible misinterpretation of the end of the
statements by JavaScript engine.
Expressions
While writing client-logic in JavaScript, variables and operators are often combined to do
computations. This is achieved by writing expressions.
Different types of expressions that can be written in JavaScript are:

1. 10 + 30; //Evaluates to numeric value


2. "Hello" + "World"; //Evaluates to string value
3. itemRating > 5; //Evaluates to boolean value
4. (age > 60): "Senior citizen": "Normal citizen";
5. /* Evaluates to one string value based on whether condition is true or false.
6. If the condition evaluates to true then the first string value "Senior citizen" is

assigned otherwise the second string value is assigned "Normal citizen" */

Example of an expression in a statement:

Types of Statements

In JavaScript, the statements can be classified into two types.

Conditional Statements:
 Conditional statements help you to decide based on certain conditions.
 These conditions are specified by a set of conditional statements
having boolean expressions that are evaluated to a boolean value true or false.
Non-Conditional Statements:
Non-Conditional statements are those statements that do not need any condition to control the
program execution flow.
Types of Non-Conditional Statements
 Non-Conditional statements are those statements that do not need any condition to
control the program execution flow.
 In JavaScript, it can be broadly classified into three categories as follows:
Comments
Comments in JavaScript can be used to prevent the execution of a certain lines of code and to
add information in the code that explains the significance of the line of code being written.
JavaScript supports two kinds of comments.

Example:

1. // Formula to find the area of a circle given its radius


2. var areaOfCircle = 2 * pi * radius;
3.
4. /*Formula to find the area of a circle based on
5. given its radius value.
6. */

7. var areaOfCircle = 2 * pi * radius;

Note: As a best practice, it is recommended to use comments for documentation purposes


and avoid using it for code commenting.
Break Statement
While iterating over the block of code getting executed within the loop, the loop may be
required to be exited if certain condition is met.
The 'break' statement is used to terminate the loop and transfer control to the first statement
following the loop.
Syntax:

1. break;

 Below example shows for loop with five iterations which increment variable
"counter".
 When loop counter = 3, loop terminates.
 Also, shown below is the value of the counter and loopVar for every iteration of the
loop.
1. var counter = 0;
2. for (var loop = 0; loop < 5; loop++) {
3. if (loop == 3)
4. break;
5. counter++;

6. }

loopVar counter
0 1
1 2
2 3
3 Loop terminated. counter = 3.
The 'if' statement used in the above example is a conditional / decision-making statement.
Continue Statement
There are times when during the iteration of the block of code within the loop, the block
execution may be required to be skipped for a specific value and then continue to execute the
block for all the other values. JavaScript gives a 'continue' statement to handle this.
Continue statement is used to terminate the current iteration of the loop and continue
execution of the loop with the next iteration.
Syntax:

1. continue;

Below example shows for loop with five iterations which increment variable "counter".
When loop counter = 3, the current iteration is skipped and moved to the next iteration.
Also, shown below is the value of the counter and the variable loop for every iteration of the
loop.

1. var counter = 0;
2. for (var loop = 0; loop < 5; loop++) {
3. if (loop == 3)
4. continue;
5. counter++;

6. }

loopVar counter
0 1
1 2
2 3
3 Iteration terminated. Hence counter is not incremented.
4 4

The 'if' statement used in the example is a conditional / decision-making statement.


Types of Conditional Statements
 Conditional statements help in performing different actions for different conditions.
 It is also termed as decision-making statements.

JavaScript supports two decision-making statements:

Ternary operator
 It is a conditional operator that evaluates to one of the values based on whether the
condition is true or false.
 It happens to be the only operator in JavaScript that takes three operands. It is mostly
used as a shortcut of 'if-else' condition.
 Example:

1. let workingHours = 9.20;


2. let additionalHours;
3. (workingHours > 9.15) ? additionalHours = "You have positive
additional hours" : additionalHours = "You have negative additional
hours";

4. console.log(additionalHours);

If Statements
Let us see each of them in detail.
if statement
The 'if' statement is used to execute a block of code if the given condition evaluates to true.
Syntax:

1. if (condition) {
2. // block of code that will be executed, if the condition is true

3. }
Example:

1. let num1 = 12;


2. if (num1 % 2 == 0) {
3. console.log("It is an even number!!");
4. }
5. // OUTPUT: It is an even number!! Because 12%2 evaluates to true

If-else
The 'else' statement is used to execute a block of code if the given condition evaluates to false.
Syntax:

1. if (condition) {
2. // block of code that will be executed, if the condition is true
3. }
4. else {
5. // block of code that will be executed, if the condition is false
6. }

7.

Example:

1. let num1 = 1;
2. if (num1 % 2 == 0) {
3. console.log("It is an even number!!");
4. }
5. else{
6. console.log("It is an odd number!!");
7. }
8. //OUTPUT: It is an odd number!! Because in if 1%2 evaluates to false and moves to
else condition

If-else-if Ladder
if...else ladder is used to check for a new condition when the first condition evaluates to false.
Syntax:

1. if (condition1) {
2. // block of code that will be executed if condition1 is true
3. }
4. else if (condition2) {
5. // block of code that will be executed if the condition1 is false and condition2 is true
6. }
7. else {
8. // block of code that will be executed if the condition1 is false and condition2 is false

9. }
Example:

1. let marks = 76;


2. if (marks >= 75) {
3. console.log("Very Good")
; 4. }
5. else if (marks < 85 && marks >= 50) {
6. console.log("Good")
; 7. }
8. else {
9. console.log("Needs Improvement");
10. }
11. // OUTPUT: Needs Improvement, Because the value of marks is 46
which doesn't satisfy the first two condition checks.

Switch Statement
The Switch statement is used to select and evaluate one of the many blocks of code.
Syntax:

1. switch (expression) {
2. case value1: code block;
3. break;
4. case value2: code block;
5. break;
6. case valueN: code block;
7. break;
8. default: code

block; 9. }

'break' statement is used to come out of the switch and continue execution of statement(s) the
following switch.

Example:
For the given Employee performance rating (between 1 to 5), displays the appropriate
performance badge.

1. var perfRating = 5;
2.
3. switch (perfRating) { case 5:
4. console.log("Very Poor"); break;
5. case 4:
6. console.log("Needs Improvement"); break;
7. case 3:
8. console.log("Met Expectations"); break;
9. case 2:
10.
11.
12.
13.
14. console.log("Commendable");
15. break;
16. case 1:
17. console.log("Outstanding");
18. break;
19. default:
20. console.log("Sorry!! Invalid Rating.");
21. }
22.

23.

OUTPUT: Very Poor


Switch Statement - with break statement
The break statements allow to get control out of the switch once we any match is found.

Example:
For the given Employee performance rating (between 1 to 5), displays the appropriate
performance badge.

1. var perfRating = 3;
2.
3. switch (perfRating) {
4. case 5:
5. console.log("Very Poor"); break;
6. case 4:
7. console.log("Needs Improvement"); break;
8.
9.
10. case 3:
console.log("Met Expectations");
break; 13. case 2:
console.log("Commendable");
break; 16. case 1:
console.log("Outstanding");
break;
default:
console.log("Sorry!! Invalid Rating.");
21. } 22.
23. /*
24. OUTPUT:
25.
26. Met Expectation
27. */
28.

The reason for the above output is, first perfRating value is checked against case 5 and it does
not match. Next, it is checked against case 4 and it also does not match. Next, when it is
checked against case 3. it got a match hence “Met Expectation” is displayed, and the
break statement moves the execution control out of the switch statement.

Switch Statement - without break statement


Consider the below code snippet without break statement:

1. var perfRating = 5;
2.
3. switch (perfRating) {
4. case 5:
5. console.log("Very Poor");
6.
7. case 4:
8. console.log("Needs Improvement");
9.
10. case 3:
11. console.log("Met Expectations"); 12.
13. case 2:
14. console.log("Commendable"); 15.
16. case 1:
17. console.log("Outstanding"); 18.
default:
console.log("Sorry!! Invalid Rating.");
21. } 22.
23. /*
OUTPUT:
Very Poor
Needs Improvement
Met Expectations
Commendable
Outstanding
Sorry!! Invalid Rating.
31. */
32.

33.
The reason for the above output
is, initially perfRating is checked against case 5 and it got matched,
hence 'Very Poor' is displayed. But as the break statement is missing,
the remaining cases including default got executed.
Switch Statement - default statement
A scenario in which the default statement gets executed.

1. var perfRating = 15;


2.
3. switch (perfRating) {
4. case 5:
5. console.log("Very Poor");
6. break;
7. case 4:
8. console.log("Needs Improvement");
9. break;
10. case 3:
11. console.log("Met Expectations"); 12. break;
13. case 2:
14. console.log("Commendable"); 15. break;
16. case 1:
17. console.log("Outstanding"); 18. break;
default:
console.log("Sorry!! Invalid Rating.");
21. } 22.
23. /*
OUTPUT:
Sorry!! Invalid Rating.
26. */

27.

Working With Loops


In JavaScript code, specific actions may have to be repeated a number of times.
For example, consider a variable counter which has to be incremented five times.
To achieve this, increment statement can be wiritten five times as shown below:

1. let counter = 0;
2. /* Same statement repeated 5 times */
3. counter++;
4. counter++;
5. counter++;
6. counter++;

7. counter++;

Looping statements in JavaScript helps to execute statement(s) required number of times


without repeating code.
Best Practice: Avoid heavy nesting inside the loops.
Types of Loops
JavaScript supports popular looping statements as shown below:

For Loop
'for' loop is used when the block of code is expected to execute for a specific number of
times. To implement it, use the following syntax.

Example - For Loop


Example: Below example shows incrementing variable counter five times using 'for' loop:
Also, shown below is output for every iteration of the loop.

1. let counter = 0;
2. for (let loopVar = 0; loopVar < 5; loopVar++) {
3. counter = counter + 1;
4. console.log(counter)

; 5. }

Here, in the above loop


let loopVar=0; // Initialization
loopVar < 5; // Condition
loopVar++; // Update
counter = counter + 1; // Action
To understand loops better refer the below table:
loopVar counter
0 1
1 2
2 3
3 4
4 5

While Loop
'while' loop is used when the block of code is to be executed as long as the specified
condition is true. To implement the same, the following syntax is used:

The value for the variable used in the test condition should be updated inside the loop
only.
Example - While Loop
Example: The below example shows an incrementing variable counter five times using a
'while' loop.
Also, shown below is the output for every iteration of the loop.

1. let counter = 0;
2. let loopVar = 0;
3. while (loopVar < 5) {
4. console.log(loopVar);
5. counter++;
6. loopVar++;
7. console.log(counter)

; 8. }

Here, in the above loop


let counter=0; // Initialization
let loopVar=0; // Initialization
loopVar < 5; // Condition
loopVar++; // Update
counter++; // Action
To understand loops better refer the below table:
loopVar counter
0 1
1 2
2 3
3 4
4 5
Do-While Loop
 'do-while' is a variant of 'while' loop.
 This will execute a block of code once before checking any condition.
 Then, after executing the block it will evaluate the condition given at the
end of the block of code.
 Now the statements inside the block of code will be repeated till condition
evaluates to true.
 To implement 'do-while' loop, use the following syntax:

The value for the variable used in the test condition should be updated inside the loop only.
Example : Do-While Loop
Example: Below example shows incrementing variable counter five times using
'do-while' loop:
Also, shown below is output for every iteration of the loop.

1. let counter = 0;
2. let loopVar = 0;
3. do {
4. console.log(loopVar);
5. counter++;
6. loopVar++;
7. console.log(counter)
; 8. }

9. while (loopVar < 5);

Here, in the above loop


let counter=0; //
Initialization let
loopVar=0; //
Initialization
loopVar < 5; //
Condition loopVar+
+; // Update
counter++; // Action
To understand loops better refer the below table:
loopVar counter
0 1
1 2
2 3
3 4
4 5

You might also like