Comp Computer Science

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, or var before use.
  • Operators perform calculations (+, -, *, /) and comparisons (==, ===, >) on data.
  • Functions are reusable blocks of code that perform specific tasks when called.
  • Event handlers like onclick trigger 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:

HTML (Structure)Static ContentCSS (Style)Styled ContentJavaScript (Behavior)Dynamic Content
Interaction between HTML, CSS, and JavaScript in a webpage lifecycle

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:

  1. Inline (inside HTML tags):
    <button onclick="document.write('Button clicked!')">Click</button>
    
  2. Internal (inside <script> in HTML):
    <script>
        function greet() {
            alert("Welcome!");
        }
    </script>
    <button onclick="greet()">Greet</button>
    
  3. External (in a separate .js file):
    • Link the file in HTML:
      <script src="script.js"></script>
      
    • Write code in script.js:
      function showTime() {
          alert("Current time: " + new Date());
      }
      

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; // Allowed
    
  • const (cannot be changed):
    const PI = 3.14;
    PI = 3.1416; // Error! Cannot reassign.
    
  • var (older method, avoid in modern JS):
    var name = "John";
    
08162431var name = 'John'16 bitslet firstName = 'Rohan'16 bitslet lastName = 'Karki'16 bitslet age = 2016 bitslet isActive = true16 bits
Variable declarations in JavaScript (modern vs. legacy)

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.

08162431x (10)8 bitsy (3)8 bitsx + y8 bitsx - y8 bitsx * y8 bitsx % y8 bits
Arithmetic operations with x=10, y=3 (modulo example highlighted)

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.

Function CallFunction DefinitionExecution ContextReturn Value
How JavaScript functions execute (call stack flow)

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:

  1. Browser Console (F12 or Ctrl+Shift+I):
    • Open DevTools → Console tab.
    • Type console.log("Hello") to print messages.
  2. 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:

  1. User enters two numbers.
  2. Clicking "Add" calls addNumbers().
  3. The function reads the inputs, converts them to numbers, adds them, and displays the result.

NEB Board-Style Questions

Short Answer Questions

  1. What is the difference between == and === in JavaScript?

    • == checks value only (type ignored).
    • === checks value and type (strict equality).
  2. Write a JavaScript function to check if a number is even or odd.

    function checkEvenOdd(num) {
        return num % 2 === 0 ? "Even" : "Odd";
    }
    
  3. What is the output of the following code?

    console.log(typeof "10" + 5);
    
    • Output: "105" (string concatenation).

Programming Questions

  1. 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();
    
  2. 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

  1. JavaScript is a compiled language. (False: It’s interpreted.)
  2. The const keyword allows reassignment of a variable. (False: const is immutable.)

Exam Tip

  1. Syntax Matters:

    • Always use let or const for variables (avoid var).
    • End statements with ; (though JS often ignores this).
  2. Practice Writing Functions:

    • NEB often asks for simple functions (e.g., "Write a function to find the largest of two numbers").
  3. Understand Events:

    • Know how onclick, onload, and onchange work. Example questions may ask you to write event handlers.
  4. Debugging is Key:

    • Learn to use console.log() to trace variable values during exams.
  5. Mix HTML, CSS, and JS:

    • Questions may combine all three (e.g., "Create a button that changes text color when clicked").
  6. Common Pitfalls:

    • Watch for type errors (e.g., "5" + 2 gives "52", not 7).
    • Remember that arrays start at index 0 (e.g., colors[0] is the first element).

Based on the NEB +2 Management syllabus for Computer Science (Comp), unit 10.

Discussion

Loading…