Computer ScienceUnit 1011 min read
JavaScript Basics: Syntax, Variables, Operators & Simple Scripts
Unit 10 of Computer Science introduces JavaScript basics for web development, covering syntax rules, variable types, operators, and writing simple interactive scripts for HTML pages.
TAKEAWAYS:
- JavaScript is a scripting language that makes web pages dynamic by adding interactivity without requiring page reloads.
- Variables store data (numbers, text, etc.) and must be declared with
let,const, orvarbefore use. - Operators perform calculations (
+,-,*,/) and comparisons (==,===,>) on data. - Functions are reusable blocks of code that perform specific tasks when called.
- Event handlers like
onclicktrigger JavaScript code when users interact with page elements. - Debugging tools (browser console) help fix errors in JavaScript code.
What is JavaScript?
JavaScript (JS) is a programming language that runs in web browsers. It adds interactivity to websites, such as:
- Changing content dynamically (e.g., updating a clock without refreshing the page).
- Validating user input (e.g., checking if a form is filled correctly).
- Creating animations or games.
Why is it important? Without JavaScript, websites would be static (like plain HTML pages). JS brings them to life!
How JavaScript Works with HTML and CSS
JavaScript works alongside HTML (structure) and CSS (design). Here’s how they interact:
Example: An HTML button with JavaScript:
<button onclick="alert('Hello!')">Click Me</button>
When clicked, it shows an alert box with "Hello!" without reloading the page.
Writing JavaScript Code
JavaScript can be written in three ways:
- Inline (inside HTML tags):
<button onclick="document.write('Button clicked!')">Click</button> - Internal (inside
<script>in HTML):<script> function greet() { alert("Welcome!"); } </script> <button onclick="greet()">Greet</button> - External (in a separate
.jsfile):- Link the file in HTML:
<script src="script.js"></script> - Write code in
script.js:function showTime() { alert("Current time: " + new Date()); }
- Link the file in HTML:
Variables in JavaScript
Variables store data (like names, numbers, or true/false values). To declare a variable, use:
let(can be changed later):let age = 20; age = 21; // Allowedconst(cannot be changed):const PI = 3.14; PI = 3.1416; // Error! Cannot reassign.var(older method, avoid in modern JS):var name = "John";
Example: Variable Usage
let firstName = "Rohan";
let lastName = "Karki";
let fullName = firstName + " " + lastName;
console.log(fullName); // Output: "Rohan Karki"
Data Types in JavaScript
JavaScript has primitive (simple) and non-primitive (complex) data types:
| Type | Example | Description |
|---|---|---|
| String | "Hello" |
Text data (use quotes). |
| Number | 42, 3.14 |
Integers or decimals. |
| Boolean | true, false |
True/False values. |
| Undefined | let x; |
Variable declared but not assigned. |
| Null | null |
Intentional empty value. |
| Object | {name: "Alice"} |
Stores key-value pairs (e.g., JSON). |
| Array | [1, 2, 3] |
Ordered list of values. |
Example: Different Data Types
let text = "JavaScript"; // String
let count = 100; // Number
let isActive = true; // Boolean
let person = {name: "Bob"}; // Object
let colors = ["red", "green"]; // Array
Operators in JavaScript
Operators perform operations on variables and values.
1. Arithmetic Operators
| Operator | Example | Description |
|---|---|---|
+ |
5 + 3 |
Addition |
- |
5 - 3 |
Subtraction |
* |
5 * 3 |
Multiplication |
/ |
6 / 2 |
Division |
% |
5 % 2 |
Modulus (remainder) |
Example:
let x = 10, y = 3;
console.log(x + y); // 13
console.log(x % y); // 1 (remainder)
2. Comparison Operators
| Operator | Example | Description |
|---|---|---|
== |
5 == "5" |
Equal (type ignored) |
=== |
5 === "5" |
Strict equal (type checked) |
!= |
5 != 3 |
Not equal |
> |
10 > 5 |
Greater than |
Example:
console.log(5 == "5"); // true (value same, type ignored)
console.log(5 === "5"); // false (types differ)
3. Logical Operators
| Operator | Example | Description |
|---|---|---|
&& |
true && false |
AND (both true) |
| ` | ` | |
! |
!true |
NOT (inverts value) |
Example:
let age = 18;
let hasID = true;
console.log(age >= 18 && hasID); // true (both conditions met)
Functions in JavaScript
Functions are reusable blocks of code that perform a task. They are defined with function and called by name.
Syntax:
function functionName(parameters) {
// Code to execute
return value; // Optional
}
Example: Simple Function
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Alice")); // Output: "Hello, Alice!"
Example: Function with No Return
function showAlert() {
alert("This is an alert!");
}
showAlert(); // Shows alert when called
Event Handling
Events are actions (like clicks or keypresses) that trigger JavaScript code. Common events:
onclick: When a button is clicked.onload: When a page finishes loading.onchange: When a dropdown value changes.
Example: Button Click Event
<button onclick="changeText()">Click Me</button>
<p id="demo">Original text</p>
<script>
function changeText() {
document.getElementById("demo").innerHTML = "Text changed!";
}
</script>
When the button is clicked, the paragraph text updates.
Debugging JavaScript
Debugging means finding and fixing errors in code. Use:
- Browser Console (
F12orCtrl+Shift+I):- Open DevTools → Console tab.
- Type
console.log("Hello")to print messages.
- Alerts (
alert()):alert("Error: Invalid input!");
Example: Debugging with console.log
let a = 5;
let b = 10;
console.log("Sum:", a + b); // Output: Sum: 15
Common Errors and Fixes
| Error | Cause | Fix |
|---|---|---|
Uncaught ReferenceError |
Using a variable before declaring it. | Declare variables with let or const. |
NaN (Not a Number) |
Invalid math operation (e.g., "5" + 3). |
Convert strings to numbers with Number() or parseInt(). |
| SyntaxError | Missing ; or } in code. |
Check for missing brackets or typos. |
Example: Fixing NaN
let x = "5";
let y = 3;
console.log(x + y); // "53" (concatenation)
console.log(Number(x) + y); // 8 (correct addition)
Practical Example: Simple Calculator
Let’s build a calculator that adds two numbers:
<!DOCTYPE html>
<html>
<head>
<title>JS Calculator</title>
</head>
<body>
<h2>Add Two Numbers</h2>
<input type="number" id="num1" placeholder="Enter first number">
<input type="number" id="num2" placeholder="Enter second number">
<button onclick="addNumbers()">Add</button>
<p id="result"></p>
<script>
function addNumbers() {
let num1 = Number(document.getElementById("num1").value);
let num2 = Number(document.getElementById("num2").value);
let sum = num1 + num2;
document.getElementById("result").innerHTML = "Result: " + sum;
}
</script>
</body>
</html>
How it works:
- User enters two numbers.
- Clicking "Add" calls
addNumbers(). - The function reads the inputs, converts them to numbers, adds them, and displays the result.
NEB Board-Style Questions
Short Answer Questions
What is the difference between
==and===in JavaScript?==checks value only (type ignored).===checks value and type (strict equality).
Write a JavaScript function to check if a number is even or odd.
function checkEvenOdd(num) { return num % 2 === 0 ? "Even" : "Odd"; }What is the output of the following code?
console.log(typeof "10" + 5);- Output:
"105"(string concatenation).
- Output:
Programming Questions
Write a JavaScript program to display the current date and time.
function showDateTime() { let now = new Date(); document.write("Current date and time: " + now); } showDateTime();Create a function that takes a name as input and greets the user.
function greetUser(name) { alert("Hello, " + name + "! Welcome to our website."); } greetUser("Ramesh");
True/False
- JavaScript is a compiled language. (False: It’s interpreted.)
- The
constkeyword allows reassignment of a variable. (False:constis immutable.)
Exam Tip
Syntax Matters:
- Always use
letorconstfor variables (avoidvar). - End statements with
;(though JS often ignores this).
- Always use
Practice Writing Functions:
- NEB often asks for simple functions (e.g., "Write a function to find the largest of two numbers").
Understand Events:
- Know how
onclick,onload, andonchangework. Example questions may ask you to write event handlers.
- Know how
Debugging is Key:
- Learn to use
console.log()to trace variable values during exams.
- Learn to use
Mix HTML, CSS, and JS:
- Questions may combine all three (e.g., "Create a button that changes text color when clicked").
Common Pitfalls:
- Watch for type errors (e.g.,
"5" + 2gives"52", not7). - Remember that arrays start at index
0(e.g.,colors[0]is the first element).
- Watch for type errors (e.g.,
Based on the NEB +2 Management syllabus for Computer Science (Comp), unit 10.
Discussion
Loading…