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

Getting Started With JavaScript

The document provides an introduction to JavaScript basics. It discusses using the JavaScript console to perform math operations. It describes JavaScript data types including primitive types like numbers, strings, booleans. It explains variables and how to assign values of different data types to variables. The document also outlines arithmetic operators in JavaScript like exponentiation, remainder, and increment operators.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Getting Started With JavaScript

The document provides an introduction to JavaScript basics. It discusses using the JavaScript console to perform math operations. It describes JavaScript data types including primitive types like numbers, strings, booleans. It explains variables and how to assign values of different data types to variables. The document also outlines arithmetic operators in JavaScript like exponentiation, remainder, and increment operators.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

1/23/2024

Getting Started with JavaScript


Learning JavaScript

DigiChamps

Learning Objectives

● use JavaScript Console;


● perform basic math operations on JavaScript;
● understand JavaScript data types;
● implement variables and different types of operators.

2
1/23/2024

Outline

● Basics of JavaScript.

After a website is created using HTML, it is JavaScript that makes it interactive. Take the
instance of some web features you use every day, like an online maps application. You can
zoom in and out, place markers and get information about most places with a click. Similarly,
in an online restaurant booking system with an interactive seating plan of a restaurant, you
can see which tables are open at what time.

JavaScript is a scripting language used to make and control dynamic website content like
photo slideshows, interactive forms, animated graphics, autocomplete text suggestions, and
much more. Let’s learn some of the basics of JavaScript in this sprint.

4
1/23/2024

Using JavaScript Console

Using JavaScript Console

You can start practicing JavaScript using Chrome's Console .

Step 1: Click on the three dots button ( ) in the upper right corner of the Google Chrome
browser.

Step 2: Choose More Tools.

6
1/23/2024

Step 3: Select Developer Tools .

Step 4: Most of the time, the tools will be docked on the right side of the screen or at the
bottom. Select the Console tab to open the JavaScript Console

8
1/23/2024

Step 5: Let’s add two numbers in the Console . Type 2+5; in the JavaScript Console and press
the enter key. Though it is not compulsory, as a best practice, add a semicolon ( ; ) at the end
of each line of code in JavaScript.

You just added two numbers using JavaScript. Let’s do a few more basic arithmetic operations
like subtraction, multiplication, division, exponentiation, and so on.

Step 6: Type the following and observe the output.

JavaScript has operators for doing the four basic math calculations: addition ( + ),
subtraction ( - ), multiplication ( * ), and division ( / ). In addition to these, JavaScript also
comes with other operators that we will learn in the following sections.

10
1/23/2024

JavaScript data types

11

JavaScript data types

In a JavaScript program, you can use different kinds of data. JavaScript has two main data
types as mentioned below:

a. Primitive data types

b. Non-primitive (reference) data types

JavaScript primitive data types

There are seven primitive data types that JavaScript offers. These are also called built-in
data types. Here is the list of five primitive data types with a brief description.

12
1/23/2024

The non-primitive data types are derived from primitive data types . List and array are
examples of non-primitive data types. We will learn about non-primitive data types at a later
stage.
13

Variables

14
1/23/2024

Variables

A variable is like a box that has a name and can hold data. The image shows a variable named
a holding the value 20.

15

To declare variable a , write:

let a;

Declaring a variable doesn’t actually mean it holds any value. For that, you need to assign
some value to the variable.

A variable can be assigned a value using the assignment operator = . This way of creating a
variable and assigning a value to it is called variable initialization.

Let’s create a variable with the character a and initialize its value as 20 . In the Console , if
you want to write codes in multiple lines, press the shift+enter (or shift+return) key.

let a;
a = 20; 16
1/23/2024

Here in the first statement, you are declaring a variable a and in the second statement you
are assigning value 20 to the variable a . You can also initialize the value of a variable when
you declare it.

let a = 20;

Multiple variables can also be initialized in JavaScript in a single statement, separated by


commas.

let a = 20 , b = 60 , c= 70;

17

Assigning different types of data to a variable

Let’s try assigning different types of data to variables in the Console .

Step 1: Open Chrome's Console .

Step 2: Assign an integer value 10 to a variable a.

let a = 10; // number 10 is assigned to


variable a which is integer type

The above JavaScript command will store the number 10 in the variable a . This can be
checked by printing the variable in Console . To print the value of variable a , type:

a;
18
1/23/2024

Step 3: Assign a decimal value 54.34 to a variable b and print the value to the Console.

let b = 54.34 ; // 54.34 is assigned to variable b


which is float type b;

19

Step 4: Assign a character value " m" to a variable chr and print the value to the Console.

let chr = "m"; // "m" is assigned to variable chr


which is string type chr;

Step 5: A group of characters is called a string. Let’s initialize a string value "Computer
Science" to a variable subject and print the value to the Console

20
1/23/2024

let subject = "Computer Science" ; // "Computer


Science" is assigned to variable subject which is
string type subject;

21

Step 6: Assign a boolean value true/false to a variable userLoggedIn and print the value to
the Console .

let userLoggedIn = false ;


userLoggedIn;

22
1/23/2024

Arithmetic operators in JavaScript

In addition to the basic four arithmetic operators ( + , - , * , / ) there are a few more useful
arithmetic operators.

Exponentiation operator

To evaluate in JavaScript, a**b is used. The ** is called the exponentiation operator. 𝑎 𝑏

Step 1: Type the following in the Console :

2**3

23

Remainder operator

If an integer is not completely divisible by another integer, you get a remainder. For example,
dividing 16 by 5 will give the remainder 1. JavaScript provides a remainder operator ( % ) to
find out the remainder when an integer is divided by another.

Step 2: Type the following in the Console :

16%5

24
1/23/2024

Increment operator

JavaScript provides an increment operator that helps to increase the value of an operand by 1.
This operator is written as ++ . There are two ways in which the increment operator can be
used to increase the value of an operand x by 1.

margin-bottom: 20px;

25

Step 3: Type the following in the Console :

let x = 5 , y = 5;

Step 4: Check the value of x

x;

26
1/23/2024

Step 5: Check the value of y .

y;

Step 6: Now, let’s increment the value of x by 1, using the increment operator as a prefix.

++x;

27

It increments the value of x by 1, and immediately returns the value after the increment.
Step 7: Let’s increment the value of y by 1 using the increment operator as a postfix.

y++;

The value displayed on the Console is still 5 because using the increment operator as postfix
first returns the value of the operand and then increases it by 1.
Step 8: To check if the value of operand y has increased by 1, type:
28
1/23/2024

y;

29

Unary plus and negation

If an operand is not a number, the unary plus operator ( + ), when added as a prefix to an
operand, attempts to convert it to a number. Let’s understand it by working with this operator.
Step 9: Initialize x = "3" . Remember that adding the number 3 in quotes will make it a string
data type.

let x = "3";

The typeof operator followed by an operand tells us the data type of the value the variable
holds.
Step 10: Check the data type of x , using typeof operator.

30
1/23/2024

typeof x;

Step 11: Check the data type of +x . Here the unary plus operator is added as a prefix.

typeof +x;

31

The unary negation ( - ) operator when used as a prefix with an operand, will return its
negative counterpart. For example, if x = 4 , the results of -x will be -4. Alternatively, if y = -6 ,
the result of -y will be 6.

Step 12: Type the following in the Console :

32
1/23/2024

Comparison operators in JavaScript

While the arithmetic operators are useful in performing arithmetic operations, you also need
to compare two operands in many situations. For this comparison, operators are used in
JavaScript. You already know that the equal sign ( = ) is used to assign a value to a variable.
Hence, a single equal sign cannot be used to compare two operands. Instead, two equal signs (
== ) are used.

Step 1: Let's compare a few numbers using the == operator. Type the following in the
Console:

33

As both the operands (number 5 in this case) are equal, the result is true . If you try 5 == 7;
you will get the result as false . You can also compare strings using this operator. Try
"apple"=="apple"; and you will get true . Compare "apple"=="aple"; . What result do you get?

Step 2: Compare 3 with "3", where 3 enclosed in quotes is a string.

34
1/23/2024

This operator still gives a true result, as it compares "3" (a string) with 3 (a number) after
converting "3" (a string) to a number. Therefore, to strictly compare two operands in JavaScript
three equal signs ( === ) are used. The three equal signs ( === ) are together termed as the
strictly equal operator.

Step 3: Let’s use the strictly equal ( === ) operator to compare 3 with "3".

35

The strictly equal ( === ) operator doesn’t convert the data type of the operand, hence you get
a false result in this case. Below are a few more comparison operators.

36
1/23/2024

37

Try these operators to compare different numbers, and strings to understand how they work.

38
1/23/2024

Changing the value of a variable

39

Incrementing the value of a variable

Let's first assign a value 5 to the variable x.

Now, let's increment the value of x by 1 .

40
1/23/2024

41

Now, let's increment the value of x by 5 .

42
1/23/2024

Swapping values of variables

Let’s write a program to swap the values of the variables.

Step 1: Declare and initialize two variables: a = 10 and b = 12.

Step 2: Take a third variable, temp , which will hold the swapped data temporarily.

Step 3: Swap the values of the variables.

43

Step 4: Get the value of a.

Step 5: Get the value of b.

44
1/23/2024

Operator precedence

The order in which operations are carried out in an arithmetic expression is known as operator
precedence. Multiplication ( * ) and division ( / ) take precedence over addition ( + ) and
subtraction ( - ).

As in traditional math, the first step is to multiply:

45

Now, let’s use parentheses and check the result. Observe that, when you use parentheses, the
operations inside them are evaluated first.

46
1/23/2024

Operators with the same precedence (such as * and / ) are computed from left to right.

47

Master Challenges

48
1/23/2024

Challenge 1

If p = 6, and q = 8; evaluate the output in the following cases without and with the use of
Console. Compare your results with the results obtained from the Console.

1) p * q + p
2) p * q / p
3) (p + q) - p

49

Challenge 1 - Solution
Solution:
A sample solution is given below:
a) p * q + p
Without the use of Console: if we substitute p = 6 and q = 8, the expression becomes 6 * 8 + 6,
which simplifies to 48 + 6, resulting in 54.
p*q+p
=6*8+6
= 48 + 6
= 54

Using the Console: if we run console.log(p * q + p) in the console with p = 6 and q = 8, it will
display 54 as the output.

50
1/23/2024

let p=6;
let q=8;
console.log(p * q + p); // Output : 54

51

2. p * q / p

Without the use of Console: substituting p = 6 and q = 8, the expression becomes 6 * 8 / 6,


which simplifies to 48 / 6, resulting in 8.

p*q/p
let p=6;
=6*8/6 let q=8;
console.log(p * q / p); Output : 8
= 48 / 6

=8

Using the console: if we run console.log(p * q + p) in the console with p = 6 and q = 8, it will
display 54 as the output.

52
1/23/2024

3. (p + q) - p * q
Without the use of Console: substituting p = 6 and q = 8, the expression becomes (6 + 8) - 6 *
8, which simplifies to 14 - 48, resulting in -34.
(p + q) - p * q
let p=6;
= (6 + 8) - 6 * 8 let q=8;
console.log((p + q) - p * q); //
= 14 - 48 Output: -34
= -34
Using the console: if we run console.log((p + q) - p * q) in the console with p = 6 and q = 8, it
will display -34 as the output.

53

Challenge 2

Write a program to figure out how much an organization has donated to a disaster relief fund
if one of its department has given $1,500 every year for the past 10 years and another
department has given $19,800 every year for the past 5 years.

54
1/23/2024

Challenge 2 - Solution

Solution:
A sample solution is given below:
Step 1: Open Chrome's Console.
Step 2: Calculate the total amount donated by each department by multiplying the annual
donation amount by the number of years.
Step 3: Calculate the total donation of the organization by summing up the amounts donated
by both departments.
Step 4: Use console.log() to display the total amount donated to the disaster relief fund.

55

Challenge 2 - Solution
// Calculate the total amount donated by each department
const department1 = 1500 * 10; // $1,500 donated every
year for 10 years
const department2 = 19800 * 5; // $19,800 donated every
year for 5 years

// Calculate the total amount donated by the


organization
const totalDonation = department1 + department2;

// Display the total amount donated


console.log("Total donation to the disaster relief fund:
$" + totalDonation);

56
1/23/2024

The output will look like

Total donation to the disaster relief fund: $114000

57

Challenge 3

Create a program for the following using JavaScript:

a) Rick’s robotics school is at a distance of 6 km and 250 m from his home. He travels 2 km
and 60 m on foot and the rest on his bicycle. Create a program to calculate the distance he
covers on his bicycle.
b) Sana completes 15 laps around the triangular field of her school, with sides measuring 22
m, 35 m, and 40 m. Create a program to calculate the entire distance she travels.

(Hint: Use variables to store the given values and use the necessary arithmetic operator to
solve the problem.)

58
1/23/2024

Challenge 3 - Solution
Solution:

A sample solution is given below:

Step 1: Open Chrome's Console.

Step 2: For Rick's distance calculation, the total distance from home to school is given in
meters as TotalDistance. The distance traveled on foot is given as distanceOnFoot.

Step 3: Subtract the distance on foot from the total distance, to calculate the distance Rick
covers on his bicycle.

Step 4: Store the result in the variable distanceOnBicycle and print it to the console.

59

// Rick's distance calculation


const TotalDistance = 6250; // Distance from home to
school in meters
const distanceOnFoot = 2060; // Distance traveled on
foot in meters

// Calculate distance on bicycle


const distanceOnBicycle = TotalDistance -
distanceOnFoot;

console.log("Rick covers " + distanceOnBicycle + "


meters on his bicycle.");

60
1/23/2024

The output will look like


Rick covers 4190 meters on his bicycle.

61

b) Step 1: Open Chrome's Console.

Step 2: For Sana's distance calculation, the number of laps around the triangular field is
given as lapCount, and the lengths of the three sides of the field are given as side1, side2, and
side3.

Step 4: Calculate the perimeter of the triangular field by multiplying the sum of the three
sides by the number of laps.

Step 5: Store the result in the variable perimeter and print it to the console.

62
1/23/2024

// Sana's distance calculation


const lapCount = 15;
const side1 = 22; // Length of the first side of the
triangular field in meters
const side2 = 35; // Length of the second side of the
triangular field in meters
const side3 = 40; // Length of the third side of the
triangular field in meters

// Calculate the perimeter of the triangular field


const perimeter = lapCount * (side1 + side2 + side3);

console.log("Sana travels a total distance of " +


perimeter + " meters.");

63

The output will look like


Sana travels a total distance of 1455 meters.

64

You might also like