0% found this document useful (0 votes)
4 views18 pages

JavaScript Basics for Grade 10 Students

Uploaded by

byarfarhan7
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views18 pages

JavaScript Basics for Grade 10 Students

Uploaded by

byarfarhan7
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

COMPUTER LESSON

JAVA

Script

BOOK COVER
Grade 10
CHAPTER - 1 - Intro to python

Lesson 1 - Programming
Computer programming is like a secret language that lets you talk to computers. It's all about
giving computers instructions, like a recipe, so they can do things for you. These instructions
are called programs, and they're made up of a series of steps that computers can follow.
Imagine you want to make a website. You need to tell the computer what you want it to look
like and how it should work. You do this by writing code in a special language that computers
understand. There are many different programming languages, just like there are many
different human languages.
Learning to program is like learning any other language. It takes time and practice. But once
you get the hang of it, you can do amazing things. You can create your own games, build
websites, or even write programs that can solve complex problems.

Computer programming languages are like different ways to talk to a computer. Some
languages are easier to understand for humans, while others are more like the computer's
native language. These languages are grouped into different levels based on how much they
resemble human language.
High-level programming languages are like speaking English to a computer. They use words
and phrases that are easier for humans to understand, even if the computer doesn't
understand them directly. These languages need to be translated into a lower-level language
that the computer can understand. Examples of high-level languages include Python, Java,
and C++.
Low-level programming languages are like speaking in a code that the computer understands
directly. They use numbers and symbols that are difficult for humans to read. These
languages are closer to the computer's hardware and give programmers more control over
how the computer works. Examples of low-level languages include machine code and
assembly language.

1
Lesson 2 - Intro to JavaScript
Introduction to JavaScript: Alerts, Prompts, and Comments
JavaScript is a powerful programming language that is widely used to create interactive
effects within web browsers. In this section, we will explore three essential features of
JavaScript: alerts, prompts, and comments. Understanding these components will help you
write more effective and user-friendly code.

Alerts
An alert is a way to display a message to users. When an alert is triggered, a small dialog box
appears on the screen with a message and an "OK" button. This is useful for notifying users
about important information or errors in the program. You can create an alert using the
following syntax:
alert("This is an alert message!");
When this code runs, it shows a dialog box with the message "This is an alert message!" and
the user must click "OK" to continue.

Prompts
A prompt is similar to an alert, but it allows users to input information. When a prompt is
displayed, it shows a dialog box with a message and a text field where users can type their
response. The input can then be stored in a variable for further use. Here’s how you can
create a prompt:
var userResponse = prompt("Please enter your name:");
In this example, the user will see a dialog box asking them to enter their name. Whatever
name they type will be saved in the variable userResponse, which can be used later in your
code.

Comments
Comments are essential for making your code easier to read and understand. They allow you
to write notes within your code that explain what certain parts do. Comments are ignored by
the computer, so they don’t affect how your program runs. In JavaScript, there are two types
of comments:
[Link]-line comments start with //. Everything after // on that line is a comment.
// This is a single-line comment
Using comments effectively can help others (and yourself) understand your code better,
especially when you return to it after some time.

Conclusion
In summary, alerts, prompts, and comments are fundamental features of JavaScript that
enhance user interaction and improve code readability. Alerts notify users, prompts gather
input, and comments provide clarity to your code. By mastering these elements, you can
create more engaging and user-friendly web applications.
Practice using these features in your own JavaScript projects to see how they can improve
the user experience!
2
Lesson 2 - Displaying Messages with Alerts in JavaScript

Introduction to JavaScript Alerts


In JavaScript, an alert is a pop-up message box that can display a message to the user. It’s
often used to give users information or warnings when they interact with a webpage.
Creating an Alert
To create an alert, use the alert() function in JavaScript. The message you want to show goes
inside the parentheses (), and it must be in quotation marks (either double quotes " or single
quotes ').
Example: alert("Hello, welcome to JavaScript!");
This line of code will pop up a message saying "Hello, welcome to JavaScript!"

Understanding Strings
A string is simply text in JavaScript. Strings can be any words or characters you want to
display, and they must be inside quotation marks. You can use either double quotation marks
(") or single quotation marks (') for strings in JavaScript.
Double Quotes Example: alert("This is a message with double quotes.");

Single Quotes Example: alert('This is a message with single quotes.');


Tip: Make sure that if you start with double quotes, you end with double quotes, and the same
goes for single quotes. If you mix them, JavaScript will give you an error!
Creating a New Line
To make the text in an alert appear on different lines, you can use the newline character \n
inside the string. When JavaScript sees \n, it knows to start a new line in the alert box.
Example: alert("Hello!\nWelcome to JavaScript programming.\nLet's learn
together!");

Output:

3
Lesson 3 - Understanding JavaScript: Math Calculations and Order
of Operations
Math Calculations in JavaScript
JavaScript is great for performing math calculations, from simple addition and subtraction to
more complex operations. In JavaScript, you can use symbols (called operators) to perform
math with numbers.

The modulus operator (%) returns the remainder when one number is divided by another. For
example, 10 % 3 equals 1 because 10 divided by 3 leaves a remainder of 1.
Order of Operations
Just like in regular math, JavaScript follows a set of rules called the order of operations to
decide which calculations to do first.
The order of operations is often remembered with the acronym PEMDAS:
[Link] ()
[Link] (JavaScript uses ** for exponents, e.g., 2 ** 3 is 8)
[Link] * and Division /
[Link] + and Subtraction -
Operations inside parentheses are done first, followed by exponents, then multiplication and
division, and finally addition and subtraction.

Conclusion
In JavaScript, understanding how to perform math calculations and the order of operations is
essential for writing effective code. By mastering these concepts, you will be better equipped
to tackle more complex programming challenges in the future. Remember to practice using
these operations and the order of operations to become comfortable with JavaScript math
calculations!

4
Questions
Section 1: Multiple Choice Questions (5 points)
1- What is a programming language?
a) A way to communicate with other humans
b) A set of instructions to tell a computer what to do
c) A system to organize files on a computer
d) A software application used for editing text
2- Which of the following is a high-level programming language?
a) Assembly b) Machine Code c) Python d) Binary
3-What does the alert() function in JavaScript do?
a) Collects user input b) Displays a pop-up message to the user
c) Saves a variable d) Starts a new line in the program
4-Which of the following symbols is used for comments in JavaScript?
a) # b) // c) /* */ d) All of the above
5- What does the modulus operator (%) do in JavaScript?
a) Multiplies two numbers b) Divides two numbers
c) Returns the remainder of a division operation d) Adds two numbers

Section 2: Short Answer (10 points)


[Link] is the difference between a high-level and a low-level programming
language? Provide one example of each.
[Link] are comments important in programming?
[Link] happens when you use incorrect quotation marks in a string in JavaScript?
[Link] the concept of "order of operations" in JavaScript and why it's
important when performing math calculations.
[Link] does the modulus operator work in JavaScript? Provide an example.

Section 3: Fill in the Blanks (5 points)


[Link] _________() function in JavaScript allows you to display a message in a pop-up
box.
[Link] JavaScript, strings must be enclosed in ________ (either single or double).
[Link] order of operations in JavaScript follows the acronym ________.
[Link] get the remainder of 15 divided by 4 in JavaScript, you would use the ________
operator.
[Link] ________ function in JavaScript lets the user enter input into a dialog box.

5
Lesson 4 - Understanding JavaScript Variables
Variables act like containers that store data values. This allows programmers to use, modify,
and retrieve data throughout their code. Let's dive into what variables are and how to use
them in JavaScript.

Variable
A variable is a symbolic name for a value. You can think of it as a box that can hold data. You
can put something in the box, take it out, or even change what’s inside. In JavaScript,
variables can store different types of data, such as:
Numbers: Whole numbers or decimals.
Strings: Text wrapped in quotes.
Booleans: True or false values.

Declaring Variables
To create a variable in JavaScript, you need to use a keyword followed by the variable name.
The most common keywords are var, let, and const. Here’s how you can declare variables:
var age = 14; // Declaring a variable with `var`
var: This keyword is used to declare a variable that can be updated later in the code.

Using Variables
Once you have declared a variable, you can use it in your code. For example, if you want to
display the variable name in an alert box, you can do it like this:
alert(name); // This will show an alert box with the name "Alex".
You can also perform operations with variables. Here’s an example using numbers:
var num1 = 5;
var num2 = 10;
var sum = num1 + num2; // sum will hold the value 15
Variable Naming Rules
When creating variable names, you must follow certain rules:
[Link] with a letter, dollar sign ($), or underscore (_): For example, myVariable, $amount, or
_temp.
[Link] spaces: Use camelCase or underscores instead. For example, myVariable or
my_variable.
[Link] reserved words: Words like if, else, function, etc., cannot be used as variable names.

Conclusion
Variables are a crucial part of programming in JavaScript. They allow you to store and
manipulate data easily. By declaring variables with var, let, and const, you can manage your
data effectively. Remember to follow the naming rules to make your code clear and
functional. By mastering variables, you will be well on your way to writing efficient JavaScript
code!
6
Lesson 5 - Understanding Programming Errors
Programming is a skill that involves writing code to create software, apps, and websites.
However, when you write code, it’s common to encounter problems known as programming
errors or "bugs." Understanding these errors is essential for anyone learning to code. This
guide will help you identify and resolve some common programming errors.

Types of Programming Errors


1. Syntax Errors: These occur when the code does not follow the rules of the programming
language. For example, missing a semicolon at the end of a statement in languages like Java
or C++ can cause a syntax error.
2. Runtime Errors: These errors happen while the program is running, often due to invalid
operations. For example, trying to divide a number by zero will cause a runtime error.
3. Logic Errors: These are mistakes in the code that cause it to behave incorrectly, even if it
runs without crashing. Logic errors can be tricky to find because the program doesn’t show
any error messages.

How to Debug Your Code


Debugging is the process of finding and fixing errors in your code. Here are some steps you can
take to debug effectively:
[Link] the Error Message: When your code doesn’t work, pay close attention to any error
messages. They often indicate where the problem is.
[Link] Your Syntax: Look for missing punctuation, incorrect keywords, or mismatched
parentheses.
[Link] Print Statements: Add print statements to your code to check the value of variables at
different points. This can help you understand where your logic might be failing.
[Link] Down Your Code: If your code is complex, try breaking it down into smaller parts.
Test each part separately to ensure it works before combining them.
[Link] for Help: If you’re stuck, don’t hesitate to ask for help from classmates, teachers, or
online coding communities.

Conclusion
Programming errors are a normal part of coding. By learning about different types of errors
and how to debug your code, you will become a more effective programmer. Remember,
every error is an opportunity to learn and improve your skills!

7
Lesson 6 - Understanding Selection in JavaScript
In programming, making decisions is an essential skill. In JavaScript, we use selection
statements to control the flow of our programs based on certain conditions. This guide will
help you understand how to use if, else, and else if statements in JavaScript to make your
programs more interactive and responsive.
What is Selection?
Selection allows your program to choose different paths based on specific conditions. For
instance, if a student’s score is above a certain number, they might pass a class; otherwise,
they might fail. This decision-making process is crucial in programming and is achieved using
conditional statements.
The if Statement
The if statement is the simplest form of selection. You use it to test a condition. If the
condition is true, the code inside the if block runs. If it’s false, the program skips that block.
Here’s an example:
var score = 85;
if (score >= 70) {
alert("You passed the class!");
}
In this example, since the score is 85, which is greater than 70, the message "You passed the
class!" will be printed to the console.
The else Statement
Sometimes, we want to perform an action when the if condition is not met. This is where the
else statement comes in. It provides an alternative action when the if condition is false.
Here’s how it looks:
var score = 65;
if (score >= 70) {
alert("You passed the class!");
} else {
alert("You failed the class.");
}
In this case, since the score is 65, the program will execute the code in the else block and
print "You failed the class."
The else if Statement
If you have multiple conditions to check, you can use else if. This allows you to test several
conditions in sequence. If the first condition is false, the program will check the next one.

8
Here is an example:
var score = 85;
if (score >= 90) {
alert("You got an A!");
} else if (score >= 80) {
alert("You got a B!");
} else if (score >= 70) {
alert("You got a C!");
} else {
alert("You need to improve.");
}
In this case, since the score is 85, the program will print "You got a B!" because the
first condition (score >= 90) is false, but the second condition (score >= 80) is true.

Conclusion
Understanding how to use if, else, and else if statements is vital for writing effective
JavaScript programs. These selection statements enable you to control how your program
responds to different situations. By mastering these concepts, you can create interactive
applications that react to user input or other variables.
As you practice these concepts, try creating your own programs that utilize these selection
statements. Experiment with different conditions and combinations to see how they affect
the flow of your code. Happy coding!

9
CHAPTER - 2 - Conditions

Lesson 1 - Understanding if Statements in JavaScript


In JavaScript, we often need to check if certain conditions are met before running specific
code. One way to do this is by using an if statement. Let’s explore how it works with a simple
example.
Example: Checking a Password
Consider the following code:

Breaking it down:
[Link] first line asks the user to enter a password using the prompt() function. The user's
input is then stored in a variable called guess.
[Link] if statement on line 3 checks whether the value stored in guess is equal to "Firewall".
[Link] the condition is true (meaning the user entered "Firewall"), the alert() function runs,
displaying the message "Access granted!"
[Link] the user enters anything other than "Firewall", the alert does not appear, and the
program simply moves on.

Understanding == vs. =
It is important to understand the difference between == (double equals) and = (single equals):
= (single equals) is used to assign a value to a variable. For example:
let password = "Firewall"; // Assigning the value "Firewall" to the variable password
== (double equals) is used inside an if statement to compare two values. For example:
if (guess == "Firewall") { ... } // Checking if guess is equal to "Firewall"
Note:
Using = instead of == inside an if statement will cause errors because the condition won’t
work as expected.

10
Lesson 2 - Using if...else Statements in JavaScript
In JavaScript, we can use an if...else statement to check multiple conditions and execute
different code depending on the result. Let’s modify our previous password example to check
for two possible passwords:

Breaking it down:
[Link] user is prompted to enter a password, and their response is stored in the guess
variable.
[Link] if statement checks if guess is equal to "Firewall" or "Secure123". The || (double pipe)
symbol represents OR, meaning that if the user enters either "Firewall" or "Secure123",
they will be granted access.
[Link] the user enters anything other than these two passwords, the else block runs,
displaying the message "Incorrect!"

Understanding if...else
if (condition) → Runs if the condition is true.
else → Runs if the condition is false.
|| (OR operator) → Allows us to check multiple conditions.

Using {} to Group Multiple Commands


In JavaScript, when an if condition is met, we can execute multiple statements by
surrounding them with curly braces {}.

Why Use {}?


Curly braces {} group multiple statements inside an if block.
If you don’t use {}, only the first line after if will be part of the condition.

11
Lesson 3 - Understanding Boolean Logic in JavaScript
What is a Boolean?
A Boolean (pronounced boo-lee-an) is a special type of value that can be either true or false.

Comparison Operators
JavaScript provides several operators to compare values:

Using {} to Group Multiple Commands


In JavaScript, when an if condition is met, we can execute multiple statements by
surrounding them with curly braces {}.

Logical Operators: AND (&&), OR (||), and NOT (!)


Logical operators allow us to combine multiple conditions and evaluate them as true or false.
AND (&&) – Both conditions must be true
The && (AND) operator returns true only if both values are true. If either value is false, the
result is false.
OR (||) – At least one condition must be true
The || (OR) operator returns true if at least one of the values is true. It only returns false if
both values are false.
NOT (!) – Reverses a Boolean value
The ! (NOT) operator negates a Boolean value. If something is true, ! makes it false, and vice
versa.
Operator Precedence
The ! (NOT) operator is applied before && (AND) and || (OR).
The && (AND) operator is evaluated before || (OR).
Using < and > with Strings
When comparing text, JavaScript checks the alphabetical order of characters:
12
Lesson 4 - The confirm() Function in JavaScript
Have you ever tried to leave a website and seen a pop-up asking if you're sure you want to
leave? This is done using the confirm() function.
A function is a reusable block of code that performs a specific task. In earlier lessons, we
referred to functions as commands. The confirm() function is built into JavaScript and is
used to display a message with "OK" and "Cancel" buttons.

How confirm() Works


If the user clicks "OK", the function returns true.
If the user clicks "Cancel", it returns false.

Explanation
[Link] confirm() function displays a pop-up with the given message.
[Link] user's response (true for "OK" and false for "Cancel") is stored in the variable
userResponse.
[Link] if statement checks the value:
If true, an alert says "You chose to leave."
If false, an alert says "You decided to stay!"
This function is commonly used to prevent users from accidentally losing data or leaving a
page without saving their progress.

Lesson 5 - Null value in a condition


In JavaScript, when you interact with a prompt box and click the "Cancel" button, the
variable that stores the user's input will be assigned a special value called null. This value
signifies the absence of any input, or that no value was provided.

13
Lesson 6 - Common Mistakes with if Statements in JavaScript
n JavaScript, one of the most common mistakes when writing if statements is making small
errors that can be difficult to spot. Often, the error is not on the exact line indicated by the
error message, but rather a few lines before it. This can be confusing, and understanding why
this happens requires a bit of insight into how JavaScript reads and processes code.
Here are some key points to help you avoid common mistakes when using if statements:
1- Misplaced or Missing Parentheses
When using if statements, ensure that the condition inside the parentheses ( Brackets )is
correctly formed. Missing or extra parentheses can cause JavaScript to misinterpret your
code.
2- Confusing = (Assignment) with == (Comparison)
One of the most common mistakes is using = instead of ==. The single = sign is used for
assignment, while == is used for comparison.
3- Unexpected Code Flow
Sometimes the error message refers to a line that seems correct. However, the real issue
might be earlier in the code. For example, if a function or variable is not defined or closed
properly earlier, it can affect later parts of the code.

14
CHAPTER - 3 - Loops

Introduction to Loops
In programming, a loop is a control structure that allows code to be repeated multiple times.
Instead of writing the same instruction again and again, we use loops to automate repetition.
This makes the code shorter, easier to manage, and more efficient.
There are several types of loops in JavaScript. In this lesson, we focus on the while loop.
2. The While Loop
A while loop is used when we want to repeat a block of code as long as a certain condition is
true. The syntax is similar to an if statement but it continues running the block of code
repeatedly until the condition becomes false.
Structure of a While Loop

The loop checks the condition before each repetition.


If the condition is true, the code inside the {} runs.
If the condition is false, the loop stops.

3. Example: Loop Until Correct Answer

This loop continues asking the user to enter the correct password. The loop only stops when
the password matches "secret123".

4. Valid and Invalid Input


It is important to test a program with different kinds of input:
Valid Input: Expected and acceptable input (e.g. typing "secret123").
Invalid Input: Unacceptable input such as pressing Cancel or leaving the input blank.
Programs should be tested with both valid and invalid inputs to ensure they behave correctly
in all situations.

15
5. Fixed Number of Repetitions
A loop can also be used to repeat code a fixed number of times. This can be done using a
while loop with a counter.
Example: Counting from 1 to 5

In this example:
The loop starts with number = 1.
Each time the loop runs, number is increased by 1.
The loop ends when number becomes greater than 5.

7. Combining Loop Output into One Message


Instead of printing values one by one, all the values can be combined into a single message.
Example:

This is not a loop, but it shows how output can be combined when required.

8. Efficiency of Loops
Using loops is efficient, especially for repetitive tasks. For example, listing multiples of 5 from
5 to 30,000 manually would take hours. A loop can do this in seconds.
Example: Multiples of 3 from 90 to 300

9. Loop Conditions
The condition in a while loop determines how many times the loop will run. When the
condition is no longer true, the loop stops.
Common Conditions
x < 10: loop continues while x is less than 10.
x !== 5: loop continues while x is not equal to 5.
Increment and Decrement
x = x + 1 increases x by 1.
x = x - 1 decreases x by 1.

16
10. Infinite Loops
A loop that never stops is called an infinite loop. This happens when the condition always
remains true due to a missing or incorrect update in the loop.
Example of an Infinite Loop

Without updating count, the condition count <= 5 always remains true.
11. Skipped Loops
If the initial condition is false, the loop body will never run, not even once.

Since i is not less than 5, the loop is skipped.


12. Counting Down and Up
Loops can also be used to count downward, and then back upward.
Example:
Count from 4 down to 0, then up to 4.

13. Using Loops to Gather User Input


You can use loops to ask the user for information multiple times. For example, to collect
hours worked each day in a week.

17

You might also like