Hello World Program in JavaScript
javascript*// Create a file in Visual Studio Code with .js extension* console.log("Hello World");
To run:
- Open terminal at file location
- Run:
node filename.js(make sure Node.js is installed and set in system variables)
Output:
textHello World
Comments in JavaScript
javascript*// This is a single line comment/**
*This is a multi-line comment */*
Comments don't impact execution.
Variables in JavaScript
JavaScript variables are loosely typed - no explicit data types are needed.
Example of declaring a variable:
**let a = 4;** console.log(a); *// Prints: 4*
To check type of variable:
console.log(typeof a); *// Outputs: "number"*
Variables can be declared with var, let, and const. let and const were introduced in ES6.
var, let, const
var: Function scoped, can be redeclared and reassigned.let: Block scoped, cannot be redeclared, but can be reassigned.const: Block scoped, cannot be redeclared or reassigned (constant).
Example:
let a = 4; a = 5; *// OK*
let a=6; // cannot be redeclared `const b = 10; b = 15; // Error: Assignment to constant variable.
var c = 7; var c = 8; *// Allowed with var` ,*can be redeclared and reassigned.
Use let or const instead of var for better scoping.
Boolean negation operator
let flag = true; console.log(!flag); *// Prints: false*
Negation ! works only with boolean values.
Reassignment and variable declaration
`javascriptlet c = a + b; // Declared once c = a + b; // Reassignment allowed without let keyword
let c = a + b; // Error: 'c' already declared`
Loops in JavaScript
while loop
let i = 0; while (i < 10) { console.log(i); i++; }
Infinite loop caution: Condition must eventually become false.
- The loop starts with
i = 0. - Each iteration prints
iand increases it by 1. - When
ireaches 10, the condition(i < 10)becomes false, so the loop stops.
If you forget to update i, the condition never becomes false, creating an infinite loop.
do-while loop
javascriptlet i = 10; do { console.log(i); i++; } while (i < 10);
Executes once before checking condition.
for loop
for (let i = 0; i <= 10; i++) { console.log(i); }
Use when the number of iterations is known.
Example: Find multiples of 2 and 5
for (let k = 1; k <= 10; k++) { if (k % 2 === 0 && k % 5 === 0) { console.log(k); } } *// Output: 10*
break statement example
let n = 0; for (let k = 1; k <= 100; k++) { if (k % 2 === 0 && k % 5 === 0) { n++; console.log(k); if (n === 3) break; *// Stop after first 3 matches* } }
- The loop runs from
k = 1tok = 100. - Inside, the condition
(k % 2 === 0 && k % 5 === 0)checks whetherkis divisible by both 2 and 5 (which means divisible by 10). - Each valid match increases
nby 1 and printsk. - Once
nreaches 3, thebreakstatement exits the loop early.
So the output stops after printing the first 3 such numbers (10, 20, 30).
Arrays in JavaScript
Declaring and initializing an array
javascriptlet marks = new Array(6); marks = [20, 40, 35, 45, 50, 37];
Or simply:
javascriptlet marks = [20, 40, 35, 45, 50, 37];
Accessing array elements
javascriptconsole.log(marks[2]); *// Outputs: 35*
Updating array element
javascriptmarks[3] = 14; *// Change fourth element to 14* console.log(marks);
Array length
javascriptconsole.log(marks.length); *// Outputs: 6*
Adding/removing elements
javascriptmarks.push(65); *// Add 65 at the end* marks.pop(); *// Removes last element* marks.unshift(12); *// Add 12 at beginning*
Array methods: indexOf, includes, slice
javascriptconsole.log(marks.indexOf(35)); *// Get index of 35* console.log(marks.includes(120)); *// false - if 120 not found* let subMarks = marks.slice(2, 5); *// elements from index 2 to 4*
Loop to sum array elements
javascriptlet sum = 0; for(let i = 0; i < marks.length; i++) { sum += marks[i]; } console.log(sum);
Using reduce
javascriptlet totalMarks = marks.reduce((sum, mark) => sum + mark, 0); console.log(totalMarks);
Filtering even numbers from an array
javascriptlet scores = [12, 13, 14, 16]; let evenScores = []; for(let i = 0; i < scores.length; i++) { if(scores[i] % 2 === 0) { evenScores.push(scores[i]); } } console.log(evenScores); *// [12, 14, 16]*
Using filter method
javascriptlet evenScores = scores.filter(score => score % 2 === 0); console.log(evenScores);
Mapping over array elements
Multiply evens by 3:
javascriptlet mappedScores = evenScores.map(score => score * 3); console.log(mappedScores);
Combining filter, map, reduce
`javascriptlet result = scores .filter(score => score % 2 === 0) .map(score => score * 3) .reduce((total, score) => total + score, 0);
console.log(result);`
Sorting
Sorting strings
javascriptlet fruits = ['Banana', 'Mango', 'Apple']; fruits.sort(); console.log(fruits);
Sorting numbers (with custom comparator)
`javascriptlet numbers = [12, 3, 19, 16, 14]; numbers.sort((a, b) => a - b); console.log(numbers); // Ascending order
numbers.sort((a, b) => b - a); console.log(numbers); // Descending order`
Functions in JavaScript
Named function
function add(a, b) { return a + b; } let result = add(2, 3); console.log(result); *// 5*
Anonymous function assigned to variable
let add = function(a, b) { return a + b; }; console.log(add(2, 3)); *// 5*
Arrow function (ES6)
let add = (a, b) => a + b; console.log(add(2, 3)); *// 5*
Variable scope differences: var vs let vs const
varis function scopedletandconstare block scoped
Example problem with var:
`javascriptif (true) { var grade = "Afternoon"; // var scoped outside block } console.log(grade); // Prints "Afternoon"
if (true) { let grade = "Evening"; // let scoped inside block } console.log(grade); // Error if grade not declared outside block`
Strings in JavaScript
javascriptlet day = "Tuesday"; console.log(day.length); *// String length// Substring with slice* let sub = day.slice(0, 4); *// 'Tues'// Access character by index* console.log(day[1]); *// 'u'// Split string* let parts = day.split('s'); *// splits at 's'// Trim whitespace* let rawString = " hello "; console.log(rawString.trim()); *// 'hello'*
Converting string to number and vice versa
javascriptlet str = "27"; let num = parseInt(str); console.log(num - 23); *// Subtract numbers correctly* console.log(num.toString()); *// Convert back to string*
Objects in JavaScript
`javascriptlet person = { firstName: "John", lastName: "Doe", gender: "Male" };
// Access properties console.log(person.firstName); console.log(person['lastName']);
// Update property person.firstName = "Tim";
// Add new property person.age = 30;
// Delete property delete person.gender;
// Check if property exists console.log('gender' in person); // false after deletion// Iterate properties for (let key in person) { console.log(key + ": " + person[key]); }`
Object methods (functions as properties)
`javascriptlet person = { firstName: "Tim", lastName: "Smith", fullName: function() { return this.firstName + " " + this.lastName; } };
console.log(person.fullName()); // Call function property`
Classes in JavaScript (ES6)
`javascriptclass Person { constructor(firstName, lastName) { this.firstName = firstName; // instance variable this.lastName = lastName; // instance variable }
fullName() { return this.firstName + " " + this.lastName; }
get location() { return "Canada"; // getter property } }
// Create instance const p1 = new Person("Tim", "Joseph"); console.log(p1.fullName()); console.log(p1.location);`
Exporting and importing classes in Node.js
Export class:
javascriptmodule.exports = Person;
Import and use in another file:
`javascriptconst Person = require('./Person');
const p1 = new Person("Chris", "Edward"); console.log(p1.fullName());`
Inheritance in JavaScript classes
`javascriptconst Person = require('./Person');
class Pet extends Person { constructor(firstName, lastName) { super(firstName, lastName); // Call parent's constructor }
get location() { return "Blue Cross"; // Override parent's location } }
const pet1 = new Pet("Sam", "Sam"); console.log(pet1.fullName()); // Inherited method console.log(pet1.location); // Overridden property`
0 Comments