cs
cs
1 JavaScript Syntax
1. What is JavaScript?
● JavaScript is a client-side scripting language that adds interactivity to web pages.
● It is loosely typed, meaning variables do not require explicit data types.
● Initially called LiveScript, later renamed JavaScript.
Embedded JavaScript
<script>
document.write("Hello World!");
</script>
External JavaScript
<script src="script.js"></script>
Inline JavaScript
<a href="#" onclick="alert('Hello World!')">Click Me</a>
Tip: Open the console using F12 → Select the "Console" tab.
1. What is a Variable?
● A variable is a container for storing data.
● It can hold different values (numbers, strings, etc.).
● In JavaScript, variables can be declared using var, let, and const.
2. Declaring Variables
Using var (Global or Function Scope, Hoisted)
● Can be reassigned.
● Hoisted (can be used before declaration).
var x; // Declaration
var x = 5; // Initialization
x = 6; // Reassignment
let y = 10;
const z = 25;
// z = 30; //❌Error (cannot reassign)
5. String Operations
Concatenation (+ operator)
let message = "Oh hi, " + "Pisay!";
console.log(message); // "Oh hi, Pisay!"
String Methods
Method Description Example Output
8. Undefined vs Null
Type Description Example Output
undefin A variable that has been declared but not let x; console.log(x); →
ed assigned a value. undefined
4.
5. Display: "You will need NN to last you until the age of X".
● Variables store data and can be declared using var, let, or const.
● Data types include String, Number, Boolean, Undefined, Null, and Symbol.
● Strings can be concatenated using +, .concat(), or template literals ` `.
● Numbers support arithmetic and scientific notation.
● Booleans store true or false values.
● Undefined means a variable has no value, while null is an intentional empty value.
1. Arithmetic Operators
Given: a = 20, b = 30
● Addition (+) → a + b = 50
● Subtraction (-) → a - b = -10
● Multiplication (*) → a * b = 600
● Division (/) → b / a = 1.5
● Modulus (%) → a % b = 20
● Increment (++)
○ ++x → returns new value after increment
○ x++ → returns current value, then increments
● Decrement (--)
○ --x → returns new value after decrement
○ x-- → returns current value, then decrements
● String Concatenation (+) → 5 + "Hello" → "5Hello"
Comparison Operators
Given: a = 20, b = 30
Logical Operators
● Logical AND (&&)
○ true && true → true
○ "cat" && "dog" → "dog"
● Logical OR (||)
○ false || false → false
○ "cat" || "dog" → "cat"
● Logical NOT (!)
○ !(5 == "5") → false
● Falsy values: null, 0, NaN, "", undefined
Assignment Operators
● Basic Assignment (=) → x = y
● Addition Assignment (+=) → x += y → x = x + y
● Subtraction Assignment (-=) → x -= y → x = x - y
● Multiplication Assignment (*=) → x *= y → x = x * y
● Division Assignment (/=) → x /= y → x = x / y
● Modulo Assignment (%=) → x %= y → x = x % y
Evaluation Practice
Given: var a = 10, b = 5, c = "10"
Find x:
1. x = a + c; → "1010"
2. x = (a === c); → false
3. x = a / c; → 1
4. x = (a === b) || !c; → false
5. x = a * b; → 50
6. x = "hello" && a; → 10
7. x = c % a; → 0
8. x = !b && !a; → false
9. x = a * 6; → 60
10.x = a + "Hi"; → "10Hi"
Example:
document.getElementById("demo").innerHTML = "Hello World!";
○ The script must be placed after the selected element to avoid errors.
Example:
let name = prompt("Enter your name:");
alert("Hello, " + name);
Example:
let result = confirm("Do you agree?");
if (result) {
alert("You agreed!");
} else {
alert("You canceled!");
}
Note that:
● window.alert(), window.prompt(), and window.confirm() are valid but window is
optional.
● innerHTML is case-sensitive.
● document.write() is only recommended for testing purposes.
Event Handlers
Event handlers detect and respond to events. They are placed inside an HTML element’s
opening tag:
Examples
Alert Message on Click
<p onclick="alert('So I click you, now what?')">Click Me.</p>
1.
○ Clicking the text will display an alert box.
2.
○ this.innerHTML updates the element’s content.
3.
○ Clicking the image will replace it with img_girl.jpg.
Using a Function:
<img id="image" onclick="changeImage()" src="smiley.gif" width="100">
<script>
function changeImage() {
document.getElementById("image").src = 'img_girl.jpg';
</script>
4.
○ Uses document.getElementById("image") to change the image.
function changeColor() {
document.getElementById("dBody").style.backgroundColor = dColor;
</script>
</body>
● document.getElementById(id).innerHTML
● alert()
<script>
function getSum(a, b) {
sum = a + b;
document.getElementById('div1').innerHTML = sum;
getSum(1,2);
</script>
<script>
function getSum(a, b) {
sum = a + b;
window.alert(sum);
getSum(1,2);
</script>
Note: Variables inside a function are local variables and can only be accessed
within the function block.
<script>
function getSum(a, b) {
sum = a + b;
return sum;
x = getSum(1,2);
</script>
<p id="demo"></p>
<script>
function myFunction() {
while (true) {
if (isNaN(number)) {
return false;
myFunction();
</script>
● The loop continues until a letter (non-numeric input) is entered, then it stops execution.
<div id="demo"></div>
<script>
function getSum(a, b) {
sum = a + b;
return sum;
document.getElementById("demo").innerHTML = getSum(1,2);
</script>
Summary:
● Function outputs can be displayed using alert(),
document.getElementById(id).innerHTML, etc.
● The return statement passes function output to a variable outside the function.
● return can also be used to stop function execution.
● Function outputs can be directly used in print statements or operations.
1. JavaScript Objects
● Objects store multiple values (properties).
● Objects have methods, which are functions specific to them.
Mathematical Constants
Math.SQRT √2 1.414…
2
alert(d);
getDistance(2, 3, 3, 5);
Output: 2.236
Accessing Characters
let name = "Uzumaki Naruto";
console.log(name[0]); // "U"
console.log(name[20]); // undefined
name = name.toUpperCase();
if ("AEIOU".includes(name[i])) {
alert(name);
solveProblem("Uzumaki Naruto");
Number Properties
Property Description Example Output
Number Methods
Method Description Example Output
Creating Dates
let d = new Date(); // Current date and time
let d = new Date(2021, 0, 4, 10, 3, 59); // Jan 4, 2021, 10:03:59
Note:
● Months start from 0 (January = 0, December = 11).
● If only one argument is provided, it's treated as milliseconds since Jan
1, 1970, 00:00:00 UTC.
Sample Output:
Syntax:
if (condition) {
// Executes if condition is true
}
else if (another condition) {
// Executes if first condition is false but second is true
}
else {
// Executes if all previous conditions are false
}
== Equal to a == 2 → TRUE
Logical Operators
Operator Description Example (a = 1, Output
b = 2)
&& (AND) True if both conditions are (a < b && a > TRUE
true 0)
` ` (OR) True if at least one condition
is true
4. Switch Statement
● Used when multiple conditions exist instead of using multiple if-else statements.
Syntax:
switch(expression) {
case value1:
// Executes if expression == value1
break;
case value2:
// Executes if expression == value2
break;
default:
// Executes if none of the cases match
}
Note: break prevents further cases from executing if one case is met.
Syntax:
for (start; condition; increment) {
// Code block to be executed
}